diff --git a/static/pkg/atmosphere/CNAME b/static/pkg/atmosphere/CNAME new file mode 100644 index 00000000..63a8a507 --- /dev/null +++ b/static/pkg/atmosphere/CNAME @@ -0,0 +1 @@ +vrm.syui.ai diff --git a/static/pkg/atmosphere/assets/index-CHT4Xf7A.js b/static/pkg/atmosphere/assets/index-CHT4Xf7A.js new file mode 100644 index 00000000..1e3fb3e0 --- /dev/null +++ b/static/pkg/atmosphere/assets/index-CHT4Xf7A.js @@ -0,0 +1,10476 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const a of r)if(a.type==="childList")for(const s of a.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&i(s)}).observe(document,{childList:!0,subtree:!0});function t(r){const a={};return r.integrity&&(a.integrity=r.integrity),r.referrerPolicy&&(a.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?a.credentials="include":r.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(r){if(r.ep)return;r.ep=!0;const a=t(r);fetch(r.href,a)}})();function aS(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var BU={exports:{}},sS={};/** + * @license React + * react-jsx-runtime.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var VV=Symbol.for("react.transitional.element"),GV=Symbol.for("react.fragment");function FU(n,e,t){var i=null;if(t!==void 0&&(i=""+t),e.key!==void 0&&(i=""+e.key),"key"in e){t={};for(var r in e)r!=="key"&&(t[r]=e[r])}else t=e;return e=t.ref,{$$typeof:VV,type:n,key:i,ref:e!==void 0?e:null,props:t}}sS.Fragment=GV;sS.jsx=FU;sS.jsxs=FU;BU.exports=sS;var ot=BU.exports,HU={exports:{}},qt={};/** + * @license React + * react.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var XA=Symbol.for("react.transitional.element"),kV=Symbol.for("react.portal"),WV=Symbol.for("react.fragment"),XV=Symbol.for("react.strict_mode"),qV=Symbol.for("react.profiler"),YV=Symbol.for("react.consumer"),jV=Symbol.for("react.context"),ZV=Symbol.for("react.forward_ref"),QV=Symbol.for("react.suspense"),KV=Symbol.for("react.memo"),VU=Symbol.for("react.lazy"),JV=Symbol.for("react.activity"),TD=Symbol.iterator;function $V(n){return n===null||typeof n!="object"?null:(n=TD&&n[TD]||n["@@iterator"],typeof n=="function"?n:null)}var GU={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},kU=Object.assign,WU={};function Hp(n,e,t){this.props=n,this.context=e,this.refs=WU,this.updater=t||GU}Hp.prototype.isReactComponent={};Hp.prototype.setState=function(n,e){if(typeof n!="object"&&typeof n!="function"&&n!=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,n,e,"setState")};Hp.prototype.forceUpdate=function(n){this.updater.enqueueForceUpdate(this,n,"forceUpdate")};function XU(){}XU.prototype=Hp.prototype;function qA(n,e,t){this.props=n,this.context=e,this.refs=WU,this.updater=t||GU}var YA=qA.prototype=new XU;YA.constructor=qA;kU(YA,Hp.prototype);YA.isPureReactComponent=!0;var ED=Array.isArray;function BM(){}var li={H:null,A:null,T:null,S:null},qU=Object.prototype.hasOwnProperty;function jA(n,e,t){var i=t.ref;return{$$typeof:XA,type:n,key:e,ref:i!==void 0?i:null,props:t}}function eG(n,e){return jA(n.type,e,n.props)}function ZA(n){return typeof n=="object"&&n!==null&&n.$$typeof===XA}function tG(n){var e={"=":"=0",":":"=2"};return"$"+n.replace(/[=:]/g,function(t){return e[t]})}var bD=/\/+/g;function Q2(n,e){return typeof n=="object"&&n!==null&&n.key!=null?tG(""+n.key):e.toString(36)}function nG(n){switch(n.status){case"fulfilled":return n.value;case"rejected":throw n.reason;default:switch(typeof n.status=="string"?n.then(BM,BM):(n.status="pending",n.then(function(e){n.status==="pending"&&(n.status="fulfilled",n.value=e)},function(e){n.status==="pending"&&(n.status="rejected",n.reason=e)})),n.status){case"fulfilled":return n.value;case"rejected":throw n.reason}}throw n}function Tf(n,e,t,i,r){var a=typeof n;(a==="undefined"||a==="boolean")&&(n=null);var s=!1;if(n===null)s=!0;else switch(a){case"bigint":case"string":case"number":s=!0;break;case"object":switch(n.$$typeof){case XA:case kV:s=!0;break;case VU:return s=n._init,Tf(s(n._payload),e,t,i,r)}}if(s)return r=r(n),s=i===""?"."+Q2(n,0):i,ED(r)?(t="",s!=null&&(t=s.replace(bD,"$&/")+"/"),Tf(r,e,t,"",function(u){return u})):r!=null&&(ZA(r)&&(r=eG(r,t+(r.key==null||n&&n.key===r.key?"":(""+r.key).replace(bD,"$&/")+"/")+s)),e.push(r)),1;s=0;var o=i===""?".":i+":";if(ED(n))for(var l=0;l>>1,se=X[ce];if(0>>1;cer(nt,Q))ttr(xt,nt)?(X[ce]=xt,X[tt]=Q,ce=tt):(X[ce]=nt,X[Xe]=Q,ce=Xe);else if(ttr(xt,Q))X[ce]=xt,X[tt]=Q,ce=tt;else break e}}return te}function r(X,te){var Q=X.sortIndex-te.sortIndex;return Q!==0?Q:X.id-te.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;n.unstable_now=function(){return a.now()}}else{var s=Date,o=s.now();n.unstable_now=function(){return s.now()-o}}var l=[],u=[],d=1,f=null,p=3,m=!1,v=!1,x=!1,S=!1,_=typeof setTimeout=="function"?setTimeout:null,T=typeof clearTimeout=="function"?clearTimeout:null,E=typeof setImmediate<"u"?setImmediate:null;function b(X){for(var te=t(u);te!==null;){if(te.callback===null)i(u);else if(te.startTime<=X)i(u),te.sortIndex=te.expirationTime,e(l,te);else break;te=t(u)}}function R(X){if(x=!1,b(X),!v)if(t(l)!==null)v=!0,w||(w=!0,W());else{var te=t(u);te!==null&&ae(R,te.startTime-X)}}var w=!1,L=-1,U=5,N=-1;function C(){return S?!0:!(n.unstable_now()-NX&&C());){var ce=f.callback;if(typeof ce=="function"){f.callback=null,p=f.priorityLevel;var se=ce(f.expirationTime<=X);if(X=n.unstable_now(),typeof se=="function"){f.callback=se,b(X),te=!0;break t}f===t(l)&&i(l),b(X)}else i(l);f=t(l)}if(f!==null)te=!0;else{var De=t(u);De!==null&&ae(R,De.startTime-X),te=!1}}break e}finally{f=null,p=Q,m=!1}te=void 0}}finally{te?W():w=!1}}}var W;if(typeof E=="function")W=function(){E(z)};else if(typeof MessageChannel<"u"){var K=new MessageChannel,oe=K.port2;K.port1.onmessage=z,W=function(){oe.postMessage(null)}}else W=function(){_(z,0)};function ae(X,te){L=_(function(){X(n.unstable_now())},te)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(X){X.callback=null},n.unstable_forceFrameRate=function(X){0>X||125ce?(X.sortIndex=Q,e(u,X),t(l)===null&&X===t(u)&&(x?(T(L),L=-1):x=!0,ae(R,Q-ce))):(X.sortIndex=se,e(l,X),v||m||(v=!0,w||(w=!0,W()))),X},n.unstable_shouldYield=C,n.unstable_wrapCallback=function(X){var te=p;return function(){var Q=p;p=te;try{return X.apply(this,arguments)}finally{p=Q}}}})(ZU);jU.exports=ZU;var aG=jU.exports,QU={exports:{}},Zr={};/** + * @license React + * react-dom.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var sG=ie;function KU(n){var e="https://react.dev/errors/"+n;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(JU)}catch(n){console.error(n)}}JU(),QU.exports=Zr;var cG=QU.exports;/** + * @license React + * react-dom-client.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Ki=aG,$U=ie,uG=cG;function Pe(n){var e="https://react.dev/errors/"+n;if(1Df||(n.current=WM[Df],WM[Df]=null,Df--)}function $n(n,e){Df++,WM[Df]=n.current,n.current=e}var Do=Io(null),cg=Io(null),zc=Io(null),_1=Io(null);function x1(n,e){switch($n(zc,e),$n(cg,n),$n(Do,null),e.nodeType){case 9:case 11:n=(n=e.documentElement)&&(n=n.namespaceURI)?LN(n):0;break;default:if(n=e.tagName,e=e.namespaceURI)e=LN(e),n=M8(e,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}hr(Do),$n(Do,n)}function lp(){hr(Do),hr(cg),hr(zc)}function XM(n){n.memoizedState!==null&&$n(_1,n);var e=Do.current,t=M8(e,n.type);e!==t&&($n(cg,n),$n(Do,t))}function y1(n){cg.current===n&&(hr(Do),hr(cg)),_1.current===n&&(hr(_1),yg._currentValue=_h)}var K2,RD;function eh(n){if(K2===void 0)try{throw Error()}catch(t){var e=t.stack.trim().match(/\n( *(at )?)/);K2=e&&e[1]||"",RD=-1)":-1r||l[i]!==u[r]){var d=` +`+l[i].replace(" at new "," at ");return n.displayName&&d.includes("")&&(d=d.replace("",n.displayName)),d}while(1<=i&&0<=r);break}}}finally{J2=!1,Error.prepareStackTrace=t}return(t=n?n.displayName||n.name:"")?eh(t):""}function mG(n,e){switch(n.tag){case 26:case 27:case 5:return eh(n.type);case 16:return eh("Lazy");case 13:return n.child!==e&&e!==null?eh("Suspense Fallback"):eh("Suspense");case 19:return eh("SuspenseList");case 0:case 15:return $2(n.type,!1);case 11:return $2(n.type.render,!1);case 1:return $2(n.type,!0);case 31:return eh("Activity");default:return""}}function CD(n){try{var e="",t=null;do e+=mG(n,t),t=n,n=n.return;while(n);return e}catch(i){return` +Error generating stack: `+i.message+` +`+i.stack}}var qM=Object.prototype.hasOwnProperty,$A=Ki.unstable_scheduleCallback,eE=Ki.unstable_cancelCallback,gG=Ki.unstable_shouldYield,vG=Ki.unstable_requestPaint,Wa=Ki.unstable_now,_G=Ki.unstable_getCurrentPriorityLevel,sP=Ki.unstable_ImmediatePriority,oP=Ki.unstable_UserBlockingPriority,S1=Ki.unstable_NormalPriority,xG=Ki.unstable_LowPriority,lP=Ki.unstable_IdlePriority,yG=Ki.log,SG=Ki.unstable_setDisableYieldValue,Vg=null,Xa=null;function Rc(n){if(typeof yG=="function"&&SG(n),Xa&&typeof Xa.setStrictMode=="function")try{Xa.setStrictMode(Vg,n)}catch{}}var qa=Math.clz32?Math.clz32:bG,TG=Math.log,EG=Math.LN2;function bG(n){return n>>>=0,n===0?32:31-(TG(n)/EG|0)|0}var i_=256,r_=262144,a_=4194304;function th(n){var e=n&42;if(e!==0)return e;switch(n&-n){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 n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function cS(n,e,t){var i=n.pendingLanes;if(i===0)return 0;var r=0,a=n.suspendedLanes,s=n.pingedLanes;n=n.warmLanes;var o=i&134217727;return o!==0?(i=o&~a,i!==0?r=th(i):(s&=o,s!==0?r=th(s):t||(t=o&~n,t!==0&&(r=th(t))))):(o=i&~a,o!==0?r=th(o):s!==0?r=th(s):t||(t=i&~n,t!==0&&(r=th(t)))),r===0?0:e!==0&&e!==r&&!(e&a)&&(a=r&-r,t=e&-e,a>=t||a===32&&(t&4194048)!==0)?e:r}function Gg(n,e){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&e)===0}function MG(n,e){switch(n){case 1:case 2:case 4:case 8:case 64:return e+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 e+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 cP(){var n=a_;return a_<<=1,!(a_&62914560)&&(a_=4194304),n}function tE(n){for(var e=[],t=0;31>t;t++)e.push(n);return e}function kg(n,e){n.pendingLanes|=e,e!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function AG(n,e,t,i,r,a){var s=n.pendingLanes;n.pendingLanes=t,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=t,n.entangledLanes&=t,n.errorRecoveryDisabledLanes&=t,n.shellSuspendCounter=0;var o=n.entanglements,l=n.expirationTimes,u=n.hiddenUpdates;for(t=s&~t;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var OG=/[\n"\\]/g;function ys(n){return n.replace(OG,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function ZM(n,e,t,i,r,a,s,o){n.name="",s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"?n.type=s:n.removeAttribute("type"),e!=null?s==="number"?(e===0&&n.value===""||n.value!=e)&&(n.value=""+gs(e)):n.value!==""+gs(e)&&(n.value=""+gs(e)):s!=="submit"&&s!=="reset"||n.removeAttribute("value"),e!=null?QM(n,s,gs(e)):t!=null?QM(n,s,gs(t)):i!=null&&n.removeAttribute("value"),r==null&&a!=null&&(n.defaultChecked=!!a),r!=null&&(n.checked=r&&typeof r!="function"&&typeof r!="symbol"),o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"?n.name=""+gs(o):n.removeAttribute("name")}function _P(n,e,t,i,r,a,s,o){if(a!=null&&typeof a!="function"&&typeof a!="symbol"&&typeof a!="boolean"&&(n.type=a),e!=null||t!=null){if(!(a!=="submit"&&a!=="reset"||e!=null)){jM(n);return}t=t!=null?""+gs(t):"",e=e!=null?""+gs(e):t,o||e===n.value||(n.value=e),n.defaultValue=e}i=i??r,i=typeof i!="function"&&typeof i!="symbol"&&!!i,n.checked=o?n.checked:!!i,n.defaultChecked=!!i,s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"&&(n.name=s),jM(n)}function QM(n,e,t){e==="number"&&T1(n.ownerDocument)===n||n.defaultValue===""+t||(n.defaultValue=""+t)}function Qf(n,e,t,i){if(n=n.options,e){e={};for(var r=0;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),JM=!1;if(Nl)try{var Nm={};Object.defineProperty(Nm,"passive",{get:function(){JM=!0}}),window.addEventListener("test",Nm,Nm),window.removeEventListener("test",Nm,Nm)}catch{JM=!1}var Cc=null,aw=null,jx=null;function EP(){if(jx)return jx;var n,e=aw,t=e.length,i,r="value"in Cc?Cc.value:Cc.textContent,a=r.length;for(n=0;n=P0),HD=" ",VD=!1;function MP(n,e){switch(n){case"keyup":return sk.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function AP(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Lf=!1;function lk(n,e){switch(n){case"compositionend":return AP(e);case"keypress":return e.which!==32?null:(VD=!0,HD);case"textInput":return n=e.data,n===HD&&VD?null:n;default:return null}}function ck(n,e){if(Lf)return n==="compositionend"||!ow&&MP(n,e)?(n=EP(),jx=aw=Cc=null,Lf=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:t,offset:e-n};n=i}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=qD(t)}}function DP(n,e){return n&&e?n===e?!0:n&&n.nodeType===3?!1:e&&e.nodeType===3?DP(n,e.parentNode):"contains"in n?n.contains(e):n.compareDocumentPosition?!!(n.compareDocumentPosition(e)&16):!1:!1}function NP(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var e=T1(n.document);e instanceof n.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)n=e.contentWindow;else break;e=T1(n.document)}return e}function lw(n){var e=n&&n.nodeName&&n.nodeName.toLowerCase();return e&&(e==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||e==="textarea"||n.contentEditable==="true")}var vk=Nl&&"documentMode"in document&&11>=document.documentMode,If=null,$M=null,B0=null,e3=!1;function jD(n,e,t){var i=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;e3||If==null||If!==T1(i)||(i=If,"selectionStart"in i&&lw(i)?i={start:i.selectionStart,end:i.selectionEnd}:(i=(i.ownerDocument&&i.ownerDocument.defaultView||window).getSelection(),i={anchorNode:i.anchorNode,anchorOffset:i.anchorOffset,focusNode:i.focusNode,focusOffset:i.focusOffset}),B0&&dg(B0,i)||(B0=i,i=H1($M,"onSelect"),0>=s,r-=s,Ao=1<<32-qa(e)+r|t<U?(N=L,L=null):N=L.sibling;var C=p(_,L,E[U],b);if(C===null){L===null&&(L=N);break}n&&L&&C.alternate===null&&e(_,L),T=a(C,T,U),w===null?R=C:w.sibling=C,w=C,L=N}if(U===E.length)return t(_,L),hn&&xl(_,U),R;if(L===null){for(;UU?(N=L,L=null):N=L.sibling;var z=p(_,L,C.value,b);if(z===null){L===null&&(L=N);break}n&&L&&z.alternate===null&&e(_,L),T=a(z,T,U),w===null?R=z:w.sibling=z,w=z,L=N}if(C.done)return t(_,L),hn&&xl(_,U),R;if(L===null){for(;!C.done;U++,C=E.next())C=f(_,C.value,b),C!==null&&(T=a(C,T,U),w===null?R=C:w.sibling=C,w=C);return hn&&xl(_,U),R}for(L=i(L);!C.done;U++,C=E.next())C=m(L,_,U,C.value,b),C!==null&&(n&&C.alternate!==null&&L.delete(C.key===null?U:C.key),T=a(C,T,U),w===null?R=C:w.sibling=C,w=C);return n&&L.forEach(function(W){return e(_,W)}),hn&&xl(_,U),R}function S(_,T,E,b){if(typeof E=="object"&&E!==null&&E.type===Cf&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case n_:e:{for(var R=E.key;T!==null;){if(T.key===R){if(R=E.type,R===Cf){if(T.tag===7){t(_,T.sibling),b=r(T,E.props.children),b.return=_,_=b;break e}}else if(T.elementType===R||typeof R=="object"&&R!==null&&R.$$typeof===Sc&&nh(R)===T.type){t(_,T.sibling),b=r(T,E.props),Lm(b,E),b.return=_,_=b;break e}t(_,T);break}else e(_,T);T=T.sibling}E.type===Cf?(b=xh(E.props.children,_.mode,b,E.key),b.return=_,_=b):(b=Qx(E.type,E.key,E.props,null,_.mode,b),Lm(b,E),b.return=_,_=b)}return s(_);case S0:e:{for(R=E.key;T!==null;){if(T.key===R)if(T.tag===4&&T.stateNode.containerInfo===E.containerInfo&&T.stateNode.implementation===E.implementation){t(_,T.sibling),b=r(T,E.children||[]),b.return=_,_=b;break e}else{t(_,T);break}else e(_,T);T=T.sibling}b=uE(E,_.mode,b),b.return=_,_=b}return s(_);case Sc:return E=nh(E),S(_,T,E,b)}if(T0(E))return v(_,T,E,b);if(Dm(E)){if(R=Dm(E),typeof R!="function")throw Error(Pe(150));return E=R.call(E),x(_,T,E,b)}if(typeof E.then=="function")return S(_,T,c_(E),b);if(E.$$typeof===El)return S(_,T,l_(_,E),b);u_(_,E)}return typeof E=="string"&&E!==""||typeof E=="number"||typeof E=="bigint"?(E=""+E,T!==null&&T.tag===6?(t(_,T.sibling),b=r(T,E),b.return=_,_=b):(t(_,T),b=cE(E,_.mode,b),b.return=_,_=b),s(_)):t(_,T)}return function(_,T,E,b){try{mg=0;var R=S(_,T,E,b);return $f=null,R}catch(L){if(L===Wp||L===mS)throw L;var w=Ha(29,L,null,_.mode);return w.lanes=b,w.return=_,w}finally{}}}var Nh=qP(!0),YP=qP(!1),Tc=!1;function vw(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function o3(n,e){n=n.updateQueue,e.updateQueue===n&&(e.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function Fc(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function Hc(n,e,t){var i=n.updateQueue;if(i===null)return null;if(i=i.shared,Tn&2){var r=i.pending;return r===null?e.next=e:(e.next=r.next,r.next=e),i.pending=e,e=b1(n),BP(n,null,t),e}return pS(n,i,e,t),b1(n)}function H0(n,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194048)!==0)){var i=e.lanes;i&=n.pendingLanes,t|=i,e.lanes=t,hP(n,t)}}function dE(n,e){var t=n.updateQueue,i=n.alternate;if(i!==null&&(i=i.updateQueue,t===i)){var r=null,a=null;if(t=t.firstBaseUpdate,t!==null){do{var s={lane:t.lane,tag:t.tag,payload:t.payload,callback:null,next:null};a===null?r=a=s:a=a.next=s,t=t.next}while(t!==null);a===null?r=a=e:a=a.next=e}else r=a=e;t={baseState:i.baseState,firstBaseUpdate:r,lastBaseUpdate:a,shared:i.shared,callbacks:i.callbacks},n.updateQueue=t;return}n=t.lastBaseUpdate,n===null?t.firstBaseUpdate=e:n.next=e,t.lastBaseUpdate=e}var l3=!1;function V0(){if(l3){var n=Jf;if(n!==null)throw n}}function G0(n,e,t,i){l3=!1;var r=n.updateQueue;Tc=!1;var a=r.firstBaseUpdate,s=r.lastBaseUpdate,o=r.shared.pending;if(o!==null){r.shared.pending=null;var l=o,u=l.next;l.next=null,s===null?a=u:s.next=u,s=l;var d=n.alternate;d!==null&&(d=d.updateQueue,o=d.lastBaseUpdate,o!==s&&(o===null?d.firstBaseUpdate=u:o.next=u,d.lastBaseUpdate=l))}if(a!==null){var f=r.baseState;s=0,d=u=l=null,o=a;do{var p=o.lane&-536870913,m=p!==o.lane;if(m?(un&p)===p:(i&p)===p){p!==0&&p===hp&&(l3=!0),d!==null&&(d=d.next={lane:0,tag:o.tag,payload:o.payload,callback:null,next:null});e:{var v=n,x=o;p=e;var S=t;switch(x.tag){case 1:if(v=x.payload,typeof v=="function"){f=v.call(S,f,p);break e}f=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=x.payload,p=typeof v=="function"?v.call(S,f,p):v,p==null)break e;f=ci({},f,p);break e;case 2:Tc=!0}}p=o.callback,p!==null&&(n.flags|=64,m&&(n.flags|=8192),m=r.callbacks,m===null?r.callbacks=[p]:m.push(p))}else m={lane:p,tag:o.tag,payload:o.payload,callback:o.callback,next:null},d===null?(u=d=m,l=f):d=d.next=m,s|=p;if(o=o.next,o===null){if(o=r.shared.pending,o===null)break;m=o,o=m.next,m.next=null,r.lastBaseUpdate=m,r.shared.pending=null}}while(!0);d===null&&(l=f),r.baseState=l,r.firstBaseUpdate=u,r.lastBaseUpdate=d,a===null&&(r.shared.lanes=0),Jc|=s,n.lanes=s,n.memoizedState=f}}function jP(n,e){if(typeof n!="function")throw Error(Pe(191,n));n.call(e)}function ZP(n,e){var t=n.callbacks;if(t!==null)for(n.callbacks=null,n=0;na?a:8;var s=zt.T,o={};zt.T=o,Dw(n,!1,e,t);try{var l=r(),u=zt.S;if(u!==null&&u(o,l),l!==null&&typeof l=="object"&&typeof l.then=="function"){var d=Ak(l,i);k0(n,e,d,Ya(n))}else k0(n,e,i,Ya(n))}catch(f){k0(n,e,{then:function(){},status:"rejected",reason:f},Ya())}finally{En.p=a,s!==null&&o.types!==null&&(s.types=o.types),zt.T=s}}function Ok(){}function f3(n,e,t,i){if(n.tag!==5)throw Error(Pe(476));var r=y6(n).queue;x6(n,r,e,_h,t===null?Ok:function(){return S6(n),t(i)})}function y6(n){var e=n.memoizedState;if(e!==null)return e;e={memoizedState:_h,baseState:_h,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ll,lastRenderedState:_h},next:null};var t={};return e.next={memoizedState:t,baseState:t,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ll,lastRenderedState:t},next:null},n.memoizedState=e,n=n.alternate,n!==null&&(n.memoizedState=e),e}function S6(n){var e=y6(n);e.next===null&&(e=n.alternate.memoizedState),k0(n,e.next.queue,{},Ya())}function Cw(){return yr(yg)}function T6(){return Di().memoizedState}function E6(){return Di().memoizedState}function Lk(n){for(var e=n.return;e!==null;){switch(e.tag){case 24:case 3:var t=Ya();n=Fc(t);var i=Hc(e,n,t);i!==null&&(pa(i,e,t),H0(i,e,t)),e={cache:pw()},n.payload=e;return}e=e.return}}function Ik(n,e,t){var i=Ya();t={lane:i,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null},xS(n)?M6(e,t):(t=uw(n,e,t,i),t!==null&&(pa(t,n,i),A6(t,e,i)))}function b6(n,e,t){var i=Ya();k0(n,e,t,i)}function k0(n,e,t,i){var r={lane:i,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null};if(xS(n))M6(e,r);else{var a=n.alternate;if(n.lanes===0&&(a===null||a.lanes===0)&&(a=e.lastRenderedReducer,a!==null))try{var s=e.lastRenderedState,o=a(s,t);if(r.hasEagerState=!0,r.eagerState=o,Qa(o,s))return pS(n,e,r,0),qn===null&&fS(),!1}catch{}finally{}if(t=uw(n,e,r,i),t!==null)return pa(t,n,i),A6(t,e,i),!0}return!1}function Dw(n,e,t,i){if(i={lane:2,revertLane:Fw(),gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},xS(n)){if(e)throw Error(Pe(479))}else e=uw(n,t,i,2),e!==null&&pa(e,n,2)}function xS(n){var e=n.alternate;return n===Qt||e!==null&&e===Qt}function M6(n,e){ep=D1=!0;var t=n.pending;t===null?e.next=e:(e.next=t.next,t.next=e),n.pending=e}function A6(n,e,t){if(t&4194048){var i=e.lanes;i&=n.pendingLanes,t|=i,e.lanes=t,hP(n,t)}}var vg={readContext:yr,use:vS,useCallback:Ei,useContext:Ei,useEffect:Ei,useImperativeHandle:Ei,useLayoutEffect:Ei,useInsertionEffect:Ei,useMemo:Ei,useReducer:Ei,useRef:Ei,useState:Ei,useDebugValue:Ei,useDeferredValue:Ei,useTransition:Ei,useSyncExternalStore:Ei,useId:Ei,useHostTransitionStatus:Ei,useFormState:Ei,useActionState:Ei,useOptimistic:Ei,useMemoCache:Ei,useCacheRefresh:Ei};vg.useEffectEvent=Ei;var w6={readContext:yr,use:vS,useCallback:function(n,e){return Gr().memoizedState=[n,e===void 0?null:e],n},useContext:yr,useEffect:cN,useImperativeHandle:function(n,e,t){t=t!=null?t.concat([n]):null,$x(4194308,4,p6.bind(null,e,n),t)},useLayoutEffect:function(n,e){return $x(4194308,4,n,e)},useInsertionEffect:function(n,e){$x(4,2,n,e)},useMemo:function(n,e){var t=Gr();e=e===void 0?null:e;var i=n();if(Oh){Rc(!0);try{n()}finally{Rc(!1)}}return t.memoizedState=[i,e],i},useReducer:function(n,e,t){var i=Gr();if(t!==void 0){var r=t(e);if(Oh){Rc(!0);try{t(e)}finally{Rc(!1)}}}else r=e;return i.memoizedState=i.baseState=r,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:r},i.queue=n,n=n.dispatch=Ik.bind(null,Qt,n),[i.memoizedState,n]},useRef:function(n){var e=Gr();return n={current:n},e.memoizedState=n},useState:function(n){n=h3(n);var e=n.queue,t=b6.bind(null,Qt,e);return e.dispatch=t,[n.memoizedState,t]},useDebugValue:ww,useDeferredValue:function(n,e){var t=Gr();return Rw(t,n,e)},useTransition:function(){var n=h3(!1);return n=x6.bind(null,Qt,n.queue,!0,!1),Gr().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,e,t){var i=Qt,r=Gr();if(hn){if(t===void 0)throw Error(Pe(407));t=t()}else{if(t=e(),qn===null)throw Error(Pe(349));un&127||e6(i,e,t)}r.memoizedState=t;var a={value:t,getSnapshot:e};return r.queue=a,cN(n6.bind(null,i,a,n),[n]),i.flags|=2048,fp(9,{destroy:void 0},t6.bind(null,i,a,t,e),null),t},useId:function(){var n=Gr(),e=qn.identifierPrefix;if(hn){var t=wo,i=Ao;t=(i&~(1<<32-qa(i)-1)).toString(32)+t,e="_"+e+"R_"+t,t=N1++,0<\/script>",a=a.removeChild(a.firstChild);break;case"select":a=typeof i.is=="string"?s.createElement("select",{is:i.is}):s.createElement("select"),i.multiple?a.multiple=!0:i.size&&(a.size=i.size);break;default:a=typeof i.is=="string"?s.createElement(r,{is:i.is}):s.createElement(r)}}a[vr]=e,a[ma]=i;e:for(s=e.child;s!==null;){if(s.tag===5||s.tag===6)a.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===e)break e;for(;s.sibling===null;){if(s.return===null||s.return===e)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}e.stateNode=a;e:switch(Tr(a,r,i),r){case"button":case"input":case"select":case"textarea":i=!!i.autoFocus;break e;case"img":i=!0;break e;default:i=!1}i&&Qo(e)}}return ii(e),yE(e,e.type,n===null?null:n.memoizedProps,e.pendingProps,t),null;case 6:if(n&&e.stateNode!=null)n.memoizedProps!==i&&Qo(e);else{if(typeof i!="string"&&e.stateNode===null)throw Error(Pe(166));if(n=zc.current,Id(e)){if(n=e.stateNode,t=e.memoizedProps,i=null,r=_r,r!==null)switch(r.tag){case 27:case 5:i=r.memoizedProps}n[vr]=e,n=!!(n.nodeValue===t||i!==null&&i.suppressHydrationWarning===!0||b8(n.nodeValue,t)),n||Qc(e,!0)}else n=V1(n).createTextNode(i),n[vr]=e,e.stateNode=n}return ii(e),null;case 31:if(t=e.memoizedState,n===null||n.memoizedState!==null){if(i=Id(e),t!==null){if(n===null){if(!i)throw Error(Pe(318));if(n=e.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(Pe(557));n[vr]=e}else Ch(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;ii(e),n=!1}else t=hE(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=t),n=!0;if(!n)return e.flags&256?(Fa(e),e):(Fa(e),null);if(e.flags&128)throw Error(Pe(558))}return ii(e),null;case 13:if(i=e.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(r=Id(e),i!==null&&i.dehydrated!==null){if(n===null){if(!r)throw Error(Pe(318));if(r=e.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(Pe(317));r[vr]=e}else Ch(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;ii(e),r=!1}else r=hE(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=r),r=!0;if(!r)return e.flags&256?(Fa(e),e):(Fa(e),null)}return Fa(e),e.flags&128?(e.lanes=t,e):(t=i!==null,n=n!==null&&n.memoizedState!==null,t&&(i=e.child,r=null,i.alternate!==null&&i.alternate.memoizedState!==null&&i.alternate.memoizedState.cachePool!==null&&(r=i.alternate.memoizedState.cachePool.pool),a=null,i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(a=i.memoizedState.cachePool.pool),a!==r&&(i.flags|=2048)),t!==n&&t&&(e.child.flags|=8192),h_(e,e.updateQueue),ii(e),null);case 4:return lp(),n===null&&Hw(e.stateNode.containerInfo),ii(e),null;case 10:return wl(e.type),ii(e),null;case 19:if(hr(Ci),i=e.memoizedState,i===null)return ii(e),null;if(r=(e.flags&128)!==0,a=i.rendering,a===null)if(r)Im(i,!1);else{if(bi!==0||n!==null&&n.flags&128)for(n=e.child;n!==null;){if(a=C1(n),a!==null){for(e.flags|=128,Im(i,!1),n=a.updateQueue,e.updateQueue=n,h_(e,n),e.subtreeFlags=0,n=t,t=e.child;t!==null;)FP(t,n),t=t.sibling;return $n(Ci,Ci.current&1|2),hn&&xl(e,i.treeForkCount),e.child}n=n.sibling}i.tail!==null&&Wa()>U1&&(e.flags|=128,r=!0,Im(i,!1),e.lanes=4194304)}else{if(!r)if(n=C1(a),n!==null){if(e.flags|=128,r=!0,n=n.updateQueue,e.updateQueue=n,h_(e,n),Im(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!hn)return ii(e),null}else 2*Wa()-i.renderingStartTime>U1&&t!==536870912&&(e.flags|=128,r=!0,Im(i,!1),e.lanes=4194304);i.isBackwards?(a.sibling=e.child,e.child=a):(n=i.last,n!==null?n.sibling=a:e.child=a,i.last=a)}return i.tail!==null?(n=i.tail,i.rendering=n,i.tail=n.sibling,i.renderingStartTime=Wa(),n.sibling=null,t=Ci.current,$n(Ci,r?t&1|2:t&1),hn&&xl(e,i.treeForkCount),n):(ii(e),null);case 22:case 23:return Fa(e),_w(),i=e.memoizedState!==null,n!==null?n.memoizedState!==null!==i&&(e.flags|=8192):i&&(e.flags|=8192),i?t&536870912&&!(e.flags&128)&&(ii(e),e.subtreeFlags&6&&(e.flags|=8192)):ii(e),t=e.updateQueue,t!==null&&h_(e,t.retryQueue),t=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(t=n.memoizedState.cachePool.pool),i=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(i=e.memoizedState.cachePool.pool),i!==t&&(e.flags|=2048),n!==null&&hr(yh),null;case 24:return t=null,n!==null&&(t=n.memoizedState.cache),e.memoizedState.cache!==t&&(e.flags|=2048),wl(Vi),ii(e),null;case 25:return null;case 30:return null}throw Error(Pe(156,e.tag))}function Fk(n,e){switch(fw(e),e.tag){case 1:return n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 3:return wl(Vi),lp(),n=e.flags,n&65536&&!(n&128)?(e.flags=n&-65537|128,e):null;case 26:case 27:case 5:return y1(e),null;case 31:if(e.memoizedState!==null){if(Fa(e),e.alternate===null)throw Error(Pe(340));Ch()}return n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 13:if(Fa(e),n=e.memoizedState,n!==null&&n.dehydrated!==null){if(e.alternate===null)throw Error(Pe(340));Ch()}return n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 19:return hr(Ci),null;case 4:return lp(),null;case 10:return wl(e.type),null;case 22:case 23:return Fa(e),_w(),n!==null&&hr(yh),n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 24:return wl(Vi),null;case 25:return null;default:return null}}function F6(n,e){switch(fw(e),e.tag){case 3:wl(Vi),lp();break;case 26:case 27:case 5:y1(e);break;case 4:lp();break;case 31:e.memoizedState!==null&&Fa(e);break;case 13:Fa(e);break;case 19:hr(Ci);break;case 10:wl(e.type);break;case 22:case 23:Fa(e),_w(),n!==null&&hr(yh);break;case 24:wl(Vi)}}function jg(n,e){try{var t=e.updateQueue,i=t!==null?t.lastEffect:null;if(i!==null){var r=i.next;t=r;do{if((t.tag&n)===n){i=void 0;var a=t.create,s=t.inst;i=a(),s.destroy=i}t=t.next}while(t!==r)}}catch(o){Ln(e,e.return,o)}}function Kc(n,e,t){try{var i=e.updateQueue,r=i!==null?i.lastEffect:null;if(r!==null){var a=r.next;i=a;do{if((i.tag&n)===n){var s=i.inst,o=s.destroy;if(o!==void 0){s.destroy=void 0,r=e;var l=t,u=o;try{u()}catch(d){Ln(r,l,d)}}}i=i.next}while(i!==a)}}catch(d){Ln(e,e.return,d)}}function H6(n){var e=n.updateQueue;if(e!==null){var t=n.stateNode;try{ZP(e,t)}catch(i){Ln(n,n.return,i)}}}function V6(n,e,t){t.props=Lh(n.type,n.memoizedProps),t.state=n.memoizedState;try{t.componentWillUnmount()}catch(i){Ln(n,e,i)}}function W0(n,e){try{var t=n.ref;if(t!==null){switch(n.tag){case 26:case 27:case 5:var i=n.stateNode;break;case 30:i=n.stateNode;break;default:i=n.stateNode}typeof t=="function"?n.refCleanup=t(i):t.current=i}}catch(r){Ln(n,e,r)}}function Ro(n,e){var t=n.ref,i=n.refCleanup;if(t!==null)if(typeof i=="function")try{i()}catch(r){Ln(n,e,r)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof t=="function")try{t(null)}catch(r){Ln(n,e,r)}else t.current=null}function G6(n){var e=n.type,t=n.memoizedProps,i=n.stateNode;try{e:switch(e){case"button":case"input":case"select":case"textarea":t.autoFocus&&i.focus();break e;case"img":t.src?i.src=t.src:t.srcSet&&(i.srcset=t.srcSet)}}catch(r){Ln(n,n.return,r)}}function SE(n,e,t){try{var i=n.stateNode;oW(i,n.type,t,e),i[ma]=e}catch(r){Ln(n,n.return,r)}}function k6(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&ru(n.type)||n.tag===4}function TE(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||k6(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&ru(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function _3(n,e,t){var i=n.tag;if(i===5||i===6)n=n.stateNode,e?(t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t).insertBefore(n,e):(e=t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t,e.appendChild(n),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=bl));else if(i!==4&&(i===27&&ru(n.type)&&(t=n.stateNode,e=null),n=n.child,n!==null))for(_3(n,e,t),n=n.sibling;n!==null;)_3(n,e,t),n=n.sibling}function I1(n,e,t){var i=n.tag;if(i===5||i===6)n=n.stateNode,e?t.insertBefore(n,e):t.appendChild(n);else if(i!==4&&(i===27&&ru(n.type)&&(t=n.stateNode),n=n.child,n!==null))for(I1(n,e,t),n=n.sibling;n!==null;)I1(n,e,t),n=n.sibling}function W6(n){var e=n.stateNode,t=n.memoizedProps;try{for(var i=n.type,r=e.attributes;r.length;)e.removeAttributeNode(r[0]);Tr(e,i,t),e[vr]=n,e[ma]=t}catch(a){Ln(n,n.return,a)}}var yl=!1,Hi=!1,EE=!1,TN=typeof WeakSet=="function"?WeakSet:Set,cr=null;function Hk(n,e){if(n=n.containerInfo,M3=X1,n=NP(n),lw(n)){if("selectionStart"in n)var t={start:n.selectionStart,end:n.selectionEnd};else e:{t=(t=n.ownerDocument)&&t.defaultView||window;var i=t.getSelection&&t.getSelection();if(i&&i.rangeCount!==0){t=i.anchorNode;var r=i.anchorOffset,a=i.focusNode;i=i.focusOffset;try{t.nodeType,a.nodeType}catch{t=null;break e}var s=0,o=-1,l=-1,u=0,d=0,f=n,p=null;t:for(;;){for(var m;f!==t||r!==0&&f.nodeType!==3||(o=s+r),f!==a||i!==0&&f.nodeType!==3||(l=s+i),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===n)break t;if(p===t&&++u===r&&(o=s),p===a&&++d===i&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}t=o===-1||l===-1?null:{start:o,end:l}}else t=null}t=t||{start:0,end:0}}else t=null;for(A3={focusedElem:n,selectionRange:t},X1=!1,cr=e;cr!==null;)if(e=cr,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,cr=n;else for(;cr!==null;){switch(e=cr,a=e.alternate,n=e.flags,e.tag){case 0:if(n&4&&(n=e.updateQueue,n=n!==null?n.events:null,n!==null))for(t=0;t title"))),Tr(a,i,t),a[vr]=n,ur(a),i=a;break e;case"link":var s=GN("link","href",r).get(i+(t.href||""));if(s){for(var o=0;oS&&(s=S,S=x,x=s);var _=YD(o,x),T=YD(o,S);if(_&&T&&(m.rangeCount!==1||m.anchorNode!==_.node||m.anchorOffset!==_.offset||m.focusNode!==T.node||m.focusOffset!==T.offset)){var E=f.createRange();E.setStart(_.node,_.offset),m.removeAllRanges(),x>S?(m.addRange(E),m.extend(T.node,T.offset)):(E.setEnd(T.node,T.offset),m.addRange(E))}}}}for(f=[],m=o;m=m.parentNode;)m.nodeType===1&&f.push({element:m,left:m.scrollLeft,top:m.scrollTop});for(typeof o.focus=="function"&&o.focus(),o=0;ot?32:t,zt.T=null,t=S3,S3=null;var a=Gc,s=Rl;if(Zi=0,mp=Gc=null,Rl=0,Tn&6)throw Error(Pe(331));var o=Tn;if(Tn|=4,t8(a.current),J6(a,a.current,s,t),Tn=o,Zg(0,!1),Xa&&typeof Xa.onPostCommitFiberRoot=="function")try{Xa.onPostCommitFiberRoot(Vg,a)}catch{}return!0}finally{En.p=r,zt.T=i,g8(n,e)}}function AN(n,e,t){e=Ss(t,e),e=m3(n.stateNode,e,2),n=Hc(n,e,2),n!==null&&(kg(n,2),Uo(n))}function Ln(n,e,t){if(n.tag===3)AN(n,n,t);else for(;e!==null;){if(e.tag===3){AN(e,n,t);break}else if(e.tag===1){var i=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof i.componentDidCatch=="function"&&(Vc===null||!Vc.has(i))){n=Ss(t,n),t=O6(2),i=Hc(e,t,2),i!==null&&(L6(t,i,e,n),kg(i,2),Uo(i));break}}e=e.return}}function ME(n,e,t){var i=n.pingCache;if(i===null){i=n.pingCache=new kk;var r=new Set;i.set(e,r)}else r=i.get(e),r===void 0&&(r=new Set,i.set(e,r));r.has(t)||(Pw=!0,r.add(t),n=jk.bind(null,n,e,t),e.then(n,n))}function jk(n,e,t){var i=n.pingCache;i!==null&&i.delete(e),n.pingedLanes|=n.suspendedLanes&t,n.warmLanes&=~t,qn===n&&(un&t)===t&&(bi===4||bi===3&&(un&62914560)===un&&300>Wa()-yS?!(Tn&2)&&gp(n,0):zw|=t,pp===un&&(pp=0)),Uo(n)}function _8(n,e){e===0&&(e=cP()),n=Kh(n,e),n!==null&&(kg(n,e),Uo(n))}function Zk(n){var e=n.memoizedState,t=0;e!==null&&(t=e.retryLane),_8(n,t)}function Qk(n,e){var t=0;switch(n.tag){case 31:case 13:var i=n.stateNode,r=n.memoizedState;r!==null&&(t=r.retryLane);break;case 19:i=n.stateNode;break;case 22:i=n.stateNode._retryCache;break;default:throw Error(Pe(314))}i!==null&&i.delete(e),_8(n,t)}function Kk(n,e){return $A(n,e)}var B1=null,bf=null,E3=!1,F1=!1,AE=!1,Oc=0;function Uo(n){n!==bf&&n.next===null&&(bf===null?B1=bf=n:bf=bf.next=n),F1=!0,E3||(E3=!0,$k())}function Zg(n,e){if(!AE&&F1){AE=!0;do for(var t=!1,i=B1;i!==null;){if(n!==0){var r=i.pendingLanes;if(r===0)var a=0;else{var s=i.suspendedLanes,o=i.pingedLanes;a=(1<<31-qa(42|n)+1)-1,a&=r&~(s&~o),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(t=!0,wN(i,a))}else a=un,a=cS(i,i===qn?a:0,i.cancelPendingCommit!==null||i.timeoutHandle!==-1),!(a&3)||Gg(i,a)||(t=!0,wN(i,a));i=i.next}while(t);AE=!1}}function Jk(){x8()}function x8(){F1=E3=!1;var n=0;Oc!==0&&cW()&&(n=Oc);for(var e=Wa(),t=null,i=B1;i!==null;){var r=i.next,a=y8(i,e);a===0?(i.next=null,t===null?B1=r:t.next=r,r===null&&(bf=t)):(t=i,(n!==0||a&3)&&(F1=!0)),i=r}Zi!==0&&Zi!==5||Zg(n),Oc!==0&&(Oc=0)}function y8(n,e){for(var t=n.suspendedLanes,i=n.pingedLanes,r=n.expirationTimes,a=n.pendingLanes&-62914561;0o)break;var d=l.transferSize,f=l.initiatorType;d&&ON(f)&&(l=l.responseEnd,s+=d*(l"u"?null:document;function C8(n,e,t){var i=qp;if(i&&typeof e=="string"&&e){var r=ys(e);r='link[rel="'+n+'"][href="'+r+'"]',typeof t=="string"&&(r+='[crossorigin="'+t+'"]'),FN.has(r)||(FN.add(r),n={rel:n,crossOrigin:t,href:e},i.querySelector(r)===null&&(e=i.createElement("link"),Tr(e,"link",n),ur(e),i.head.appendChild(e)))}}function _W(n){Fl.D(n),C8("dns-prefetch",n,null)}function xW(n,e){Fl.C(n,e),C8("preconnect",n,e)}function yW(n,e,t){Fl.L(n,e,t);var i=qp;if(i&&n&&e){var r='link[rel="preload"][as="'+ys(e)+'"]';e==="image"&&t&&t.imageSrcSet?(r+='[imagesrcset="'+ys(t.imageSrcSet)+'"]',typeof t.imageSizes=="string"&&(r+='[imagesizes="'+ys(t.imageSizes)+'"]')):r+='[href="'+ys(n)+'"]';var a=r;switch(e){case"style":a=vp(n);break;case"script":a=Yp(n)}Cs.has(a)||(n=ci({rel:"preload",href:e==="image"&&t&&t.imageSrcSet?void 0:n,as:e},t),Cs.set(a,n),i.querySelector(r)!==null||e==="style"&&i.querySelector(Qg(a))||e==="script"&&i.querySelector(Kg(a))||(e=i.createElement("link"),Tr(e,"link",n),ur(e),i.head.appendChild(e)))}}function SW(n,e){Fl.m(n,e);var t=qp;if(t&&n){var i=e&&typeof e.as=="string"?e.as:"script",r='link[rel="modulepreload"][as="'+ys(i)+'"][href="'+ys(n)+'"]',a=r;switch(i){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":a=Yp(n)}if(!Cs.has(a)&&(n=ci({rel:"modulepreload",href:n},e),Cs.set(a,n),t.querySelector(r)===null)){switch(i){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(t.querySelector(Kg(a)))return}i=t.createElement("link"),Tr(i,"link",n),ur(i),t.head.appendChild(i)}}}function TW(n,e,t){Fl.S(n,e,t);var i=qp;if(i&&n){var r=Zf(i).hoistableStyles,a=vp(n);e=e||"default";var s=r.get(a);if(!s){var o={loading:0,preload:null};if(s=i.querySelector(Qg(a)))o.loading=5;else{n=ci({rel:"stylesheet",href:n,"data-precedence":e},t),(t=Cs.get(a))&&Vw(n,t);var l=s=i.createElement("link");ur(l),Tr(l,"link",n),l._p=new Promise(function(u,d){l.onload=u,l.onerror=d}),l.addEventListener("load",function(){o.loading|=1}),l.addEventListener("error",function(){o.loading|=2}),o.loading|=4,i1(s,e,i)}s={type:"stylesheet",instance:s,count:1,state:o},r.set(a,s)}}}function EW(n,e){Fl.X(n,e);var t=qp;if(t&&n){var i=Zf(t).hoistableScripts,r=Yp(n),a=i.get(r);a||(a=t.querySelector(Kg(r)),a||(n=ci({src:n,async:!0},e),(e=Cs.get(r))&&Gw(n,e),a=t.createElement("script"),ur(a),Tr(a,"link",n),t.head.appendChild(a)),a={type:"script",instance:a,count:1,state:null},i.set(r,a))}}function bW(n,e){Fl.M(n,e);var t=qp;if(t&&n){var i=Zf(t).hoistableScripts,r=Yp(n),a=i.get(r);a||(a=t.querySelector(Kg(r)),a||(n=ci({src:n,async:!0,type:"module"},e),(e=Cs.get(r))&&Gw(n,e),a=t.createElement("script"),ur(a),Tr(a,"link",n),t.head.appendChild(a)),a={type:"script",instance:a,count:1,state:null},i.set(r,a))}}function HN(n,e,t,i){var r=(r=zc.current)?G1(r):null;if(!r)throw Error(Pe(446));switch(n){case"meta":case"title":return null;case"style":return typeof t.precedence=="string"&&typeof t.href=="string"?(e=vp(t.href),t=Zf(r).hoistableStyles,i=t.get(e),i||(i={type:"style",instance:null,count:0,state:null},t.set(e,i)),i):{type:"void",instance:null,count:0,state:null};case"link":if(t.rel==="stylesheet"&&typeof t.href=="string"&&typeof t.precedence=="string"){n=vp(t.href);var a=Zf(r).hoistableStyles,s=a.get(n);if(s||(r=r.ownerDocument||r,s={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},a.set(n,s),(a=r.querySelector(Qg(n)))&&!a._p&&(s.instance=a,s.state.loading=5),Cs.has(n)||(t={rel:"preload",as:"style",href:t.href,crossOrigin:t.crossOrigin,integrity:t.integrity,media:t.media,hrefLang:t.hrefLang,referrerPolicy:t.referrerPolicy},Cs.set(n,t),a||MW(r,n,t,s.state))),e&&i===null)throw Error(Pe(528,""));return s}if(e&&i!==null)throw Error(Pe(529,""));return null;case"script":return e=t.async,t=t.src,typeof t=="string"&&e&&typeof e!="function"&&typeof e!="symbol"?(e=Yp(t),t=Zf(r).hoistableScripts,i=t.get(e),i||(i={type:"script",instance:null,count:0,state:null},t.set(e,i)),i):{type:"void",instance:null,count:0,state:null};default:throw Error(Pe(444,n))}}function vp(n){return'href="'+ys(n)+'"'}function Qg(n){return'link[rel="stylesheet"]['+n+"]"}function D8(n){return ci({},n,{"data-precedence":n.precedence,precedence:null})}function MW(n,e,t,i){n.querySelector('link[rel="preload"][as="style"]['+e+"]")?i.loading=1:(e=n.createElement("link"),i.preload=e,e.addEventListener("load",function(){return i.loading|=1}),e.addEventListener("error",function(){return i.loading|=2}),Tr(e,"link",t),ur(e),n.head.appendChild(e))}function Yp(n){return'[src="'+ys(n)+'"]'}function Kg(n){return"script[async]"+n}function VN(n,e,t){if(e.count++,e.instance===null)switch(e.type){case"style":var i=n.querySelector('style[data-href~="'+ys(t.href)+'"]');if(i)return e.instance=i,ur(i),i;var r=ci({},t,{"data-href":t.href,"data-precedence":t.precedence,href:null,precedence:null});return i=(n.ownerDocument||n).createElement("style"),ur(i),Tr(i,"style",r),i1(i,t.precedence,n),e.instance=i;case"stylesheet":r=vp(t.href);var a=n.querySelector(Qg(r));if(a)return e.state.loading|=4,e.instance=a,ur(a),a;i=D8(t),(r=Cs.get(r))&&Vw(i,r),a=(n.ownerDocument||n).createElement("link"),ur(a);var s=a;return s._p=new Promise(function(o,l){s.onload=o,s.onerror=l}),Tr(a,"link",i),e.state.loading|=4,i1(a,t.precedence,n),e.instance=a;case"script":return a=Yp(t.src),(r=n.querySelector(Kg(a)))?(e.instance=r,ur(r),r):(i=t,(r=Cs.get(a))&&(i=ci({},t),Gw(i,r)),n=n.ownerDocument||n,r=n.createElement("script"),ur(r),Tr(r,"link",i),n.head.appendChild(r),e.instance=r);case"void":return null;default:throw Error(Pe(443,e.type))}else e.type==="stylesheet"&&!(e.state.loading&4)&&(i=e.instance,e.state.loading|=4,i1(i,t.precedence,n));return e.instance}function i1(n,e,t){for(var i=t.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),r=i.length?i[i.length-1]:null,a=r,s=0;s title"):null)}function AW(n,e,t){if(t===1||e.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof e.precedence!="string"||typeof e.href!="string"||e.href==="")break;return!0;case"link":if(typeof e.rel!="string"||typeof e.href!="string"||e.href===""||e.onLoad||e.onError)break;switch(e.rel){case"stylesheet":return n=e.disabled,typeof e.precedence=="string"&&n==null;default:return!0}case"script":if(e.async&&typeof e.async!="function"&&typeof e.async!="symbol"&&!e.onLoad&&!e.onError&&e.src&&typeof e.src=="string")return!0}return!1}function N8(n){return!(n.type==="stylesheet"&&!(n.state.loading&3))}function wW(n,e,t,i){if(t.type==="stylesheet"&&(typeof i.media!="string"||matchMedia(i.media).matches!==!1)&&!(t.state.loading&4)){if(t.instance===null){var r=vp(i.href),a=e.querySelector(Qg(r));if(a){e=a._p,e!==null&&typeof e=="object"&&typeof e.then=="function"&&(n.count++,n=k1.bind(n),e.then(n,n)),t.state.loading|=4,t.instance=a,ur(a);return}a=e.ownerDocument||e,i=D8(i),(r=Cs.get(r))&&Vw(i,r),a=a.createElement("link"),ur(a);var s=a;s._p=new Promise(function(o,l){s.onload=o,s.onerror=l}),Tr(a,"link",i),t.instance=a}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(t,e),(e=t.state.preload)&&!(t.state.loading&3)&&(n.count++,t=k1.bind(n),e.addEventListener("load",t),e.addEventListener("error",t))}}var OE=0;function RW(n,e){return n.stylesheets&&n.count===0&&a1(n,n.stylesheets),0OE?50:800)+e);return n.unsuspend=t,function(){n.unsuspend=null,clearTimeout(i),clearTimeout(r)}}:null}function k1(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)a1(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var W1=null;function a1(n,e){n.stylesheets=null,n.unsuspend!==null&&(n.count++,W1=new Map,e.forEach(CW,n),W1=null,k1.call(n))}function CW(n,e){if(!(e.state.loading&4)){var t=W1.get(n);if(t)var i=t.get(null);else{t=new Map,W1.set(n,t);for(var r=n.querySelectorAll("link[data-precedence],style[data-precedence]"),a=0;a"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(F8)}catch(n){console.error(n)}}F8(),YU.exports=oS;var H8=YU.exports;const zW=aS(H8);var V8={exports:{}},au={};/** + * @license React + * react-reconciler-constants.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */au.ConcurrentRoot=1;au.ContinuousEventPriority=8;au.DefaultEventPriority=32;au.DiscreteEventPriority=2;au.IdleEventPriority=268435456;au.LegacyRoot=0;au.NoEventPriority=0;V8.exports=au;var o1=V8.exports;/** + * @license + * Copyright 2010-2025 Three.js Authors + * SPDX-License-Identifier: MIT + */const $s="181",rh={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},ah={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},G8=0,I3=1,k8=2,BW=3,W8=0,MS=1,Z0=2,Xs=3,eo=0,ki=1,xr=2,Lr=0,Eh=1,U3=2,P3=3,z3=4,AS=5,bo=100,X8=101,q8=102,Y8=103,j8=104,Yw=200,uh=201,Z8=202,Q8=203,Y1=204,j1=205,K8=206,J8=207,$8=208,e9=209,t9=210,n9=211,i9=212,r9=213,a9=214,Z1=0,Eg=1,Q1=2,Ih=3,K1=4,J1=5,$1=6,ey=7,Jg=0,s9=1,o9=2,As=0,l9=1,c9=2,u9=3,jw=4,h9=5,d9=6,f9=7,B3="attached",p9="detached",wS=300,Pl=301,$c=302,bg=303,Mg=304,jp=306,Ir=1e3,Wi=1001,xp=1002,Yn=1003,RS=1004,FW=1004,hh=1005,HW=1005,Bt=1006,np=1007,VW=1007,Ga=1008,m9=1008,Ni=1009,CS=1010,DS=1011,Uh=1012,$g=1013,to=1014,fi=1015,Jn=1016,NS=1017,OS=1018,Ph=1020,Zw=35902,Qw=35899,Kw=1021,Jw=1022,ai=1023,yp=1026,zh=1027,Qs=1028,ev=1029,Mo=1030,LS=1031,GW=1032,IS=1033,Q0=33776,K0=33777,J0=33778,$0=33779,ty=35840,ny=35841,iy=35842,ry=35843,ay=36196,sy=37492,oy=37496,ly=37808,cy=37809,uy=37810,hy=37811,dy=37812,fy=37813,py=37814,my=37815,gy=37816,vy=37817,_y=37818,xy=37819,yy=37820,Sy=37821,Ty=36492,Ey=36494,by=36495,My=36283,Ay=36284,wy=36285,Ry=36286,$w=2200,g9=2201,v9=2202,Sp=2300,Tp=2301,l1=2302,dh=2400,fh=2401,Ag=2402,US=2500,eR=2501,_9=0,tR=1,Cy=2,su=3200,x9=3201,kW=3202,WW=3203,Hl=0,y9=1,Xr="",mn="srgb",Xn="srgb-linear",wg="linear",Dn="srgb",XW=0,sh=7680,qW=7681,YW=7682,jW=7683,ZW=34055,QW=34056,KW=5386,JW=512,$W=513,eX=514,tX=515,nX=516,iX=517,rX=518,F3=519,S9=512,T9=513,E9=514,nR=515,b9=516,M9=517,A9=518,w9=519,Rg=35044,R9=35048,aX=35040,sX=35045,oX=35049,lX=35041,cX=35046,uX=35050,hX=35042,dX="100",No="300 es",ka=2e3,Ep=2001,fX={COMPUTE:"compute",RENDER:"render"},pX={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},mX={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"};function C9(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}const gX={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function Vf(n,e){return new gX[n](e)}function Cg(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function D9(){const n=Cg("canvas");return n.style.display="block",n}const QN={};let eu=null;function vX(n){eu=n}function _X(){return eu}function Dg(...n){const e="THREE."+n.shift();eu?eu("log",e,...n):console.log(e,...n)}function dt(...n){const e="THREE."+n.shift();eu?eu("warn",e,...n):console.warn(e,...n)}function Ht(...n){const e="THREE."+n.shift();eu?eu("error",e,...n):console.error(e,...n)}function bp(...n){const e=n.join(" ");e in QN||(QN[e]=!0,dt(...n))}function xX(n,e,t){return new Promise(function(i,r){function a(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:r();break;case n.TIMEOUT_EXPIRED:setTimeout(a,t);break;default:i()}}setTimeout(a,t)})}let Mi=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners;if(i===void 0)return;const r=i[e];if(r!==void 0){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const i=t[e.type];if(i!==void 0){e.target=this;const r=i.slice(0);for(let a=0,s=r.length;a>8&255]+Cr[n>>16&255]+Cr[n>>24&255]+"-"+Cr[e&255]+Cr[e>>8&255]+"-"+Cr[e>>16&15|64]+Cr[e>>24&255]+"-"+Cr[t&63|128]+Cr[t>>8&255]+"-"+Cr[t>>16&255]+Cr[t>>24&255]+Cr[i&255]+Cr[i>>8&255]+Cr[i>>16&255]+Cr[i>>24&255]).toLowerCase()}function It(n,e,t){return Math.max(e,Math.min(t,n))}function iR(n,e){return(n%e+e)%e}function yX(n,e,t,i,r){return i+(n-e)*(r-i)/(t-e)}function SX(n,e,t){return n!==e?(t-n)/(e-n):0}function eg(n,e,t){return(1-t)*n+t*e}function TX(n,e,t,i){return eg(n,e,1-Math.exp(-t*i))}function EX(n,e=1){return e-Math.abs(iR(n,e*2)-e)}function bX(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function MX(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function AX(n,e){return n+Math.floor(Math.random()*(e-n+1))}function wX(n,e){return n+Math.random()*(e-n)}function RX(n){return n*(.5-Math.random())}function CX(n){n!==void 0&&(KN=n);let e=KN+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function DX(n){return n*bh}function NX(n){return n*Mp}function OX(n){return(n&n-1)===0&&n!==0}function LX(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function IX(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function UX(n,e,t,i,r){const a=Math.cos,s=Math.sin,o=a(t/2),l=s(t/2),u=a((e+i)/2),d=s((e+i)/2),f=a((e-i)/2),p=s((e-i)/2),m=a((i-e)/2),v=s((i-e)/2);switch(r){case"XYX":n.set(o*d,l*f,l*p,o*u);break;case"YZY":n.set(l*p,o*d,l*f,o*u);break;case"ZXZ":n.set(l*f,l*p,o*d,o*u);break;case"XZX":n.set(o*d,l*v,l*m,o*u);break;case"YXY":n.set(l*m,o*d,l*v,o*u);break;case"ZYZ":n.set(l*v,l*m,o*d,o*u);break;default:dt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}function qr(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function Zt(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const lt={DEG2RAD:bh,RAD2DEG:Mp,generateUUID:ja,clamp:It,euclideanModulo:iR,mapLinear:yX,inverseLerp:SX,lerp:eg,damp:TX,pingpong:EX,smoothstep:bX,smootherstep:MX,randInt:AX,randFloat:wX,randFloatSpread:RX,seededRandom:CX,degToRad:DX,radToDeg:NX,isPowerOfTwo:OX,ceilPowerOfTwo:LX,floorPowerOfTwo:IX,setQuaternionFromProperEuler:UX,normalize:Zt,denormalize:qr};class re{constructor(e=0,t=0){re.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6],this.y=r[1]*t+r[4]*i+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=It(this.x,e.x,t.x),this.y=It(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=It(this.x,e,t),this.y=It(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(It(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(It(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),r=Math.sin(t),a=this.x-e.x,s=this.y-e.y;return this.x=a*i-s*r+e.x,this.y=a*r+s*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ft{constructor(e=0,t=0,i=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=r}static slerpFlat(e,t,i,r,a,s,o){let l=i[r+0],u=i[r+1],d=i[r+2],f=i[r+3],p=a[s+0],m=a[s+1],v=a[s+2],x=a[s+3];if(o<=0){e[t+0]=l,e[t+1]=u,e[t+2]=d,e[t+3]=f;return}if(o>=1){e[t+0]=p,e[t+1]=m,e[t+2]=v,e[t+3]=x;return}if(f!==x||l!==p||u!==m||d!==v){let S=l*p+u*m+d*v+f*x;S<0&&(p=-p,m=-m,v=-v,x=-x,S=-S);let _=1-o;if(S<.9995){const T=Math.acos(S),E=Math.sin(T);_=Math.sin(_*T)/E,o=Math.sin(o*T)/E,l=l*_+p*o,u=u*_+m*o,d=d*_+v*o,f=f*_+x*o}else{l=l*_+p*o,u=u*_+m*o,d=d*_+v*o,f=f*_+x*o;const T=1/Math.sqrt(l*l+u*u+d*d+f*f);l*=T,u*=T,d*=T,f*=T}}e[t]=l,e[t+1]=u,e[t+2]=d,e[t+3]=f}static multiplyQuaternionsFlat(e,t,i,r,a,s){const o=i[r],l=i[r+1],u=i[r+2],d=i[r+3],f=a[s],p=a[s+1],m=a[s+2],v=a[s+3];return e[t]=o*v+d*f+l*m-u*p,e[t+1]=l*v+d*p+u*f-o*m,e[t+2]=u*v+d*m+o*p-l*f,e[t+3]=d*v-o*f-l*p-u*m,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,r=e._y,a=e._z,s=e._order,o=Math.cos,l=Math.sin,u=o(i/2),d=o(r/2),f=o(a/2),p=l(i/2),m=l(r/2),v=l(a/2);switch(s){case"XYZ":this._x=p*d*f+u*m*v,this._y=u*m*f-p*d*v,this._z=u*d*v+p*m*f,this._w=u*d*f-p*m*v;break;case"YXZ":this._x=p*d*f+u*m*v,this._y=u*m*f-p*d*v,this._z=u*d*v-p*m*f,this._w=u*d*f+p*m*v;break;case"ZXY":this._x=p*d*f-u*m*v,this._y=u*m*f+p*d*v,this._z=u*d*v+p*m*f,this._w=u*d*f-p*m*v;break;case"ZYX":this._x=p*d*f-u*m*v,this._y=u*m*f+p*d*v,this._z=u*d*v-p*m*f,this._w=u*d*f+p*m*v;break;case"YZX":this._x=p*d*f+u*m*v,this._y=u*m*f+p*d*v,this._z=u*d*v-p*m*f,this._w=u*d*f-p*m*v;break;case"XZY":this._x=p*d*f-u*m*v,this._y=u*m*f-p*d*v,this._z=u*d*v+p*m*f,this._w=u*d*f+p*m*v;break;default:dt("Quaternion: .setFromEuler() encountered an unknown order: "+s)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,r=Math.sin(i);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],r=t[4],a=t[8],s=t[1],o=t[5],l=t[9],u=t[2],d=t[6],f=t[10],p=i+o+f;if(p>0){const m=.5/Math.sqrt(p+1);this._w=.25/m,this._x=(d-l)*m,this._y=(a-u)*m,this._z=(s-r)*m}else if(i>o&&i>f){const m=2*Math.sqrt(1+i-o-f);this._w=(d-l)/m,this._x=.25*m,this._y=(r+s)/m,this._z=(a+u)/m}else if(o>f){const m=2*Math.sqrt(1+o-i-f);this._w=(a-u)/m,this._x=(r+s)/m,this._y=.25*m,this._z=(l+d)/m}else{const m=2*Math.sqrt(1+f-i-o);this._w=(s-r)/m,this._x=(a+u)/m,this._y=(l+d)/m,this._z=.25*m}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(It(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const r=Math.min(1,t/i);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,r=e._y,a=e._z,s=e._w,o=t._x,l=t._y,u=t._z,d=t._w;return this._x=i*d+s*o+r*u-a*l,this._y=r*d+s*l+a*o-i*u,this._z=a*d+s*u+i*l-r*o,this._w=s*d-i*o-r*l-a*u,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let i=e._x,r=e._y,a=e._z,s=e._w,o=this.dot(e);o<0&&(i=-i,r=-r,a=-a,s=-s,o=-o);let l=1-t;if(o<.9995){const u=Math.acos(o),d=Math.sin(u);l=Math.sin(l*u)/d,t=Math.sin(t*u)/d,this._x=this._x*l+i*t,this._y=this._y*l+r*t,this._z=this._z*l+a*t,this._w=this._w*l+s*t,this._onChangeCallback()}else this._x=this._x*l+i*t,this._y=this._y*l+r*t,this._z=this._z*l+a*t,this._w=this._w*l+s*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),r=Math.sqrt(1-i),a=Math.sqrt(i);return this.set(r*Math.sin(e),r*Math.cos(e),a*Math.sin(t),a*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class D{constructor(e=0,t=0,i=0){D.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(JN.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(JN.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,r=this.z,a=e.elements;return this.x=a[0]*t+a[3]*i+a[6]*r,this.y=a[1]*t+a[4]*i+a[7]*r,this.z=a[2]*t+a[5]*i+a[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,r=this.z,a=e.elements,s=1/(a[3]*t+a[7]*i+a[11]*r+a[15]);return this.x=(a[0]*t+a[4]*i+a[8]*r+a[12])*s,this.y=(a[1]*t+a[5]*i+a[9]*r+a[13])*s,this.z=(a[2]*t+a[6]*i+a[10]*r+a[14])*s,this}applyQuaternion(e){const t=this.x,i=this.y,r=this.z,a=e.x,s=e.y,o=e.z,l=e.w,u=2*(s*r-o*i),d=2*(o*t-a*r),f=2*(a*i-s*t);return this.x=t+l*u+s*f-o*d,this.y=i+l*d+o*u-a*f,this.z=r+l*f+a*d-s*u,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,r=this.z,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*r,this.y=a[1]*t+a[5]*i+a[9]*r,this.z=a[2]*t+a[6]*i+a[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=It(this.x,e.x,t.x),this.y=It(this.y,e.y,t.y),this.z=It(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=It(this.x,e,t),this.y=It(this.y,e,t),this.z=It(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(It(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,r=e.y,a=e.z,s=t.x,o=t.y,l=t.z;return this.x=r*l-a*o,this.y=a*s-i*l,this.z=i*o-r*s,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return LE.copy(this).projectOnVector(e),this.sub(LE)}reflect(e){return this.sub(LE.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(It(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,r=this.z-e.z;return t*t+i*i+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const r=Math.sin(t)*e;return this.x=r*Math.sin(i),this.y=Math.cos(t)*e,this.z=r*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const LE=new D,JN=new ft;class Mt{constructor(e,t,i,r,a,s,o,l,u){Mt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,r,a,s,o,l,u)}set(e,t,i,r,a,s,o,l,u){const d=this.elements;return d[0]=e,d[1]=r,d[2]=o,d[3]=t,d[4]=a,d[5]=l,d[6]=i,d[7]=s,d[8]=u,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,r=t.elements,a=this.elements,s=i[0],o=i[3],l=i[6],u=i[1],d=i[4],f=i[7],p=i[2],m=i[5],v=i[8],x=r[0],S=r[3],_=r[6],T=r[1],E=r[4],b=r[7],R=r[2],w=r[5],L=r[8];return a[0]=s*x+o*T+l*R,a[3]=s*S+o*E+l*w,a[6]=s*_+o*b+l*L,a[1]=u*x+d*T+f*R,a[4]=u*S+d*E+f*w,a[7]=u*_+d*b+f*L,a[2]=p*x+m*T+v*R,a[5]=p*S+m*E+v*w,a[8]=p*_+m*b+v*L,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],r=e[2],a=e[3],s=e[4],o=e[5],l=e[6],u=e[7],d=e[8];return t*s*d-t*o*u-i*a*d+i*o*l+r*a*u-r*s*l}invert(){const e=this.elements,t=e[0],i=e[1],r=e[2],a=e[3],s=e[4],o=e[5],l=e[6],u=e[7],d=e[8],f=d*s-o*u,p=o*l-d*a,m=u*a-s*l,v=t*f+i*p+r*m;if(v===0)return this.set(0,0,0,0,0,0,0,0,0);const x=1/v;return e[0]=f*x,e[1]=(r*u-d*i)*x,e[2]=(o*i-r*s)*x,e[3]=p*x,e[4]=(d*t-r*l)*x,e[5]=(r*a-o*t)*x,e[6]=m*x,e[7]=(i*l-u*t)*x,e[8]=(s*t-i*a)*x,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,r,a,s,o){const l=Math.cos(a),u=Math.sin(a);return this.set(i*l,i*u,-i*(l*s+u*o)+s+e,-r*u,r*l,-r*(-u*s+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(IE.makeScale(e,t)),this}rotate(e){return this.premultiply(IE.makeRotation(-e)),this}translate(e,t){return this.premultiply(IE.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let r=0;r<9;r++)if(t[r]!==i[r])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const IE=new Mt,$N=new Mt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),eO=new Mt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function PX(){const n={enabled:!0,workingColorSpace:Xn,spaces:{},convert:function(r,a,s){return this.enabled===!1||a===s||!a||!s||(this.spaces[a].transfer===Dn&&(r.r=Cl(r.r),r.g=Cl(r.g),r.b=Cl(r.b)),this.spaces[a].primaries!==this.spaces[s].primaries&&(r.applyMatrix3(this.spaces[a].toXYZ),r.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===Dn&&(r.r=ip(r.r),r.g=ip(r.g),r.b=ip(r.b))),r},workingToColorSpace:function(r,a){return this.convert(r,this.workingColorSpace,a)},colorSpaceToWorking:function(r,a){return this.convert(r,a,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===Xr?wg:this.spaces[r].transfer},getToneMappingMode:function(r){return this.spaces[r].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(r,a=this.workingColorSpace){return r.fromArray(this.spaces[a].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,a,s){return r.copy(this.spaces[a].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(r,a){return bp("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(r,a)},toWorkingColorSpace:function(r,a){return bp("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(r,a)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[Xn]:{primaries:e,whitePoint:i,transfer:wg,toXYZ:$N,fromXYZ:eO,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:mn},outputColorSpaceConfig:{drawingBufferColorSpace:mn}},[mn]:{primaries:e,whitePoint:i,transfer:Dn,toXYZ:$N,fromXYZ:eO,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:mn}}}),n}const tn=PX();function Cl(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function ip(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let Pd;class N9{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Pd===void 0&&(Pd=Cg("canvas")),Pd.width=e.width,Pd.height=e.height;const r=Pd.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),i=Pd}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Cg("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const r=i.getImageData(0,0,e.width,e.height),a=r.data;for(let s=0;s1),this.pmremVersion=0}get width(){return this.source.getSize(PE).x}get height(){return this.source.getSize(PE).y}get depth(){return this.source.getSize(PE).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){dt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const r=this[t];if(r===void 0){dt(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&i&&r.isVector2&&i.isVector2||r&&i&&r.isVector3&&i.isVector3||r&&i&&r.isMatrix3&&i.isMatrix3?r.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==wS)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Ir:e.x=e.x-Math.floor(e.x);break;case Wi:e.x=e.x<0?0:1;break;case xp: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 Ir:e.y=e.y-Math.floor(e.y);break;case Wi:e.y=e.y<0?0:1;break;case xp: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++}}In.DEFAULT_IMAGE=null;In.DEFAULT_MAPPING=wS;In.DEFAULT_ANISOTROPY=1;class Pt{constructor(e=0,t=0,i=0,r=1){Pt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,r=this.z,a=this.w,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*r+s[12]*a,this.y=s[1]*t+s[5]*i+s[9]*r+s[13]*a,this.z=s[2]*t+s[6]*i+s[10]*r+s[14]*a,this.w=s[3]*t+s[7]*i+s[11]*r+s[15]*a,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 t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,r,a;const l=e.elements,u=l[0],d=l[4],f=l[8],p=l[1],m=l[5],v=l[9],x=l[2],S=l[6],_=l[10];if(Math.abs(d-p)<.01&&Math.abs(f-x)<.01&&Math.abs(v-S)<.01){if(Math.abs(d+p)<.1&&Math.abs(f+x)<.1&&Math.abs(v+S)<.1&&Math.abs(u+m+_-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const E=(u+1)/2,b=(m+1)/2,R=(_+1)/2,w=(d+p)/4,L=(f+x)/4,U=(v+S)/4;return E>b&&E>R?E<.01?(i=0,r=.707106781,a=.707106781):(i=Math.sqrt(E),r=w/i,a=L/i):b>R?b<.01?(i=.707106781,r=0,a=.707106781):(r=Math.sqrt(b),i=w/r,a=U/r):R<.01?(i=.707106781,r=.707106781,a=0):(a=Math.sqrt(R),i=L/a,r=U/a),this.set(i,r,a,t),this}let T=Math.sqrt((S-v)*(S-v)+(f-x)*(f-x)+(p-d)*(p-d));return Math.abs(T)<.001&&(T=1),this.x=(S-v)/T,this.y=(f-x)/T,this.z=(p-d)/T,this.w=Math.acos((u+m+_-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=It(this.x,e.x,t.x),this.y=It(this.y,e.y,t.y),this.z=It(this.z,e.z,t.z),this.w=It(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=It(this.x,e,t),this.y=It(this.y,e,t),this.z=It(this.z,e,t),this.w=It(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(It(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class rR extends Mi{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Bt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new Pt(0,0,e,t),this.scissorTest=!1,this.viewport=new Pt(0,0,e,t);const r={width:e,height:t,depth:i.depth},a=new In(r);this.textures=[];const s=i.count;for(let o=0;o1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,zs),zs.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(zm),__.subVectors(this.max,zm),zd.subVectors(e.a,zm),Bd.subVectors(e.b,zm),Fd.subVectors(e.c,zm),rc.subVectors(Bd,zd),ac.subVectors(Fd,Bd),Nu.subVectors(zd,Fd);let t=[0,-rc.z,rc.y,0,-ac.z,ac.y,0,-Nu.z,Nu.y,rc.z,0,-rc.x,ac.z,0,-ac.x,Nu.z,0,-Nu.x,-rc.y,rc.x,0,-ac.y,ac.x,0,-Nu.y,Nu.x,0];return!zE(t,zd,Bd,Fd,__)||(t=[1,0,0,0,1,0,0,0,1],!zE(t,zd,Bd,Fd,__))?!1:(x_.crossVectors(rc,ac),t=[x_.x,x_.y,x_.z],zE(t,zd,Bd,Fd,__))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,zs).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(zs).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:($o[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),$o[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),$o[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),$o[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),$o[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),$o[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),$o[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),$o[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints($o),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 $o=[new D,new D,new D,new D,new D,new D,new D,new D],zs=new D,v_=new Qi,zd=new D,Bd=new D,Fd=new D,rc=new D,ac=new D,Nu=new D,zm=new D,__=new D,x_=new D,Ou=new D;function zE(n,e,t,i,r){for(let a=0,s=n.length-3;a<=s;a+=3){Ou.fromArray(n,a);const o=r.x*Math.abs(Ou.x)+r.y*Math.abs(Ou.y)+r.z*Math.abs(Ou.z),l=e.dot(Ou),u=t.dot(Ou),d=i.dot(Ou);if(Math.max(-Math.max(l,u,d),Math.min(l,u,d))>o)return!1}return!0}const FX=new Qi,Bm=new D,BE=new D;class qi{constructor(e=new D,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):FX.setFromPoints(e).getCenter(i);let r=0;for(let a=0,s=e.length;athis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Bm.subVectors(e,this.center);const t=Bm.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),r=(i-this.radius)*.5;this.center.addScaledVector(Bm,r/i),this.radius+=r}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):(BE.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Bm.copy(e.center).add(BE)),this.expandByPoint(Bm.copy(e.center).sub(BE))),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}}const el=new D,FE=new D,y_=new D,sc=new D,HE=new D,S_=new D,VE=new D;class Pr{constructor(e=new D,t=new D(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,el)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=el.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(el.copy(this.origin).addScaledVector(this.direction,t),el.distanceToSquared(e))}distanceSqToSegment(e,t,i,r){FE.copy(e).add(t).multiplyScalar(.5),y_.copy(t).sub(e).normalize(),sc.copy(this.origin).sub(FE);const a=e.distanceTo(t)*.5,s=-this.direction.dot(y_),o=sc.dot(this.direction),l=-sc.dot(y_),u=sc.lengthSq(),d=Math.abs(1-s*s);let f,p,m,v;if(d>0)if(f=s*l-o,p=s*o-l,v=a*d,f>=0)if(p>=-v)if(p<=v){const x=1/d;f*=x,p*=x,m=f*(f+s*p+2*o)+p*(s*f+p+2*l)+u}else p=a,f=Math.max(0,-(s*p+o)),m=-f*f+p*(p+2*l)+u;else p=-a,f=Math.max(0,-(s*p+o)),m=-f*f+p*(p+2*l)+u;else p<=-v?(f=Math.max(0,-(-s*a+o)),p=f>0?-a:Math.min(Math.max(-a,-l),a),m=-f*f+p*(p+2*l)+u):p<=v?(f=0,p=Math.min(Math.max(-a,-l),a),m=p*(p+2*l)+u):(f=Math.max(0,-(s*a+o)),p=f>0?a:Math.min(Math.max(-a,-l),a),m=-f*f+p*(p+2*l)+u);else p=s>0?-a:a,f=Math.max(0,-(s*p+o)),m=-f*f+p*(p+2*l)+u;return i&&i.copy(this.origin).addScaledVector(this.direction,f),r&&r.copy(FE).addScaledVector(y_,p),m}intersectSphere(e,t){el.subVectors(e.center,this.origin);const i=el.dot(this.direction),r=el.dot(el)-i*i,a=e.radius*e.radius;if(r>a)return null;const s=Math.sqrt(a-r),o=i-s,l=i+s;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,r,a,s,o,l;const u=1/this.direction.x,d=1/this.direction.y,f=1/this.direction.z,p=this.origin;return u>=0?(i=(e.min.x-p.x)*u,r=(e.max.x-p.x)*u):(i=(e.max.x-p.x)*u,r=(e.min.x-p.x)*u),d>=0?(a=(e.min.y-p.y)*d,s=(e.max.y-p.y)*d):(a=(e.max.y-p.y)*d,s=(e.min.y-p.y)*d),i>s||a>r||((a>i||isNaN(i))&&(i=a),(s=0?(o=(e.min.z-p.z)*f,l=(e.max.z-p.z)*f):(o=(e.max.z-p.z)*f,l=(e.min.z-p.z)*f),i>l||o>r)||((o>i||i!==i)&&(i=o),(l=0?i:r,t)}intersectsBox(e){return this.intersectBox(e,el)!==null}intersectTriangle(e,t,i,r,a){HE.subVectors(t,e),S_.subVectors(i,e),VE.crossVectors(HE,S_);let s=this.direction.dot(VE),o;if(s>0){if(r)return null;o=1}else if(s<0)o=-1,s=-s;else return null;sc.subVectors(this.origin,e);const l=o*this.direction.dot(S_.crossVectors(sc,S_));if(l<0)return null;const u=o*this.direction.dot(HE.cross(sc));if(u<0||l+u>s)return null;const d=-o*sc.dot(VE);return d<0?null:this.at(d/s,a)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Me{constructor(e,t,i,r,a,s,o,l,u,d,f,p,m,v,x,S){Me.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,r,a,s,o,l,u,d,f,p,m,v,x,S)}set(e,t,i,r,a,s,o,l,u,d,f,p,m,v,x,S){const _=this.elements;return _[0]=e,_[4]=t,_[8]=i,_[12]=r,_[1]=a,_[5]=s,_[9]=o,_[13]=l,_[2]=u,_[6]=d,_[10]=f,_[14]=p,_[3]=m,_[7]=v,_[11]=x,_[15]=S,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Me().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,r=1/Hd.setFromMatrixColumn(e,0).length(),a=1/Hd.setFromMatrixColumn(e,1).length(),s=1/Hd.setFromMatrixColumn(e,2).length();return t[0]=i[0]*r,t[1]=i[1]*r,t[2]=i[2]*r,t[3]=0,t[4]=i[4]*a,t[5]=i[5]*a,t[6]=i[6]*a,t[7]=0,t[8]=i[8]*s,t[9]=i[9]*s,t[10]=i[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,r=e.y,a=e.z,s=Math.cos(i),o=Math.sin(i),l=Math.cos(r),u=Math.sin(r),d=Math.cos(a),f=Math.sin(a);if(e.order==="XYZ"){const p=s*d,m=s*f,v=o*d,x=o*f;t[0]=l*d,t[4]=-l*f,t[8]=u,t[1]=m+v*u,t[5]=p-x*u,t[9]=-o*l,t[2]=x-p*u,t[6]=v+m*u,t[10]=s*l}else if(e.order==="YXZ"){const p=l*d,m=l*f,v=u*d,x=u*f;t[0]=p+x*o,t[4]=v*o-m,t[8]=s*u,t[1]=s*f,t[5]=s*d,t[9]=-o,t[2]=m*o-v,t[6]=x+p*o,t[10]=s*l}else if(e.order==="ZXY"){const p=l*d,m=l*f,v=u*d,x=u*f;t[0]=p-x*o,t[4]=-s*f,t[8]=v+m*o,t[1]=m+v*o,t[5]=s*d,t[9]=x-p*o,t[2]=-s*u,t[6]=o,t[10]=s*l}else if(e.order==="ZYX"){const p=s*d,m=s*f,v=o*d,x=o*f;t[0]=l*d,t[4]=v*u-m,t[8]=p*u+x,t[1]=l*f,t[5]=x*u+p,t[9]=m*u-v,t[2]=-u,t[6]=o*l,t[10]=s*l}else if(e.order==="YZX"){const p=s*l,m=s*u,v=o*l,x=o*u;t[0]=l*d,t[4]=x-p*f,t[8]=v*f+m,t[1]=f,t[5]=s*d,t[9]=-o*d,t[2]=-u*d,t[6]=m*f+v,t[10]=p-x*f}else if(e.order==="XZY"){const p=s*l,m=s*u,v=o*l,x=o*u;t[0]=l*d,t[4]=-f,t[8]=u*d,t[1]=p*f+x,t[5]=s*d,t[9]=m*f-v,t[2]=v*f-m,t[6]=o*d,t[10]=x*f+p}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(HX,e,VX)}lookAt(e,t,i){const r=this.elements;return Oa.subVectors(e,t),Oa.lengthSq()===0&&(Oa.z=1),Oa.normalize(),oc.crossVectors(i,Oa),oc.lengthSq()===0&&(Math.abs(i.z)===1?Oa.x+=1e-4:Oa.z+=1e-4,Oa.normalize(),oc.crossVectors(i,Oa)),oc.normalize(),T_.crossVectors(Oa,oc),r[0]=oc.x,r[4]=T_.x,r[8]=Oa.x,r[1]=oc.y,r[5]=T_.y,r[9]=Oa.y,r[2]=oc.z,r[6]=T_.z,r[10]=Oa.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,r=t.elements,a=this.elements,s=i[0],o=i[4],l=i[8],u=i[12],d=i[1],f=i[5],p=i[9],m=i[13],v=i[2],x=i[6],S=i[10],_=i[14],T=i[3],E=i[7],b=i[11],R=i[15],w=r[0],L=r[4],U=r[8],N=r[12],C=r[1],z=r[5],W=r[9],K=r[13],oe=r[2],ae=r[6],X=r[10],te=r[14],Q=r[3],ce=r[7],se=r[11],De=r[15];return a[0]=s*w+o*C+l*oe+u*Q,a[4]=s*L+o*z+l*ae+u*ce,a[8]=s*U+o*W+l*X+u*se,a[12]=s*N+o*K+l*te+u*De,a[1]=d*w+f*C+p*oe+m*Q,a[5]=d*L+f*z+p*ae+m*ce,a[9]=d*U+f*W+p*X+m*se,a[13]=d*N+f*K+p*te+m*De,a[2]=v*w+x*C+S*oe+_*Q,a[6]=v*L+x*z+S*ae+_*ce,a[10]=v*U+x*W+S*X+_*se,a[14]=v*N+x*K+S*te+_*De,a[3]=T*w+E*C+b*oe+R*Q,a[7]=T*L+E*z+b*ae+R*ce,a[11]=T*U+E*W+b*X+R*se,a[15]=T*N+E*K+b*te+R*De,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],r=e[8],a=e[12],s=e[1],o=e[5],l=e[9],u=e[13],d=e[2],f=e[6],p=e[10],m=e[14],v=e[3],x=e[7],S=e[11],_=e[15];return v*(+a*l*f-r*u*f-a*o*p+i*u*p+r*o*m-i*l*m)+x*(+t*l*m-t*u*p+a*s*p-r*s*m+r*u*d-a*l*d)+S*(+t*u*f-t*o*m-a*s*f+i*s*m+a*o*d-i*u*d)+_*(-r*o*d-t*l*f+t*o*p+r*s*f-i*s*p+i*l*d)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],r=e[2],a=e[3],s=e[4],o=e[5],l=e[6],u=e[7],d=e[8],f=e[9],p=e[10],m=e[11],v=e[12],x=e[13],S=e[14],_=e[15],T=f*S*u-x*p*u+x*l*m-o*S*m-f*l*_+o*p*_,E=v*p*u-d*S*u-v*l*m+s*S*m+d*l*_-s*p*_,b=d*x*u-v*f*u+v*o*m-s*x*m-d*o*_+s*f*_,R=v*f*l-d*x*l-v*o*p+s*x*p+d*o*S-s*f*S,w=t*T+i*E+r*b+a*R;if(w===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const L=1/w;return e[0]=T*L,e[1]=(x*p*a-f*S*a-x*r*m+i*S*m+f*r*_-i*p*_)*L,e[2]=(o*S*a-x*l*a+x*r*u-i*S*u-o*r*_+i*l*_)*L,e[3]=(f*l*a-o*p*a-f*r*u+i*p*u+o*r*m-i*l*m)*L,e[4]=E*L,e[5]=(d*S*a-v*p*a+v*r*m-t*S*m-d*r*_+t*p*_)*L,e[6]=(v*l*a-s*S*a-v*r*u+t*S*u+s*r*_-t*l*_)*L,e[7]=(s*p*a-d*l*a+d*r*u-t*p*u-s*r*m+t*l*m)*L,e[8]=b*L,e[9]=(v*f*a-d*x*a-v*i*m+t*x*m+d*i*_-t*f*_)*L,e[10]=(s*x*a-v*o*a+v*i*u-t*x*u-s*i*_+t*o*_)*L,e[11]=(d*o*a-s*f*a-d*i*u+t*f*u+s*i*m-t*o*m)*L,e[12]=R*L,e[13]=(d*x*r-v*f*r+v*i*p-t*x*p-d*i*S+t*f*S)*L,e[14]=(v*o*r-s*x*r-v*i*l+t*x*l+s*i*S-t*o*S)*L,e[15]=(s*f*r-d*o*r+d*i*l-t*f*l-s*i*p+t*o*p)*L,this}scale(e){const t=this.elements,i=e.x,r=e.y,a=e.z;return t[0]*=i,t[4]*=r,t[8]*=a,t[1]*=i,t[5]*=r,t[9]*=a,t[2]*=i,t[6]*=r,t[10]*=a,t[3]*=i,t[7]*=r,t[11]*=a,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,r))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),r=Math.sin(t),a=1-i,s=e.x,o=e.y,l=e.z,u=a*s,d=a*o;return this.set(u*s+i,u*o-r*l,u*l+r*o,0,u*o+r*l,d*o+i,d*l-r*s,0,u*l-r*o,d*l+r*s,a*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,r,a,s){return this.set(1,i,a,0,e,1,s,0,t,r,1,0,0,0,0,1),this}compose(e,t,i){const r=this.elements,a=t._x,s=t._y,o=t._z,l=t._w,u=a+a,d=s+s,f=o+o,p=a*u,m=a*d,v=a*f,x=s*d,S=s*f,_=o*f,T=l*u,E=l*d,b=l*f,R=i.x,w=i.y,L=i.z;return r[0]=(1-(x+_))*R,r[1]=(m+b)*R,r[2]=(v-E)*R,r[3]=0,r[4]=(m-b)*w,r[5]=(1-(p+_))*w,r[6]=(S+T)*w,r[7]=0,r[8]=(v+E)*L,r[9]=(S-T)*L,r[10]=(1-(p+x))*L,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,i){const r=this.elements;let a=Hd.set(r[0],r[1],r[2]).length();const s=Hd.set(r[4],r[5],r[6]).length(),o=Hd.set(r[8],r[9],r[10]).length();this.determinant()<0&&(a=-a),e.x=r[12],e.y=r[13],e.z=r[14],Bs.copy(this);const u=1/a,d=1/s,f=1/o;return Bs.elements[0]*=u,Bs.elements[1]*=u,Bs.elements[2]*=u,Bs.elements[4]*=d,Bs.elements[5]*=d,Bs.elements[6]*=d,Bs.elements[8]*=f,Bs.elements[9]*=f,Bs.elements[10]*=f,t.setFromRotationMatrix(Bs),i.x=a,i.y=s,i.z=o,this}makePerspective(e,t,i,r,a,s,o=ka,l=!1){const u=this.elements,d=2*a/(t-e),f=2*a/(i-r),p=(t+e)/(t-e),m=(i+r)/(i-r);let v,x;if(l)v=a/(s-a),x=s*a/(s-a);else if(o===ka)v=-(s+a)/(s-a),x=-2*s*a/(s-a);else if(o===Ep)v=-s/(s-a),x=-s*a/(s-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return u[0]=d,u[4]=0,u[8]=p,u[12]=0,u[1]=0,u[5]=f,u[9]=m,u[13]=0,u[2]=0,u[6]=0,u[10]=v,u[14]=x,u[3]=0,u[7]=0,u[11]=-1,u[15]=0,this}makeOrthographic(e,t,i,r,a,s,o=ka,l=!1){const u=this.elements,d=2/(t-e),f=2/(i-r),p=-(t+e)/(t-e),m=-(i+r)/(i-r);let v,x;if(l)v=1/(s-a),x=s/(s-a);else if(o===ka)v=-2/(s-a),x=-(s+a)/(s-a);else if(o===Ep)v=-1/(s-a),x=-a/(s-a);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return u[0]=d,u[4]=0,u[8]=0,u[12]=p,u[1]=0,u[5]=f,u[9]=0,u[13]=m,u[2]=0,u[6]=0,u[10]=v,u[14]=x,u[3]=0,u[7]=0,u[11]=0,u[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let r=0;r<16;r++)if(t[r]!==i[r])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const Hd=new D,Bs=new Me,HX=new D(0,0,0),VX=new D(1,1,1),oc=new D,T_=new D,Oa=new D,tO=new Me,nO=new ft;class Ai{constructor(e=0,t=0,i=0,r=Ai.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=r}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,r=this._order){return this._x=e,this._y=t,this._z=i,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const r=e.elements,a=r[0],s=r[4],o=r[8],l=r[1],u=r[5],d=r[9],f=r[2],p=r[6],m=r[10];switch(t){case"XYZ":this._y=Math.asin(It(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-d,m),this._z=Math.atan2(-s,a)):(this._x=Math.atan2(p,u),this._z=0);break;case"YXZ":this._x=Math.asin(-It(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(o,m),this._z=Math.atan2(l,u)):(this._y=Math.atan2(-f,a),this._z=0);break;case"ZXY":this._x=Math.asin(It(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-f,m),this._z=Math.atan2(-s,u)):(this._y=0,this._z=Math.atan2(l,a));break;case"ZYX":this._y=Math.asin(-It(f,-1,1)),Math.abs(f)<.9999999?(this._x=Math.atan2(p,m),this._z=Math.atan2(l,a)):(this._x=0,this._z=Math.atan2(-s,u));break;case"YZX":this._z=Math.asin(It(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-d,u),this._y=Math.atan2(-f,a)):(this._x=0,this._y=Math.atan2(o,m));break;case"XZY":this._z=Math.asin(-It(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(p,u),this._y=Math.atan2(o,a)):(this._x=Math.atan2(-d,m),this._y=0);break;default:dt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return tO.makeRotationFromQuaternion(e),this.setFromRotationMatrix(tO,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return nO.setFromEuler(this),this.setFromQuaternion(nO,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Ai.DEFAULT_ORDER="XYZ";class Ap{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(o=>({...o})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function a(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=a(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let u=0,d=l.length;u0){r.children=[];for(let o=0;o0){r.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),u.length>0&&(i.textures=u),d.length>0&&(i.images=d),f.length>0&&(i.shapes=f),p.length>0&&(i.skeletons=p),m.length>0&&(i.animations=m),v.length>0&&(i.nodes=v)}return i.object=r,i;function s(o){const l=[];for(const u in o){const d=o[u];delete d.metadata,l.push(d)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i0?r.multiplyScalar(1/Math.sqrt(a)):r.set(0,0,0)}static getBarycoord(e,t,i,r,a){Fs.subVectors(r,t),nl.subVectors(i,t),kE.subVectors(e,t);const s=Fs.dot(Fs),o=Fs.dot(nl),l=Fs.dot(kE),u=nl.dot(nl),d=nl.dot(kE),f=s*u-o*o;if(f===0)return a.set(0,0,0),null;const p=1/f,m=(u*l-o*d)*p,v=(s*d-o*l)*p;return a.set(1-m-v,v,m)}static containsPoint(e,t,i,r){return this.getBarycoord(e,t,i,r,il)===null?!1:il.x>=0&&il.y>=0&&il.x+il.y<=1}static getInterpolation(e,t,i,r,a,s,o,l){return this.getBarycoord(e,t,i,r,il)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(a,il.x),l.addScaledVector(s,il.y),l.addScaledVector(o,il.z),l)}static getInterpolatedAttribute(e,t,i,r,a,s){return YE.setScalar(0),jE.setScalar(0),ZE.setScalar(0),YE.fromBufferAttribute(e,t),jE.fromBufferAttribute(e,i),ZE.fromBufferAttribute(e,r),s.setScalar(0),s.addScaledVector(YE,a.x),s.addScaledVector(jE,a.y),s.addScaledVector(ZE,a.z),s}static isFrontFacing(e,t,i,r){return Fs.subVectors(i,t),nl.subVectors(e,t),Fs.cross(nl).dot(r)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,r){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,i,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Fs.subVectors(this.c,this.b),nl.subVectors(this.a,this.b),Fs.cross(nl).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return fa.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return fa.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,r,a){return fa.getInterpolation(e,this.a,this.b,this.c,t,i,r,a)}containsPoint(e){return fa.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return fa.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,r=this.b,a=this.c;let s,o;kd.subVectors(r,i),Wd.subVectors(a,i),WE.subVectors(e,i);const l=kd.dot(WE),u=Wd.dot(WE);if(l<=0&&u<=0)return t.copy(i);XE.subVectors(e,r);const d=kd.dot(XE),f=Wd.dot(XE);if(d>=0&&f<=d)return t.copy(r);const p=l*f-d*u;if(p<=0&&l>=0&&d<=0)return s=l/(l-d),t.copy(i).addScaledVector(kd,s);qE.subVectors(e,a);const m=kd.dot(qE),v=Wd.dot(qE);if(v>=0&&m<=v)return t.copy(a);const x=m*u-l*v;if(x<=0&&u>=0&&v<=0)return o=u/(u-v),t.copy(i).addScaledVector(Wd,o);const S=d*v-m*f;if(S<=0&&f-d>=0&&m-v>=0)return lO.subVectors(a,r),o=(f-d)/(f-d+(m-v)),t.copy(r).addScaledVector(lO,o);const _=1/(S+x+p);return s=x*_,o=p*_,t.copy(i).addScaledVector(kd,s).addScaledVector(Wd,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const I9={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},lc={h:0,s:0,l:0},b_={h:0,s:0,l:0};function QE(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class Ye{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=mn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,tn.colorSpaceToWorking(this,t),this}setRGB(e,t,i,r=tn.workingColorSpace){return this.r=e,this.g=t,this.b=i,tn.colorSpaceToWorking(this,r),this}setHSL(e,t,i,r=tn.workingColorSpace){if(e=iR(e,1),t=It(t,0,1),i=It(i,0,1),t===0)this.r=this.g=this.b=i;else{const a=i<=.5?i*(1+t):i+t-i*t,s=2*i-a;this.r=QE(s,a,e+1/3),this.g=QE(s,a,e),this.b=QE(s,a,e-1/3)}return tn.colorSpaceToWorking(this,r),this}setStyle(e,t=mn){function i(a){a!==void 0&&parseFloat(a)<1&&dt("Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let a;const s=r[1],o=r[2];switch(s){case"rgb":case"rgba":if(a=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(255,parseInt(a[1],10))/255,Math.min(255,parseInt(a[2],10))/255,Math.min(255,parseInt(a[3],10))/255,t);if(a=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setRGB(Math.min(100,parseInt(a[1],10))/100,Math.min(100,parseInt(a[2],10))/100,Math.min(100,parseInt(a[3],10))/100,t);break;case"hsl":case"hsla":if(a=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(a[4]),this.setHSL(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,t);break;default:dt("Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){const a=r[1],s=a.length;if(s===3)return this.setRGB(parseInt(a.charAt(0),16)/15,parseInt(a.charAt(1),16)/15,parseInt(a.charAt(2),16)/15,t);if(s===6)return this.setHex(parseInt(a,16),t);dt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=mn){const i=I9[e.toLowerCase()];return i!==void 0?this.setHex(i,t):dt("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=Cl(e.r),this.g=Cl(e.g),this.b=Cl(e.b),this}copyLinearToSRGB(e){return this.r=ip(e.r),this.g=ip(e.g),this.b=ip(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=mn){return tn.workingToColorSpace(Dr.copy(this),e),Math.round(It(Dr.r*255,0,255))*65536+Math.round(It(Dr.g*255,0,255))*256+Math.round(It(Dr.b*255,0,255))}getHexString(e=mn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=tn.workingColorSpace){tn.workingToColorSpace(Dr.copy(this),t);const i=Dr.r,r=Dr.g,a=Dr.b,s=Math.max(i,r,a),o=Math.min(i,r,a);let l,u;const d=(o+s)/2;if(o===s)l=0,u=0;else{const f=s-o;switch(u=d<=.5?f/(s+o):f/(2-s-o),s){case i:l=(r-a)/f+(r0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){dt(`Material: parameter '${t}' has value of undefined.`);continue}const r=this[t];if(r===void 0){dt(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(i):r&&r.isVector3&&i&&i.isVector3?r.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==Eh&&(i.blending=this.blending),this.side!==eo&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==Y1&&(i.blendSrc=this.blendSrc),this.blendDst!==j1&&(i.blendDst=this.blendDst),this.blendEquation!==bo&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==Ih&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==F3&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==sh&&(i.stencilFail=this.stencilFail),this.stencilZFail!==sh&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==sh&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function r(a){const s=[];for(const o in a){const l=a[o];delete l.metadata,s.push(l)}return s}if(t){const a=r(e.textures),s=r(e.images);a.length>0&&(i.textures=a),s.length>0&&(i.images=s)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const r=t.length;i=new Array(r);for(let a=0;a!==r;++a)i[a]=t[a].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Sr extends ei{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ye(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 Ai,this.combine=Jg,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 Sl=YX();function YX(){const n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),r=new Uint32Array(512);for(let l=0;l<256;++l){const u=l-127;u<-27?(i[l]=0,i[l|256]=32768,r[l]=24,r[l|256]=24):u<-14?(i[l]=1024>>-u-14,i[l|256]=1024>>-u-14|32768,r[l]=-u-1,r[l|256]=-u-1):u<=15?(i[l]=u+15<<10,i[l|256]=u+15<<10|32768,r[l]=13,r[l|256]=13):u<128?(i[l]=31744,i[l|256]=64512,r[l]=24,r[l|256]=24):(i[l]=31744,i[l|256]=64512,r[l]=13,r[l|256]=13)}const a=new Uint32Array(2048),s=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let u=l<<13,d=0;for(;!(u&8388608);)u<<=1,d-=8388608;u&=-8388609,d+=947912704,a[l]=u|d}for(let l=1024;l<2048;++l)a[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)s[l]=l<<23;s[31]=1199570944,s[32]=2147483648;for(let l=33;l<63;++l)s[l]=2147483648+(l-32<<23);s[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:r,mantissaTable:a,exponentTable:s,offsetTable:o}}function la(n){Math.abs(n)>65504&&dt("DataUtils.toHalfFloat(): Value out of range."),n=It(n,-65504,65504),Sl.floatView[0]=n;const e=Sl.uint32View[0],t=e>>23&511;return Sl.baseTable[t]+((e&8388607)>>Sl.shiftTable[t])}function A0(n){const e=n>>10;return Sl.uint32View[0]=Sl.mantissaTable[Sl.offsetTable[e]+(n&1023)]+Sl.exponentTable[e],Sl.floatView[0]}class H3{static toHalfFloat(e){return la(e)}static fromHalfFloat(e){return A0(e)}}const zi=new D,M_=new re;let jX=0;class bt{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:jX++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=Rg,this.updateRanges=[],this.gpuType=fi,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let r=0,a=this.itemSize;rt.count&&dt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Qi);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ht("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new D(-1/0,-1/0,-1/0),new D(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,r=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const u in l)l[u]!==void 0&&(e[u]=l[u]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const u=i[l];e.data.attributes[l]=u.toJSON(e.data)}const r={};let a=!1;for(const l in this.morphAttributes){const u=this.morphAttributes[l],d=[];for(let f=0,p=u.length;f0&&(r[l]=d,a=!0)}a&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const r=e.attributes;for(const u in r){const d=r[u];this.setAttribute(u,d.clone(t))}const a=e.morphAttributes;for(const u in a){const d=[],f=a[u];for(let p=0,m=f.length;p0){const r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,s=r.length;a(e.far-e.near)**2))&&(cO.copy(a).invert(),Lu.copy(e.ray).applyMatrix4(cO),!(i.boundingBox!==null&&Lu.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,Lu)))}_computeIntersections(e,t,i){let r;const a=this.geometry,s=this.material,o=a.index,l=a.attributes.position,u=a.attributes.uv,d=a.attributes.uv1,f=a.attributes.normal,p=a.groups,m=a.drawRange;if(o!==null)if(Array.isArray(s))for(let v=0,x=p.length;vt.far?null:{distance:u,point:N_.clone(),object:n}}function O_(n,e,t,i,r,a,s,o,l,u){n.getVertexPosition(o,w_),n.getVertexPosition(l,R_),n.getVertexPosition(u,C_);const d=nq(n,e,t,i,w_,R_,C_,hO);if(d){const f=new D;fa.getBarycoord(hO,w_,R_,C_,f),r&&(d.uv=fa.getInterpolatedAttribute(r,o,l,u,f,new re)),a&&(d.uv1=fa.getInterpolatedAttribute(a,o,l,u,f,new re)),s&&(d.normal=fa.getInterpolatedAttribute(s,o,l,u,f,new D),d.normal.dot(i.direction)>0&&d.normal.multiplyScalar(-1));const p={a:o,b:l,c:u,normal:new D,materialIndex:0};fa.getNormal(w_,R_,C_,p.normal),d.face=p,d.barycoord=f}return d}class $h extends Ct{constructor(e=1,t=1,i=1,r=1,a=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:r,heightSegments:a,depthSegments:s};const o=this;r=Math.floor(r),a=Math.floor(a),s=Math.floor(s);const l=[],u=[],d=[],f=[];let p=0,m=0;v("z","y","x",-1,-1,i,t,e,s,a,0),v("z","y","x",1,-1,i,t,-e,s,a,1),v("x","z","y",1,1,e,i,t,r,s,2),v("x","z","y",1,-1,e,i,-t,r,s,3),v("x","y","z",1,-1,e,t,i,r,a,4),v("x","y","z",-1,-1,e,t,-i,r,a,5),this.setIndex(l),this.setAttribute("position",new St(u,3)),this.setAttribute("normal",new St(d,3)),this.setAttribute("uv",new St(f,2));function v(x,S,_,T,E,b,R,w,L,U,N){const C=b/L,z=R/U,W=b/2,K=R/2,oe=w/2,ae=L+1,X=U+1;let te=0,Q=0;const ce=new D;for(let se=0;se0?1:-1,d.push(ce.x,ce.y,ce.z),f.push(Xe/L),f.push(1-se/U),te+=1}}for(let se=0;se0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const r in this.extensions)this.extensions[r]===!0&&(i[r]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class ou extends Xt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Me,this.projectionMatrix=new Me,this.projectionMatrixInverse=new Me,this.coordinateSystem=ka,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const cc=new D,dO=new re,fO=new re;let si=class extends ou{constructor(e=50,t=1,i=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Mp*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(bh*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Mp*2*Math.atan(Math.tan(bh*.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,t,i){cc.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(cc.x,cc.y).multiplyScalar(-e/cc.z),cc.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(cc.x,cc.y).multiplyScalar(-e/cc.z)}getViewSize(e,t){return this.getViewBounds(e,dO,fO),t.subVectors(fO,dO)}setViewOffset(e,t,i,r,a,s){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=r,this.view.width=a,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(bh*.5*this.fov)/this.zoom,i=2*t,r=this.aspect*i,a=-.5*r;const s=this.view;if(this.view!==null&&this.view.enabled){const l=s.fullWidth,u=s.fullHeight;a+=s.offsetX*r/l,t-=s.offsetY*i/u,r*=s.width/l,i*=s.height/u}const o=this.filmOffset;o!==0&&(a+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(a,a+r,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}};const qd=-90,Yd=1;class P9 extends Xt{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const r=new si(qd,Yd,e,t);r.layers=this.layers,this.add(r);const a=new si(qd,Yd,e,t);a.layers=this.layers,this.add(a);const s=new si(qd,Yd,e,t);s.layers=this.layers,this.add(s);const o=new si(qd,Yd,e,t);o.layers=this.layers,this.add(o);const l=new si(qd,Yd,e,t);l.layers=this.layers,this.add(l);const u=new si(qd,Yd,e,t);u.layers=this.layers,this.add(u)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,r,a,s,o,l]=t;for(const u of t)this.remove(u);if(e===ka)i.up.set(0,1,0),i.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),a.up.set(0,0,-1),a.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===Ep)i.up.set(0,-1,0),i.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),a.up.set(0,0,1),a.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const u of t)this.add(u),u.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[a,s,o,l,u,d]=this.children,f=e.getRenderTarget(),p=e.getActiveCubeFace(),m=e.getActiveMipmapLevel(),v=e.xr.enabled;e.xr.enabled=!1;const x=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,r),e.render(t,a),e.setRenderTarget(i,1,r),e.render(t,s),e.setRenderTarget(i,2,r),e.render(t,o),e.setRenderTarget(i,3,r),e.render(t,l),e.setRenderTarget(i,4,r),e.render(t,u),i.texture.generateMipmaps=x,e.setRenderTarget(i,5,r),e.render(t,d),e.setRenderTarget(f,p,m),e.xr.enabled=v,i.texture.needsPMREMUpdate=!0}}class tv extends In{constructor(e=[],t=Pl,i,r,a,s,o,l,u,d){super(e,t,i,r,a,s,o,l,u,d),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class z9 extends pi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},r=[i,i,i,i,i,i];this.texture=new tv(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},r=new $h(5,5,5),a=new Oi({name:"CubemapFromEquirect",uniforms:wp(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:ki,blending:Lr});a.uniforms.tEquirect.value=t;const s=new jn(r,a),o=t.minFilter;return t.minFilter===Ga&&(t.minFilter=Bt),new P9(1,10,this).update(e,s),t.minFilter=o,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,i=!0,r=!0){const a=e.getRenderTarget();for(let s=0;s<6;s++)e.setRenderTarget(this,s),e.clear(t,i,r);e.setRenderTarget(a)}}class Xi extends Xt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const sq={type:"move"};class c1{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Xi,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Xi,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new D,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new D),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Xi,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new D,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new D),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let r=null,a=null,s=null;const o=this._targetRay,l=this._grip,u=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(u&&e.hand){s=!0;for(const x of e.hand.values()){const S=t.getJointPose(x,i),_=this._getHandJoint(u,x);S!==null&&(_.matrix.fromArray(S.transform.matrix),_.matrix.decompose(_.position,_.rotation,_.scale),_.matrixWorldNeedsUpdate=!0,_.jointRadius=S.radius),_.visible=S!==null}const d=u.joints["index-finger-tip"],f=u.joints["thumb-tip"],p=d.position.distanceTo(f.position),m=.02,v=.005;u.inputState.pinching&&p>m+v?(u.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!u.inputState.pinching&&p<=m-v&&(u.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(a=t.getPose(e.gripSpace,i),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,i),r===null&&a!==null&&(r=a),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(sq)))}return o!==null&&(o.visible=r!==null),l!==null&&(l.visible=a!==null),u!==null&&(u.visible=s!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Xi;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class zS{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new Ye(e),this.density=t}clone(){return new zS(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class BS{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new Ye(e),this.near=t,this.far=i}clone(){return new BS(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Rp extends Xt{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Ai,this.environmentIntensity=1,this.environmentRotation=new Ai,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Zp{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Rg,this.updateRanges=[],this.version=0,this.uuid=ja()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let r=0,a=this.stride;re.far||t.push({distance:l,point:Vm.clone(),uv:fa.getInterpolation(Vm,L_,km,I_,pO,$E,mO,new re),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function U_(n,e,t,i,r,a){Kd.subVectors(n,t).addScalar(.5).multiply(i),r!==void 0?(Gm.x=a*Kd.x-r*Kd.y,Gm.y=r*Kd.x+a*Kd.y):Gm.copy(Kd),n.copy(e),n.x+=Gm.x,n.y+=Gm.y,n.applyMatrix4(B9)}const P_=new D,gO=new D;class H9 extends Xt{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,r=t.length;i0){let i,r;for(i=1,r=t.length;i0){P_.setFromMatrixPosition(this.matrixWorld);const r=e.ray.origin.distanceTo(P_);this.getObjectForDistance(r).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){P_.setFromMatrixPosition(e.matrixWorld),gO.setFromMatrixPosition(this.matrixWorld);const i=P_.distanceTo(gO)/e.zoom;t[0].object.visible=!0;let r,a;for(r=1,a=t.length;r=s)t[r-1].object.visible=!1,t[r].object.visible=!0;else break}for(this._currentLevel=r-1;r1?null:t.copy(e.start).addScaledVector(i,a)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||hq.getNormalMatrix(e),r=this.coplanarPoint(nb).applyMatrix4(e),a=this.normal.applyMatrix3(i).normalize();return this.constant=-r.dot(a),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Iu=new qi,dq=new re(.5,.5),F_=new D;class ed{constructor(e=new xs,t=new xs,i=new xs,r=new xs,a=new xs,s=new xs){this.planes=[e,t,i,r,a,s]}set(e,t,i,r,a,s){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(r),o[4].copy(a),o[5].copy(s),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=ka,i=!1){const r=this.planes,a=e.elements,s=a[0],o=a[1],l=a[2],u=a[3],d=a[4],f=a[5],p=a[6],m=a[7],v=a[8],x=a[9],S=a[10],_=a[11],T=a[12],E=a[13],b=a[14],R=a[15];if(r[0].setComponents(u-s,m-d,_-v,R-T).normalize(),r[1].setComponents(u+s,m+d,_+v,R+T).normalize(),r[2].setComponents(u+o,m+f,_+x,R+E).normalize(),r[3].setComponents(u-o,m-f,_-x,R-E).normalize(),i)r[4].setComponents(l,p,S,b).normalize(),r[5].setComponents(u-l,m-p,_-S,R-b).normalize();else if(r[4].setComponents(u-l,m-p,_-S,R-b).normalize(),t===ka)r[5].setComponents(u+l,m+p,_+S,R+b).normalize();else if(t===Ep)r[5].setComponents(l,p,S,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Iu.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Iu.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Iu)}intersectsSprite(e){Iu.center.set(0,0,0);const t=dq.distanceTo(e.center);return Iu.radius=.7071067811865476+t,Iu.applyMatrix4(e.matrixWorld),this.intersectsSphere(Iu)}intersectsSphere(e){const t=this.planes,i=e.center,r=-e.radius;for(let a=0;a<6;a++)if(t[a].distanceToPoint(i)0?e.max.x:e.min.x,F_.y=r.normal.y>0?e.max.y:e.min.y,F_.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(F_)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const po=new Me,mo=new ed;class GS{constructor(){this.coordinateSystem=ka}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let i=0;i=a.length&&a.push({start:-1,count:-1,z:-1,index:-1});const o=a[this.index];s.push(o),this.index++,o.start=e,o.count=t,o.z=i,o.index=r}reset(){this.list.length=0,this.index=0}}const ra=new Me,gq=new Ye(1,1,1),MO=new ed,vq=new GS,H_=new Qi,Uu=new qi,qm=new D,AO=new D,_q=new D,rb=new mq,Nr=new jn,V_=[];function xq(n,e,t=0){const i=e.itemSize;if(n.isInterleavedBufferAttribute||n.array.constructor!==e.array.constructor){const r=n.count;for(let a=0;a65535?new Uint32Array(r):new Uint16Array(r);t.setIndex(new bt(a,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const r=e.getAttribute(i),a=t.getAttribute(i);if(r.itemSize!==a.itemSize||r.normalized!==a.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){const t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Qi);const e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let i=0,r=t.length;i=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const i={visible:!0,active:!0,geometryIndex:e};let r=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(ib),r=this._availableInstanceIds.shift(),this._instanceInfo[r]=i):(r=this._instanceInfo.length,this._instanceInfo.push(i));const a=this._matricesTexture;ra.identity().toArray(a.image.data,r*16),a.needsUpdate=!0;const s=this._colorsTexture;return s&&(gq.toArray(s.image.data,r*4),s.needsUpdate=!0),this._visibilityChanged=!0,r}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e);const r={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},a=this._geometryInfo;r.vertexStart=this._nextVertexStart,r.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const s=e.getIndex();if(s!==null&&(r.indexStart=this._nextIndexStart,r.reservedIndexCount=i===-1?s.count:i),r.indexStart!==-1&&r.indexStart+r.reservedIndexCount>this._maxIndexCount||r.vertexStart+r.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let l;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(ib),l=this._availableGeometryIds.shift(),a[l]=r):(l=this._geometryCount,this._geometryCount++,a.push(r)),this.setGeometryAt(l,e),this._nextIndexStart=r.indexStart+r.reservedIndexCount,this._nextVertexStart=r.vertexStart+r.reservedVertexCount,l}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,r=i.getIndex()!==null,a=i.getIndex(),s=t.getIndex(),o=this._geometryInfo[e];if(r&&s.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,u=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const d in i.attributes){const f=t.getAttribute(d),p=i.getAttribute(d);xq(f,p,l);const m=f.itemSize;for(let v=f.count,x=u;v=t.length||t[e].active===!1)return this;const i=this._instanceInfo;for(let r=0,a=i.length;ro).sort((s,o)=>i[s].vertexStart-i[o].vertexStart),a=this.geometry;for(let s=0,o=i.length;s=this._geometryCount)return null;const i=this.geometry,r=this._geometryInfo[e];if(r.boundingBox===null){const a=new Qi,s=i.index,o=i.attributes.position;for(let l=r.start,u=r.start+r.count;l=this._geometryCount)return null;const i=this.geometry,r=this._geometryInfo[e];if(r.boundingSphere===null){const a=new qi;this.getBoundingBoxAt(e,H_),H_.getCenter(a.center);const s=i.index,o=i.attributes.position;let l=0;for(let u=r.start,d=r.start+r.count;uo.active);if(Math.max(...i.map(o=>o.vertexStart+o.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...i.map(l=>l.indexStart+l.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);const a=this.geometry;a.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Ct,this._initializeGeometry(a));const s=this.geometry;a.index&&Pu(a.index.array,s.index.array);for(const o in a.attributes)Pu(a.attributes[o].array,s.attributes[o].array)}raycast(e,t){const i=this._instanceInfo,r=this._geometryInfo,a=this.matrixWorld,s=this.geometry;Nr.material=this.material,Nr.geometry.index=s.index,Nr.geometry.attributes=s.attributes,Nr.geometry.boundingBox===null&&(Nr.geometry.boundingBox=new Qi),Nr.geometry.boundingSphere===null&&(Nr.geometry.boundingSphere=new qi);for(let o=0,l=i.length;o({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,i,r,a){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const s=r.getIndex(),o=s===null?1:s.array.BYTES_PER_ELEMENT,l=this._instanceInfo,u=this._multiDrawStarts,d=this._multiDrawCounts,f=this._geometryInfo,p=this.perObjectFrustumCulled,m=this._indirectTexture,v=m.image.data,x=i.isArrayCamera?vq:MO;p&&!i.isArrayCamera&&(ra.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),MO.setFromProjectionMatrix(ra,i.coordinateSystem,i.reversedDepth));let S=0;if(this.sortObjects){ra.copy(this.matrixWorld).invert(),qm.setFromMatrixPosition(i.matrixWorld).applyMatrix4(ra),AO.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(ra);for(let E=0,b=l.length;E0){const r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,s=r.length;ai)return;ab.applyMatrix4(n.matrixWorld);const u=e.ray.origin.distanceTo(ab);if(!(ue.far))return{distance:u,point:RO.clone().applyMatrix4(n.matrixWorld),index:s,face:null,faceIndex:null,barycoord:null,object:n}}const CO=new D,DO=new D;class va extends Oo{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let r=0,a=t.count;r0){const r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,s=r.length;ar.far)return;a.push({distance:u,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:s})}}class G9 extends In{constructor(e,t,i,r,a=Bt,s=Bt,o,l,u){super(e,t,i,r,a,s,o,l,u),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const d=this;function f(){d.needsUpdate=!0,d._requestVideoFrameCallbackId=e.requestVideoFrameCallback(f)}"requestVideoFrameCallback"in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(f))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}}class yq extends G9{constructor(e,t,i,r,a,s,o,l){super({},e,t,i,r,a,s,o,l),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}}class Sq extends In{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=Yn,this.minFilter=Yn,this.generateMipmaps=!1,this.needsUpdate=!0}}class WS extends In{constructor(e,t,i,r,a,s,o,l,u,d,f,p){super(null,s,o,l,u,d,r,a,f,p),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class Tq extends WS{constructor(e,t,i,r,a,s){super(e,t,i,a,s),this.isCompressedArrayTexture=!0,this.image.depth=r,this.wrapR=Wi,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class Eq extends WS{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,Pl),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class bq extends In{constructor(e,t,i,r,a,s,o,l,u){super(e,t,i,r,a,s,o,l,u),this.isCanvasTexture=!0,this.needsUpdate=!0}}class iv extends In{constructor(e,t,i=to,r,a,s,o=Yn,l=Yn,u,d=yp,f=1){if(d!==yp&&d!==zh)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const p={width:e,height:t,depth:f};super(p,r,a,s,o,l,d,i,u),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Lc(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class uR extends In{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class XS extends Ct{constructor(e=1,t=1,i=4,r=8,a=1){super(),this.type="CapsuleGeometry",this.parameters={radius:e,height:t,capSegments:i,radialSegments:r,heightSegments:a},t=Math.max(0,t),i=Math.max(1,Math.floor(i)),r=Math.max(3,Math.floor(r)),a=Math.max(1,Math.floor(a));const s=[],o=[],l=[],u=[],d=t/2,f=Math.PI/2*e,p=t,m=2*f+p,v=i*2+a,x=r+1,S=new D,_=new D;for(let T=0;T<=v;T++){let E=0,b=0,R=0,w=0;if(T<=i){const N=T/i,C=N*Math.PI/2;b=-d-e*Math.cos(C),R=e*Math.sin(C),w=-e*Math.cos(C),E=N*f}else if(T<=i+a){const N=(T-i)/a;b=-d+N*t,R=e,w=0,E=f+N*p}else{const N=(T-i-a)/i,C=N*Math.PI/2;b=d+e*Math.sin(C),R=e*Math.cos(C),w=e*Math.sin(C),E=f+p+N*f}const L=Math.max(0,Math.min(1,E/m));let U=0;T===0?U=.5/r:T===v&&(U=-.5/r);for(let N=0;N<=r;N++){const C=N/r,z=C*Math.PI*2,W=Math.sin(z),K=Math.cos(z);_.x=-R*K,_.y=b,_.z=R*W,o.push(_.x,_.y,_.z),S.set(-R*K,w,R*W),S.normalize(),l.push(S.x,S.y,S.z),u.push(C+U,L)}if(T>0){const N=(T-1)*x;for(let C=0;C0&&E(!0),t>0&&E(!1)),this.setIndex(d),this.setAttribute("position",new St(f,3)),this.setAttribute("normal",new St(p,3)),this.setAttribute("uv",new St(m,2));function T(){const b=new D,R=new D;let w=0;const L=(t-e)/i;for(let U=0;U<=a;U++){const N=[],C=U/a,z=C*(t-e)+e;for(let W=0;W<=r;W++){const K=W/r,oe=K*l+o,ae=Math.sin(oe),X=Math.cos(oe);R.x=z*ae,R.y=-C*i+S,R.z=z*X,f.push(R.x,R.y,R.z),b.set(ae,L,X).normalize(),p.push(b.x,b.y,b.z),m.push(K,1-C),N.push(v++)}x.push(N)}for(let U=0;U0||N!==0)&&(d.push(C,z,K),w+=3),(t>0||N!==a-1)&&(d.push(z,W,K),w+=3)}u.addGroup(_,w,0),_+=w}function E(b){const R=v,w=new re,L=new D;let U=0;const N=b===!0?e:t,C=b===!0?1:-1;for(let W=1;W<=r;W++)f.push(0,S*C,0),p.push(0,C,0),m.push(.5,.5),v++;const z=v;for(let W=0;W<=r;W++){const oe=W/r*l+o,ae=Math.cos(oe),X=Math.sin(oe);L.x=N*X,L.y=S*C,L.z=N*ae,f.push(L.x,L.y,L.z),p.push(0,C,0),w.x=ae*.5+.5,w.y=X*.5*C+.5,m.push(w.x,w.y),v++}for(let W=0;W.9&&L<.1&&(E<.2&&(s[T+0]+=1),b<.2&&(s[T+2]+=1),R<.2&&(s[T+4]+=1))}}function p(T){a.push(T.x,T.y,T.z)}function m(T,E){const b=T*3;E.x=e[b+0],E.y=e[b+1],E.z=e[b+2]}function v(){const T=new D,E=new D,b=new D,R=new D,w=new re,L=new re,U=new re;for(let N=0,C=0;N0)l=r-1;else{l=r;break}if(r=l,i[r]===s)return r/(a-1);const d=i[r],p=i[r+1]-d,m=(s-d)/p;return(r+m)/(a-1)}getTangent(e,t){let r=e-1e-4,a=e+1e-4;r<0&&(r=0),a>1&&(a=1);const s=this.getPoint(r),o=this.getPoint(a),l=t||(s.isVector2?new re:new D);return l.copy(o).sub(s).normalize(),l}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new D,r=[],a=[],s=[],o=new D,l=new Me;for(let m=0;m<=e;m++){const v=m/e;r[m]=this.getTangentAt(v,new D)}a[0]=new D,s[0]=new D;let u=Number.MAX_VALUE;const d=Math.abs(r[0].x),f=Math.abs(r[0].y),p=Math.abs(r[0].z);d<=u&&(u=d,i.set(1,0,0)),f<=u&&(u=f,i.set(0,1,0)),p<=u&&i.set(0,0,1),o.crossVectors(r[0],i).normalize(),a[0].crossVectors(r[0],o),s[0].crossVectors(r[0],a[0]);for(let m=1;m<=e;m++){if(a[m]=a[m-1].clone(),s[m]=s[m-1].clone(),o.crossVectors(r[m-1],r[m]),o.length()>Number.EPSILON){o.normalize();const v=Math.acos(It(r[m-1].dot(r[m]),-1,1));a[m].applyMatrix4(l.makeRotationAxis(o,v))}s[m].crossVectors(r[m],a[m])}if(t===!0){let m=Math.acos(It(a[0].dot(a[e]),-1,1));m/=e,r[0].dot(o.crossVectors(a[0],a[e]))>0&&(m=-m);for(let v=1;v<=e;v++)a[v].applyMatrix4(l.makeRotationAxis(r[v],m*v)),s[v].crossVectors(r[v],a[v])}return{tangents:r,normals:a,binormals:s}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class jS extends io{constructor(e=0,t=0,i=1,r=1,a=0,s=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=r,this.aStartAngle=a,this.aEndAngle=s,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new re){const i=t,r=Math.PI*2;let a=this.aEndAngle-this.aStartAngle;const s=Math.abs(a)r;)a-=r;a0?0:(Math.floor(Math.abs(o)/a)+1)*a:l===0&&o===a-1&&(o=a-2,l=1);let u,d;this.closed||o>0?u=r[(o-1)%a]:(Z_.subVectors(r[0],r[1]).add(r[0]),u=Z_);const f=r[o%a],p=r[(o+1)%a];if(this.closed||o+2r.length-2?r.length-1:s+1],f=r[s>r.length-3?r.length-1:s+2];return i.set(LO(o,l.x,u.x,d.x,f.x),LO(o,l.y,u.y,d.y,f.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t=i){const s=r[a]-i,o=this.curves[a],l=o.getLength(),u=l===0?0:1-s/l;return o.getPointAt(u,t)}a++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,r=this.curves.length;i1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t0){const f=u.getPoint(0);f.equals(this.currentPoint)||this.lineTo(f.x,f.y)}this.curves.push(u);const d=u.getPoint(1);return this.currentPoint.copy(d),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Mh extends Ly{constructor(e){super(e),this.uuid=ja(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,r=this.holes.length;i80*t){o=n[0],l=n[1];let d=o,f=l;for(let p=t;pd&&(d=m),v>f&&(f=v)}u=Math.max(d-o,f-l),u=u!==0?32767/u:0}return Ng(a,s,t,o,l,u,0),s}function Z9(n,e,t,i,r){let a;if(r===jq(n,e,t,i)>0)for(let s=e;s=e;s-=i)a=IO(s/i|0,n[s],n[s+1],a);return a&&Cp(a,a.next)&&(Lg(a),a=a.next),a}function Fh(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(Cp(t,t.next)||_i(t.prev,t,t.next)===0)){if(Lg(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Ng(n,e,t,i,r,a,s){if(!n)return;!s&&a&&Gq(n,i,r,a);let o=n;for(;n.prev!==n.next;){const l=n.prev,u=n.next;if(a?Iq(n,i,r,a):Lq(n)){e.push(l.i,n.i,u.i),Lg(n),n=u.next,o=u.next;continue}if(n=u,n===o){s?s===1?(n=Uq(Fh(n),e),Ng(n,e,t,i,r,a,2)):s===2&&Pq(n,e,t,i,r,a):Ng(Fh(n),e,t,i,r,a,1);break}}}function Lq(n){const e=n.prev,t=n,i=n.next;if(_i(e,t,i)>=0)return!1;const r=e.x,a=t.x,s=i.x,o=e.y,l=t.y,u=i.y,d=Math.min(r,a,s),f=Math.min(o,l,u),p=Math.max(r,a,s),m=Math.max(o,l,u);let v=i.next;for(;v!==e;){if(v.x>=d&&v.x<=p&&v.y>=f&&v.y<=m&&w0(r,o,a,l,s,u,v.x,v.y)&&_i(v.prev,v,v.next)>=0)return!1;v=v.next}return!0}function Iq(n,e,t,i){const r=n.prev,a=n,s=n.next;if(_i(r,a,s)>=0)return!1;const o=r.x,l=a.x,u=s.x,d=r.y,f=a.y,p=s.y,m=Math.min(o,l,u),v=Math.min(d,f,p),x=Math.max(o,l,u),S=Math.max(d,f,p),_=G3(m,v,e,t,i),T=G3(x,S,e,t,i);let E=n.prevZ,b=n.nextZ;for(;E&&E.z>=_&&b&&b.z<=T;){if(E.x>=m&&E.x<=x&&E.y>=v&&E.y<=S&&E!==r&&E!==s&&w0(o,d,l,f,u,p,E.x,E.y)&&_i(E.prev,E,E.next)>=0||(E=E.prevZ,b.x>=m&&b.x<=x&&b.y>=v&&b.y<=S&&b!==r&&b!==s&&w0(o,d,l,f,u,p,b.x,b.y)&&_i(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;E&&E.z>=_;){if(E.x>=m&&E.x<=x&&E.y>=v&&E.y<=S&&E!==r&&E!==s&&w0(o,d,l,f,u,p,E.x,E.y)&&_i(E.prev,E,E.next)>=0)return!1;E=E.prevZ}for(;b&&b.z<=T;){if(b.x>=m&&b.x<=x&&b.y>=v&&b.y<=S&&b!==r&&b!==s&&w0(o,d,l,f,u,p,b.x,b.y)&&_i(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function Uq(n,e){let t=n;do{const i=t.prev,r=t.next.next;!Cp(i,r)&&K9(i,t,t.next,r)&&Og(i,r)&&Og(r,i)&&(e.push(i.i,t.i,r.i),Lg(t),Lg(t.next),t=n=r),t=t.next}while(t!==n);return Fh(t)}function Pq(n,e,t,i,r,a){let s=n;do{let o=s.next.next;for(;o!==s.prev;){if(s.i!==o.i&&Xq(s,o)){let l=J9(s,o);s=Fh(s,s.next),l=Fh(l,l.next),Ng(s,e,t,i,r,a,0),Ng(l,e,t,i,r,a,0);return}o=o.next}s=s.next}while(s!==n)}function zq(n,e,t,i){const r=[];for(let a=0,s=e.length;a=t.next.y&&t.next.y!==t.y){const f=t.x+(r-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(f<=i&&f>a&&(a=f,s=t.x=t.x&&t.x>=l&&i!==t.x&&Q9(rs.x||t.x===s.x&&Vq(s,t)))&&(s=t,d=f)}t=t.next}while(t!==o);return s}function Vq(n,e){return _i(n.prev,n,e.prev)<0&&_i(e.next,n,n.next)<0}function Gq(n,e,t,i){let r=n;do r.z===0&&(r.z=G3(r.x,r.y,e,t,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==n);r.prevZ.nextZ=null,r.prevZ=null,kq(r)}function kq(n){let e,t=1;do{let i=n,r;n=null;let a=null;for(e=0;i;){e++;let s=i,o=0;for(let u=0;u0||l>0&&s;)o!==0&&(l===0||!s||i.z<=s.z)?(r=i,i=i.nextZ,o--):(r=s,s=s.nextZ,l--),a?a.nextZ=r:n=r,r.prevZ=a,a=r;i=s}a.nextZ=null,t*=2}while(e>1);return n}function G3(n,e,t,i,r){return n=(n-t)*r|0,e=(e-i)*r|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function Wq(n){let e=n,t=n;do(e.x=(n-s)*(a-o)&&(n-s)*(i-o)>=(t-s)*(e-o)&&(t-s)*(a-o)>=(r-s)*(i-o)}function w0(n,e,t,i,r,a,s,o){return!(n===s&&e===o)&&Q9(n,e,t,i,r,a,s,o)}function Xq(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!qq(n,e)&&(Og(n,e)&&Og(e,n)&&Yq(n,e)&&(_i(n.prev,n,e.prev)||_i(n,e.prev,e))||Cp(n,e)&&_i(n.prev,n,n.next)>0&&_i(e.prev,e,e.next)>0)}function _i(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function Cp(n,e){return n.x===e.x&&n.y===e.y}function K9(n,e,t,i){const r=K_(_i(n,e,t)),a=K_(_i(n,e,i)),s=K_(_i(t,i,n)),o=K_(_i(t,i,e));return!!(r!==a&&s!==o||r===0&&Q_(n,t,e)||a===0&&Q_(n,i,e)||s===0&&Q_(t,n,i)||o===0&&Q_(t,e,i))}function Q_(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function K_(n){return n>0?1:n<0?-1:0}function qq(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&K9(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function Og(n,e){return _i(n.prev,n,n.next)<0?_i(n,e,n.next)>=0&&_i(n,n.prev,e)>=0:_i(n,e,n.prev)<0||_i(n,n.next,e)<0}function Yq(n,e){let t=n,i=!1;const r=(n.x+e.x)/2,a=(n.y+e.y)/2;do t.y>a!=t.next.y>a&&t.next.y!==t.y&&r<(t.next.x-t.x)*(a-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function J9(n,e){const t=k3(n.i,n.x,n.y),i=k3(e.i,e.x,e.y),r=n.next,a=e.prev;return n.next=e,e.prev=n,t.next=r,r.prev=t,i.next=t,t.prev=i,a.next=i,i.prev=a,i}function IO(n,e,t,i){const r=k3(n,e,t);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Lg(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function k3(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function jq(n,e,t,i){let r=0;for(let a=e,s=t-i;a2&&n[e-1].equals(n[0])&&n.pop()}function PO(n,e){for(let t=0;tNumber.EPSILON){const be=Math.sqrt(P),Ie=Math.sqrt(ht*ht+k*k),Se=V.x-Je/be,yt=V.y+$e/be,je=Ae.x-k/Ie,Tt=Ae.y+ht/Ie,vt=((je-Se)*k-(Tt-yt)*ht)/($e*k-Je*ht);Oe=Se+$e*vt-Ee.x,Ve=yt+Je*vt-Ee.y;const Ue=Oe*Oe+Ve*Ve;if(Ue<=2)return new re(Oe,Ve);Fe=Math.sqrt(Ue/2)}else{let be=!1;$e>Number.EPSILON?ht>Number.EPSILON&&(be=!0):$e<-Number.EPSILON?ht<-Number.EPSILON&&(be=!0):Math.sign(Je)===Math.sign(k)&&(be=!0),be?(Oe=-Je,Ve=$e,Fe=Math.sqrt(P)):(Oe=$e,Ve=Je,Fe=Math.sqrt(P/2))}return new re(Oe/Fe,Ve/Fe)}const ce=[];for(let Ee=0,V=ae.length,Ae=V-1,Oe=Ee+1;Ee=0;Ee--){const V=Ee/S,Ae=m*Math.cos(V*Math.PI/2),Oe=v*Math.sin(V*Math.PI/2)+x;for(let Ve=0,Fe=ae.length;Ve=0;){const Oe=Ae;let Ve=Ae-1;Ve<0&&(Ve=Ee.length-1);for(let Fe=0,$e=d+S*2;Fe<$e;Fe++){const Je=te*Fe,ht=te*(Fe+1),k=V+Oe+Je,P=V+Ve+Je,he=V+Ve+ht,be=V+Oe+ht;wt(k,P,he,be)}}}function de(Ee,V,Ae){l.push(Ee),l.push(V),l.push(Ae)}function it(Ee,V,Ae){ct(Ee),ct(V),ct(Ae);const Oe=r.length/3,Ve=T.generateTopUV(i,r,Oe-3,Oe-2,Oe-1);Qe(Ve[0]),Qe(Ve[1]),Qe(Ve[2])}function wt(Ee,V,Ae,Oe){ct(Ee),ct(V),ct(Oe),ct(V),ct(Ae),ct(Oe);const Ve=r.length/3,Fe=T.generateSideWallUV(i,r,Ve-6,Ve-3,Ve-2,Ve-1);Qe(Fe[0]),Qe(Fe[1]),Qe(Fe[3]),Qe(Fe[1]),Qe(Fe[2]),Qe(Fe[3])}function ct(Ee){r.push(l[Ee*3+0]),r.push(l[Ee*3+1]),r.push(l[Ee*3+2])}function Qe(Ee){a.push(Ee.x),a.push(Ee.y)}}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON(),t=this.parameters.shapes,i=this.parameters.options;return Kq(t,i,e)}static fromJSON(e,t){const i=[];for(let a=0,s=e.shapes.length;a0)&&m.push(E,b,w),(_!==i-1||l0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class t7 extends ei{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Ye(16777215),this.specular=new Ye(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ye(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Hl,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ai,this.combine=Jg,this.reflectivity=1,this.refractionRatio=.98,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.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,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.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.flatShading=e.flatShading,this.fog=e.fog,this}}class n7 extends ei{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Ye(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ye(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Hl,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,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.gradientMap=e.gradientMap,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.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class vR extends ei{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Hl,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),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.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class i7 extends ei{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Ye(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ye(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Hl,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ai,this.combine=Jg,this.reflectivity=1,this.refractionRatio=.98,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.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.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.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.flatShading=e.flatShading,this.fog=e.fog,this}}class _R extends ei{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=su,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 xR extends ei{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 r7 extends ei{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Ye(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Hl,this.normalScale=new re(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,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.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}}class a7 extends Yi{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function ph(n,e){return!n||n.constructor===e?n:typeof e.BYTES_PER_ELEMENT=="number"?new e(n):Array.prototype.slice.call(n)}function s7(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function o7(n){function e(r,a){return n[r]-n[a]}const t=n.length,i=new Array(t);for(let r=0;r!==t;++r)i[r]=r;return i.sort(e),i}function W3(n,e,t){const i=n.length,r=new n.constructor(i);for(let a=0,s=0;s!==i;++a){const o=t[a]*e;for(let l=0;l!==e;++l)r[s++]=n[o+l]}return r}function yR(n,e,t,i){let r=1,a=n[0];for(;a!==void 0&&a[i]===void 0;)a=n[r++];if(a===void 0)return;let s=a[i];if(s!==void 0)if(Array.isArray(s))do s=a[i],s!==void 0&&(e.push(a.time),t.push(...s)),a=n[r++];while(a!==void 0);else if(s.toArray!==void 0)do s=a[i],s!==void 0&&(e.push(a.time),s.toArray(t,t.length)),a=n[r++];while(a!==void 0);else do s=a[i],s!==void 0&&(e.push(a.time),t.push(s)),a=n[r++];while(a!==void 0)}function $q(n,e,t,i,r=30){const a=n.clone();a.name=e;const s=[];for(let l=0;l=i)){f.push(u.times[m]);for(let x=0;xa.tracks[l].times[0]&&(o=a.tracks[l].times[0]);for(let l=0;l=o.times[v]){const _=v*f+d,T=_+f-d;x=o.values.slice(_,T)}else{const _=o.createInterpolant(),T=d,E=f-d;_.evaluate(a),x=_.resultBuffer.slice(T,E)}l==="quaternion"&&new ft().fromArray(x).normalize().conjugate().toArray(x);const S=u.times.length;for(let _=0;_=a)){const o=t[1];e=a)break t}s=i,i=0;break n}break e}for(;i>>1;et;)--s;if(++s,a!==0||s!==r){a>=s&&(s=Math.max(s,1),a=s-1);const o=this.getValueSize();this.times=i.slice(a,s),this.values=this.values.slice(a*o,s*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(Ht("KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,r=this.values,a=i.length;a===0&&(Ht("KeyframeTrack: Track is empty.",this),e=!1);let s=null;for(let o=0;o!==a;o++){const l=i[o];if(typeof l=="number"&&isNaN(l)){Ht("KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(s!==null&&s>l){Ht("KeyframeTrack: Out of order keys.",this,o,l,s),e=!1;break}s=l}if(r!==void 0&&s7(r))for(let o=0,l=r.length;o!==l;++o){const u=r[o];if(isNaN(u)){Ht("KeyframeTrack: Value is not a valid number.",this,o,u),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),r=this.getInterpolation()===l1,a=e.length-1;let s=1;for(let o=1;o0){e[s]=e[a];for(let o=a*i,l=s*i,u=0;u!==i;++u)t[l+u]=t[o+u];++s}return s!==e.length?(this.times=e.slice(0,s),this.values=t.slice(0,s*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,r=new i(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}}Ns.prototype.ValueTypeName="";Ns.prototype.TimeBufferType=Float32Array;Ns.prototype.ValueBufferType=Float32Array;Ns.prototype.DefaultInterpolation=Tp;class nd extends Ns{constructor(e,t,i){super(e,t,i)}}nd.prototype.ValueTypeName="bool";nd.prototype.ValueBufferType=Array;nd.prototype.DefaultInterpolation=Sp;nd.prototype.InterpolantFactoryMethodLinear=void 0;nd.prototype.InterpolantFactoryMethodSmooth=void 0;class TR extends Ns{constructor(e,t,i,r){super(e,t,i,r)}}TR.prototype.ValueTypeName="color";class tu extends Ns{constructor(e,t,i,r){super(e,t,i,r)}}tu.prototype.ValueTypeName="number";class u7 extends Qp{constructor(e,t,i,r){super(e,t,i,r)}interpolate_(e,t,i,r){const a=this.resultBuffer,s=this.sampleValues,o=this.valueSize,l=(i-t)/(r-t);let u=e*o;for(let d=u+o;u!==d;u+=4)ft.slerpFlat(a,0,s,u-o,s,u,l);return a}}class nu extends Ns{constructor(e,t,i,r){super(e,t,i,r)}InterpolantFactoryMethodLinear(e){return new u7(this.times,this.values,this.getValueSize(),e)}}nu.prototype.ValueTypeName="quaternion";nu.prototype.InterpolantFactoryMethodSmooth=void 0;class id extends Ns{constructor(e,t,i){super(e,t,i)}}id.prototype.ValueTypeName="string";id.prototype.ValueBufferType=Array;id.prototype.DefaultInterpolation=Sp;id.prototype.InterpolantFactoryMethodLinear=void 0;id.prototype.InterpolantFactoryMethodSmooth=void 0;class Hh extends Ns{constructor(e,t,i,r){super(e,t,i,r)}}Hh.prototype.ValueTypeName="vector";class Vh{constructor(e="",t=-1,i=[],r=US){this.name=e,this.tracks=i,this.duration=t,this.blendMode=r,this.uuid=ja(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,r=1/(e.fps||1);for(let s=0,o=i.length;s!==o;++s)t.push(iY(i[s]).scale(r));const a=new this(e.name,e.duration,t,e.blendMode);return a.uuid=e.uuid,a.userData=JSON.parse(e.userData||"{}"),a}static toJSON(e){const t=[],i=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let a=0,s=i.length;a!==s;++a)t.push(Ns.toJSON(i[a]));return r}static CreateFromMorphTargetSequence(e,t,i,r){const a=t.length,s=[];for(let o=0;o1){const f=d[1];let p=r[f];p||(r[f]=p=[]),p.push(u)}}const s=[];for(const o in r)s.push(this.CreateFromMorphTargetSequence(o,r[o],t,i));return s}static parseAnimation(e,t){if(dt("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return Ht("AnimationClip: No animation in JSONLoader data."),null;const i=function(f,p,m,v,x){if(m.length!==0){const S=[],_=[];yR(m,S,_,v),S.length!==0&&x.push(new f(p,S,_))}},r=[],a=e.name||"default",s=e.fps||30,o=e.blendMode;let l=e.length||-1;const u=e.hierarchy||[];for(let f=0;f{t&&t(a),this.manager.itemEnd(e)},0),a;if(rl[e]!==void 0){rl[e].push({onLoad:t,onProgress:i,onError:r});return}rl[e]=[],rl[e].push({onLoad:t,onProgress:i,onError:r});const s=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(s).then(u=>{if(u.status===200||u.status===0){if(u.status===0&&dt("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||u.body===void 0||u.body.getReader===void 0)return u;const d=rl[e],f=u.body.getReader(),p=u.headers.get("X-File-Size")||u.headers.get("Content-Length"),m=p?parseInt(p):0,v=m!==0;let x=0;const S=new ReadableStream({start(_){T();function T(){f.read().then(({done:E,value:b})=>{if(E)_.close();else{x+=b.byteLength;const R=new ProgressEvent("progress",{lengthComputable:v,loaded:x,total:m});for(let w=0,L=d.length;w{_.error(E)})}}});return new Response(S)}else throw new rY(`fetch for "${u.url}" responded with ${u.status}: ${u.statusText}`,u)}).then(u=>{switch(l){case"arraybuffer":return u.arrayBuffer();case"blob":return u.blob();case"document":return u.text().then(d=>new DOMParser().parseFromString(d,o));case"json":return u.json();default:if(o==="")return u.text();{const f=/charset="?([^;"\s]*)"?/i.exec(o),p=f&&f[1]?f[1].toLowerCase():void 0,m=new TextDecoder(p);return u.arrayBuffer().then(v=>m.decode(v))}}}).then(u=>{Co.add(`file:${e}`,u);const d=rl[e];delete rl[e];for(let f=0,p=d.length;f{const d=rl[e];if(d===void 0)throw this.manager.itemError(e),u;delete rl[e];for(let f=0,p=d.length;f{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class aY extends wi{constructor(e){super(e)}load(e,t,i,r){const a=this,s=new jr(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){r?r(l):Ht(l),a.manager.itemError(e)}},i,r)}parse(e){const t=[];for(let i=0;i0:r.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const a in e.uniforms){const s=e.uniforms[a];switch(r.uniforms[a]={},s.type){case"t":r.uniforms[a].value=i(s.value);break;case"c":r.uniforms[a].value=new Ye().setHex(s.value);break;case"v2":r.uniforms[a].value=new re().fromArray(s.value);break;case"v3":r.uniforms[a].value=new D().fromArray(s.value);break;case"v4":r.uniforms[a].value=new Pt().fromArray(s.value);break;case"m3":r.uniforms[a].value=new Mt().fromArray(s.value);break;case"m4":r.uniforms[a].value=new Me().fromArray(s.value);break;default:r.uniforms[a].value=s.value}}if(e.defines!==void 0&&(r.defines=e.defines),e.vertexShader!==void 0&&(r.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(r.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(r.glslVersion=e.glslVersion),e.extensions!==void 0)for(const a in e.extensions)r.extensions[a]=e.extensions[a];if(e.lights!==void 0&&(r.lights=e.lights),e.clipping!==void 0&&(r.clipping=e.clipping),e.size!==void 0&&(r.size=e.size),e.sizeAttenuation!==void 0&&(r.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(r.map=i(e.map)),e.matcap!==void 0&&(r.matcap=i(e.matcap)),e.alphaMap!==void 0&&(r.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(r.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(r.bumpScale=e.bumpScale),e.normalMap!==void 0&&(r.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(r.normalMapType=e.normalMapType),e.normalScale!==void 0){let a=e.normalScale;Array.isArray(a)===!1&&(a=[a,a]),r.normalScale=new re().fromArray(a)}return e.displacementMap!==void 0&&(r.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(r.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(r.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(r.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(r.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(r.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(r.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(r.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(r.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(r.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(r.envMap=i(e.envMap)),e.envMapRotation!==void 0&&r.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(r.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(r.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(r.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(r.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(r.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(r.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(r.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(r.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(r.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(r.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(r.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(r.clearcoatNormalScale=new re().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(r.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(r.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(r.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(r.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(r.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(r.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(r.sheenRoughnessMap=i(e.sheenRoughnessMap)),r}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return aT.createMaterialFromType(e)}static createMaterialFromType(e){const t={ShadowMaterial:e7,SpriteMaterial:lR,RawShaderMaterial:td,ShaderMaterial:Oi,PointsMaterial:nv,MeshPhysicalMaterial:Ds,MeshStandardMaterial:lv,MeshPhongMaterial:t7,MeshToonMaterial:n7,MeshNormalMaterial:vR,MeshLambertMaterial:i7,MeshDepthMaterial:_R,MeshDistanceMaterial:xR,MeshBasicMaterial:Sr,MeshMatcapMaterial:r7,LineDashedMaterial:a7,LineBasicMaterial:Yi,Material:ei};return new t[e]}}class qc{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class v7 extends Ct{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class _7 extends wi{constructor(e){super(e)}load(e,t,i,r){const a=this,s=new jr(a.manager);s.setPath(a.path),s.setRequestHeader(a.requestHeader),s.setWithCredentials(a.withCredentials),s.load(e,function(o){try{t(a.parse(JSON.parse(o)))}catch(l){r?r(l):Ht(l),a.manager.itemError(e)}},i,r)}parse(e){const t={},i={};function r(m,v){if(t[v]!==void 0)return t[v];const S=m.interleavedBuffers[v],_=a(m,S.buffer),T=Vf(S.type,_),E=new Zp(T,S.stride);return E.uuid=S.uuid,t[v]=E,E}function a(m,v){if(i[v]!==void 0)return i[v];const S=m.arrayBuffers[v],_=new Uint32Array(S).buffer;return i[v]=_,_}const s=e.isInstancedBufferGeometry?new v7:new Ct,o=e.data.index;if(o!==void 0){const m=Vf(o.type,o.array);s.setIndex(new bt(m,1))}const l=e.data.attributes;for(const m in l){const v=l[m];let x;if(v.isInterleavedBufferAttribute){const S=r(e.data,v.data);x=new zl(S,v.itemSize,v.offset,v.normalized)}else{const S=Vf(v.type,v.array),_=v.isInstancedBufferAttribute?Bh:bt;x=new _(S,v.itemSize,v.normalized)}v.name!==void 0&&(x.name=v.name),v.usage!==void 0&&x.setUsage(v.usage),s.setAttribute(m,x)}const u=e.data.morphAttributes;if(u)for(const m in u){const v=u[m],x=[];for(let S=0,_=v.length;S<_;S++){const T=v[S];let E;if(T.isInterleavedBufferAttribute){const b=r(e.data,T.data);E=new zl(b,T.itemSize,T.offset,T.normalized)}else{const b=Vf(T.type,T.array);E=new bt(b,T.itemSize,T.normalized)}T.name!==void 0&&(E.name=T.name),x.push(E)}s.morphAttributes[m]=x}e.data.morphTargetsRelative&&(s.morphTargetsRelative=!0);const f=e.data.groups||e.data.drawcalls||e.data.offsets;if(f!==void 0)for(let m=0,v=f.length;m!==v;++m){const x=f[m];s.addGroup(x.start,x.count,x.materialIndex)}const p=e.data.boundingSphere;return p!==void 0&&(s.boundingSphere=new qi().fromJSON(p)),e.name&&(s.name=e.name),e.userData&&(s.userData=e.userData),s}}class hY extends wi{constructor(e){super(e)}load(e,t,i,r){const a=this,s=this.path===""?qc.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||s;const o=new jr(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){let u=null;try{u=JSON.parse(l)}catch(f){r!==void 0&&r(f),f("ObjectLoader: Can't parse "+e+".",f.message);return}const d=u.metadata;if(d===void 0||d.type===void 0||d.type.toLowerCase()==="geometry"){r!==void 0&&r(new Error("THREE.ObjectLoader: Can't load "+e)),Ht("ObjectLoader: Can't load "+e);return}a.parse(u,t)},i,r)}async loadAsync(e,t){const i=this,r=this.path===""?qc.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||r;const a=new jr(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials);const s=await a.loadAsync(e,t),o=JSON.parse(s),l=o.metadata;if(l===void 0||l.type===void 0||l.type.toLowerCase()==="geometry")throw new Error("THREE.ObjectLoader: Can't load "+e);return await i.parseAsync(o)}parse(e,t){const i=this.parseAnimations(e.animations),r=this.parseShapes(e.shapes),a=this.parseGeometries(e.geometries,r),s=this.parseImages(e.images,function(){t!==void 0&&t(u)}),o=this.parseTextures(e.textures,s),l=this.parseMaterials(e.materials,o),u=this.parseObject(e.object,a,l,o,i),d=this.parseSkeletons(e.skeletons,u);if(this.bindSkeletons(u,d),this.bindLightTargets(u),t!==void 0){let f=!1;for(const p in s)if(s[p].data instanceof HTMLImageElement){f=!0;break}f===!1&&t(u)}return u}async parseAsync(e){const t=this.parseAnimations(e.animations),i=this.parseShapes(e.shapes),r=this.parseGeometries(e.geometries,i),a=await this.parseImagesAsync(e.images),s=this.parseTextures(e.textures,a),o=this.parseMaterials(e.materials,s),l=this.parseObject(e.object,r,o,s,t),u=this.parseSkeletons(e.skeletons,l);return this.bindSkeletons(l,u),this.bindLightTargets(l),l}parseShapes(e){const t={};if(e!==void 0)for(let i=0,r=e.length;i0){const l=new rT(t);a=new Dp(l),a.setCrossOrigin(this.crossOrigin);for(let u=0,d=e.length;u0){r=new Dp(this.manager),r.setCrossOrigin(this.crossOrigin);for(let s=0,o=e.length;s{let S=null,_=null;return x.boundingBox!==void 0&&(S=new Qi().fromJSON(x.boundingBox)),x.boundingSphere!==void 0&&(_=new qi().fromJSON(x.boundingSphere)),{...x,boundingBox:S,boundingSphere:_}}),s._instanceInfo=e.instanceInfo,s._availableInstanceIds=e._availableInstanceIds,s._availableGeometryIds=e._availableGeometryIds,s._nextIndexStart=e.nextIndexStart,s._nextVertexStart=e.nextVertexStart,s._geometryCount=e.geometryCount,s._maxInstanceCount=e.maxInstanceCount,s._maxVertexCount=e.maxVertexCount,s._maxIndexCount=e.maxIndexCount,s._geometryInitialized=e.geometryInitialized,s._matricesTexture=u(e.matricesTexture.uuid),s._indirectTexture=u(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(s._colorsTexture=u(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(s.boundingSphere=new qi().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(s.boundingBox=new Qi().fromJSON(e.boundingBox));break;case"LOD":s=new H9;break;case"Line":s=new Oo(o(e.geometry),l(e.material));break;case"LineLoop":s=new cR(o(e.geometry),l(e.material));break;case"LineSegments":s=new va(o(e.geometry),l(e.material));break;case"PointCloud":case"Points":s=new kS(o(e.geometry),l(e.material));break;case"Sprite":s=new F9(l(e.material));break;case"Group":s=new Xi;break;case"Bone":s=new HS;break;default:s=new Xt}if(s.uuid=e.uuid,e.name!==void 0&&(s.name=e.name),e.matrix!==void 0?(s.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(s.matrixAutoUpdate=e.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(e.position!==void 0&&s.position.fromArray(e.position),e.rotation!==void 0&&s.rotation.fromArray(e.rotation),e.quaternion!==void 0&&s.quaternion.fromArray(e.quaternion),e.scale!==void 0&&s.scale.fromArray(e.scale)),e.up!==void 0&&s.up.fromArray(e.up),e.castShadow!==void 0&&(s.castShadow=e.castShadow),e.receiveShadow!==void 0&&(s.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(s.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(s.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(s.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(s.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&s.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(s.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(s.visible=e.visible),e.frustumCulled!==void 0&&(s.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(s.renderOrder=e.renderOrder),e.userData!==void 0&&(s.userData=e.userData),e.layers!==void 0&&(s.layers.mask=e.layers),e.children!==void 0){const p=e.children;for(let m=0;m"u"&&dt("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&dt("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,i,r){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const a=this,s=Co.get(`image-bitmap:${e}`);if(s!==void 0){if(a.manager.itemStart(e),s.then){s.then(u=>{if(db.has(s)===!0)r&&r(db.get(s)),a.manager.itemError(e),a.manager.itemEnd(e);else return t&&t(u),a.manager.itemEnd(e),u});return}return setTimeout(function(){t&&t(s),a.manager.itemEnd(e)},0),s}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const l=fetch(e,o).then(function(u){return u.blob()}).then(function(u){return createImageBitmap(u,Object.assign(a.options,{colorSpaceConversion:"none"}))}).then(function(u){return Co.add(`image-bitmap:${e}`,u),t&&t(u),a.manager.itemEnd(e),u}).catch(function(u){r&&r(u),db.set(l,u),Co.remove(`image-bitmap:${e}`),a.manager.itemError(e),a.manager.itemEnd(e)});Co.add(`image-bitmap:${e}`,l),a.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let J_;class RR{static getContext(){return J_===void 0&&(J_=new(window.AudioContext||window.webkitAudioContext)),J_}static setContext(e){J_=e}}class fY extends wi{constructor(e){super(e)}load(e,t,i,r){const a=this,s=new jr(this.manager);s.setResponseType("arraybuffer"),s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(l){try{const u=l.slice(0);RR.getContext().decodeAudioData(u,function(f){t(f)}).catch(o)}catch(u){o(u)}},i,r);function o(l){r?r(l):Ht(l),a.manager.itemError(e)}}}const WO=new Me,XO=new Me,zu=new Me;class pY{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new si,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new si,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,zu.copy(e.projectionMatrix);const r=t.eyeSep/2,a=r*t.near/t.focus,s=t.near*Math.tan(bh*t.fov*.5)/t.zoom;let o,l;XO.elements[12]=-r,WO.elements[12]=r,o=-s*t.aspect+a,l=s*t.aspect+a,zu.elements[0]=2*t.near/(l-o),zu.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(zu),o=-s*t.aspect-a,l=s*t.aspect-a,zu.elements[0]=2*t.near/(l-o),zu.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(zu)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(XO),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(WO)}}class y7 extends si{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class cv{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}const Bu=new D,fb=new ft,mY=new D,Fu=new D,Hu=new D;class gY extends Xt{constructor(){super(),this.type="AudioListener",this.context=RR.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new cv}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Bu,fb,mY),Fu.set(0,0,-1).applyQuaternion(fb),Hu.set(0,1,0).applyQuaternion(fb),t.positionX){const i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Bu.x,i),t.positionY.linearRampToValueAtTime(Bu.y,i),t.positionZ.linearRampToValueAtTime(Bu.z,i),t.forwardX.linearRampToValueAtTime(Fu.x,i),t.forwardY.linearRampToValueAtTime(Fu.y,i),t.forwardZ.linearRampToValueAtTime(Fu.z,i),t.upX.linearRampToValueAtTime(Hu.x,i),t.upY.linearRampToValueAtTime(Hu.y,i),t.upZ.linearRampToValueAtTime(Hu.z,i)}else t.setPosition(Bu.x,Bu.y,Bu.z),t.setOrientation(Fu.x,Fu.y,Fu.z,Hu.x,Hu.y,Hu.z)}}class S7 extends Xt{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){dt("Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){dt("Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){dt("Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){dt("Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(i,r,this._addIndex*t,1,t);for(let l=t,u=t+t;l!==u;++l)if(i[l]!==i[l+t]){o.setValue(i,r);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,r=i*this._origIndex;e.getValue(t,r);for(let a=i,s=r;a!==s;++a)t[a]=t[r+a%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let s=0;s!==a;++s)e[t+s]=e[i+s]}_slerp(e,t,i,r){ft.slerpFlat(e,t,e,t,e,i,r)}_slerpAdditive(e,t,i,r,a){const s=this._workIndex*a;ft.multiplyQuaternionsFlat(e,s,e,t,e,i),ft.slerpFlat(e,t,e,t,e,s,r)}_lerp(e,t,i,r,a){const s=1-r;for(let o=0;o!==a;++o){const l=t+o;e[l]=e[l]*s+e[i+o]*r}}_lerpAdditive(e,t,i,r,a){for(let s=0;s!==a;++s){const o=t+s;e[o]=e[o]+e[i+s]*r}}}const CR="\\[\\]\\.:\\/",yY=new RegExp("["+CR+"]","g"),DR="[^"+CR+"]",SY="[^"+CR.replace("\\.","")+"]",TY=/((?:WC+[\/:])*)/.source.replace("WC",DR),EY=/(WCOD+)?/.source.replace("WCOD",SY),bY=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",DR),MY=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",DR),AY=new RegExp("^"+TY+EY+bY+MY+"$"),wY=["material","materials","bones","map"];class RY{constructor(e,t,i){const r=i||fn.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,r=this._bindings[i];r!==void 0&&r.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let r=this._targetGroup.nCachedObjects_,a=i.length;r!==a;++r)i[r].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class fn{constructor(e,t,i){this.path=t,this.parsedPath=i||fn.parseTrackName(t),this.node=fn.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new fn.Composite(e,t,i):new fn(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(yY,"")}static parseTrackName(e){const t=AY.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=i.nodeName&&i.nodeName.lastIndexOf(".");if(r!==void 0&&r!==-1){const a=i.nodeName.substring(r+1);wY.indexOf(a)!==-1&&(i.nodeName=i.nodeName.substring(0,r),i.objectName=a)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(a){for(let s=0;s=a){const f=a++,p=e[f];t[p.uuid]=d,e[d]=p,t[u]=f,e[f]=l;for(let m=0,v=r;m!==v;++m){const x=i[m],S=x[f],_=x[d];x[d]=S,x[f]=_}}}this.nCachedObjects_=a}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,r=i.length;let a=this.nCachedObjects_,s=e.length;for(let o=0,l=arguments.length;o!==l;++o){const u=arguments[o],d=u.uuid,f=t[d];if(f!==void 0)if(delete t[d],f0&&(t[m.uuid]=f),e[f]=m,e.pop();for(let v=0,x=r;v!==x;++v){const S=i[v];S[f]=S[p],S.pop()}}}this.nCachedObjects_=a}subscribe_(e,t){const i=this._bindingsIndicesByPath;let r=i[e];const a=this._bindings;if(r!==void 0)return a[r];const s=this._paths,o=this._parsedPaths,l=this._objects,u=l.length,d=this.nCachedObjects_,f=new Array(u);r=a.length,i[e]=r,s.push(e),o.push(t),a.push(f);for(let p=d,m=l.length;p!==m;++p){const v=l[p];f[p]=new fn(v,e,t)}return f}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const r=this._paths,a=this._parsedPaths,s=this._bindings,o=s.length-1,l=s[o],u=e[o];t[u]=i,s[i]=l,s.pop(),a[i]=a[o],a.pop(),r[i]=r[o],r.pop()}}}class E7{constructor(e,t,i=null,r=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=r;const a=t.tracks,s=a.length,o=new Array(s),l={endingStart:dh,endingEnd:dh};for(let u=0;u!==s;++u){const d=a[u].createInterpolant(null);o[u]=d,d.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=g9,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i=!1){if(e.fadeOut(t),this.fadeIn(t),i===!0){const r=this._clip.duration,a=e._clip.duration,s=a/r,o=r/a;e.warp(1,s,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i=!1){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const r=this._mixer,a=r.time,s=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=r._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,u=o.sampleValues;return l[0]=a,l[1]=a+i,u[0]=e/s,u[1]=t/s,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,r){if(!this.enabled){this._updateWeight(e);return}const a=this._startTime;if(a!==null){const l=(e-a)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);const s=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,u=this._propertyBindings;switch(this.blendMode){case eR:for(let d=0,f=l.length;d!==f;++d)l[d].evaluate(s),u[d].accumulateAdditive(o);break;case US:default:for(let d=0,f=l.length;d!==f;++d)l[d].evaluate(s),u[d].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const r=i.evaluate(e)[0];t*=r,e>i.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const r=i.evaluate(e)[0];t*=r,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let r=this.time+e,a=this._loopCount;const s=i===v9;if(e===0)return a===-1?r:s&&(a&1)===1?t-r:r;if(i===$w){a===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(a===-1&&(e>=0?(a=0,this._setEndings(!0,this.repetitions===0,s)):this._setEndings(this.repetitions===0,!0,s)),r>=t||r<0){const o=Math.floor(r/t);r-=t*o,a+=Math.abs(o);const l=this.repetitions-a;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const u=e<0;this._setEndings(u,!u,s)}else this._setEndings(!1,!1,s);this._loopCount=a,this.time=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=r;if(s&&(a&1)===1)return t-r}return r}_setEndings(e,t,i){const r=this._interpolantSettings;i?(r.endingStart=fh,r.endingEnd=fh):(e?r.endingStart=this.zeroSlopeAtStart?fh:dh:r.endingStart=Ag,t?r.endingEnd=this.zeroSlopeAtEnd?fh:dh:r.endingEnd=Ag)}_scheduleFading(e,t,i){const r=this._mixer,a=r.time;let s=this._weightInterpolant;s===null&&(s=r._lendControlInterpolant(),this._weightInterpolant=s);const o=s.parameterPositions,l=s.sampleValues;return o[0]=a,l[0]=t,o[1]=a+e,l[1]=i,this}}const DY=new Float32Array(1);class b7 extends Mi{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const i=e._localRoot||this._root,r=e._clip.tracks,a=r.length,s=e._propertyBindings,o=e._interpolants,l=i.uuid,u=this._bindingsByRootAndName;let d=u[l];d===void 0&&(d={},u[l]=d);for(let f=0;f!==a;++f){const p=r[f],m=p.name;let v=d[m];if(v!==void 0)++v.referenceCount,s[f]=v;else{if(v=s[f],v!==void 0){v._cacheIndex===null&&(++v.referenceCount,this._addInactiveBinding(v,l,m));continue}const x=t&&t._propertyBindings[f].binding.parsedPath;v=new T7(fn.create(i,m,x),p.ValueTypeName,p.getValueSize()),++v.referenceCount,this._addInactiveBinding(v,l,m),s[f]=v}o[f].resultBuffer=v.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,r=e._clip.uuid,a=this._actionsByClip[r];this._bindAction(e,a&&a.knownActions[0]),this._addInactiveAction(e,r,i)}const t=e._propertyBindings;for(let i=0,r=t.length;i!==r;++i){const a=t[i];a.useCount++===0&&(this._lendBinding(a),a.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,r=t.length;i!==r;++i){const a=t[i];--a.useCount===0&&(a.restoreOriginalState(),this._takeBackBinding(a))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,r=this.time+=e,a=Math.sign(e),s=this._accuIndex^=1;for(let u=0;u!==i;++u)t[u]._update(r,e,a,s);const o=this._bindings,l=this._nActiveBindings;for(let u=0;u!==l;++u)o[u].apply(s);return this}setTime(e){this.time=0;for(let t=0;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}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}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}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}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ZO).distanceTo(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}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const QO=new D,$_=new D,ef=new D,tf=new D,pb=new D,BY=new D,FY=new D;class NR{constructor(e=new D,t=new D){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){QO.subVectors(e,this.start),$_.subVectors(this.end,this.start);const i=$_.dot($_);let a=$_.dot(QO)/i;return t&&(a=It(a,0,1)),a}closestPointToPoint(e,t,i){const r=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(r).add(this.start)}distanceSqToLine3(e,t=BY,i=FY){const r=10000000000000001e-32;let a,s;const o=this.start,l=e.start,u=this.end,d=e.end;ef.subVectors(u,o),tf.subVectors(d,l),pb.subVectors(o,l);const f=ef.dot(ef),p=tf.dot(tf),m=tf.dot(pb);if(f<=r&&p<=r)return t.copy(o),i.copy(l),t.sub(i),t.dot(t);if(f<=r)a=0,s=m/p,s=It(s,0,1);else{const v=ef.dot(pb);if(p<=r)s=0,a=It(-v/f,0,1);else{const x=ef.dot(tf),S=f*p-x*x;S!==0?a=It((x*m-v*p)/S,0,1):a=0,s=(x*a+m)/p,s<0?(s=0,a=It(-v/f,0,1)):s>1&&(s=1,a=It((x-v)/f,0,1))}}return t.copy(o).add(ef.multiplyScalar(a)),i.copy(l).add(tf.multiplyScalar(s)),t.sub(i),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const KO=new D;class HY extends Xt{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new Ct,r=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let s=0,o=1,l=32;s1)for(let f=0;f.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{nL.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(nL,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class w7 extends va{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new Ct;r.setAttribute("position",new St(t,3)),r.setAttribute("color",new St(i,3));const a=new Yi({vertexColors:!0,toneMapped:!1});super(r,a),this.type="AxesHelper"}setColors(e,t,i){const r=new Ye,a=this.geometry.attributes.color.array;return r.set(e),r.toArray(a,0),r.toArray(a,3),r.set(t),r.toArray(a,6),r.toArray(a,9),r.set(i),r.toArray(a,12),r.toArray(a,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class $Y{constructor(){this.type="ShapePath",this.color=new Ye,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Ly,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,r){return this.currentPath.quadraticCurveTo(e,t,i,r),this}bezierCurveTo(e,t,i,r,a,s){return this.currentPath.bezierCurveTo(e,t,i,r,a,s),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(_){const T=[];for(let E=0,b=_.length;ENumber.EPSILON){if(C<0&&(L=T[w],N=-N,U=T[R],C=-C),_.yU.y)continue;if(_.y===L.y){if(_.x===L.x)return!0}else{const z=C*(_.x-L.x)-N*(_.y-L.y);if(z===0)return!0;if(z<0)continue;b=!b}}else{if(_.y!==L.y)continue;if(U.x<=_.x&&_.x<=L.x||L.x<=_.x&&_.x<=U.x)return!0}}return b}const r=Ks.isClockWise,a=this.subPaths;if(a.length===0)return[];let s,o,l;const u=[];if(a.length===1)return o=a[0],l=new Mh,l.curves=o.curves,u.push(l),u;let d=!r(a[0].getPoints());d=e?!d:d;const f=[],p=[];let m=[],v=0,x;p[v]=void 0,m[v]=[];for(let _=0,T=a.length;_1){let _=!1,T=0;for(let E=0,b=p.length;E0&&_===!1&&(m=f)}let S;for(let _=0,T=p.length;_e?(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2):(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0),n}function nj(n,e){const t=n.image&&n.image.width?n.image.width/n.image.height:1;return t>e?(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0):(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2),n}function ij(n){return n.repeat.x=1,n.repeat.y=1,n.offset.x=0,n.offset.y=0,n}function Y3(n,e,t,i){const r=rj(i);switch(t){case Kw:return n*e;case Qs:return n*e/r.components*r.byteLength;case ev:return n*e/r.components*r.byteLength;case Mo:return n*e*2/r.components*r.byteLength;case LS:return n*e*2/r.components*r.byteLength;case Jw:return n*e*3/r.components*r.byteLength;case ai:return n*e*4/r.components*r.byteLength;case IS:return n*e*4/r.components*r.byteLength;case Q0:case K0:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case J0:case $0:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case ny:case ry:return Math.max(n,16)*Math.max(e,8)/4;case ty:case iy:return Math.max(n,8)*Math.max(e,8)/2;case ay:case sy:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case oy:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case ly:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case cy:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case uy:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case hy:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case dy:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case fy:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case py:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case my:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case gy:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case vy:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case _y:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case xy:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case yy:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case Sy:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case Ty:case Ey:case by:return Math.ceil(n/4)*Math.ceil(e/4)*16;case My:case Ay:return Math.ceil(n/4)*Math.ceil(e/4)*8;case wy:case Ry:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function rj(n){switch(n){case Ni:case CS:return{byteLength:1,components:1};case Uh:case DS:case Jn:return{byteLength:2,components:1};case NS:case OS:return{byteLength:2,components:4};case to:case $g:case fi:return{byteLength:4,components:1};case Zw:case Qw:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${n}.`)}class R7{static contain(e,t){return tj(e,t)}static cover(e,t){return nj(e,t)}static fill(e){return ij(e)}static getByteLength(e,t,i,r){return Y3(e,t,i,r)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:$s}}));typeof window<"u"&&(window.__THREE__?dt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=$s);/** + * @license + * Copyright 2010-2025 Three.js Authors + * SPDX-License-Identifier: MIT + */function C7(){let n=null,e=!1,t=null,i=null;function r(a,s){t(a,s),i=n.requestAnimationFrame(r)}return{start:function(){e!==!0&&t!==null&&(i=n.requestAnimationFrame(r),e=!0)},stop:function(){n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(a){t=a},setContext:function(a){n=a}}}function aj(n){const e=new WeakMap;function t(o,l){const u=o.array,d=o.usage,f=u.byteLength,p=n.createBuffer();n.bindBuffer(l,p),n.bufferData(l,u,d),o.onUploadCallback();let m;if(u instanceof Float32Array)m=n.FLOAT;else if(typeof Float16Array<"u"&&u instanceof Float16Array)m=n.HALF_FLOAT;else if(u instanceof Uint16Array)o.isFloat16BufferAttribute?m=n.HALF_FLOAT:m=n.UNSIGNED_SHORT;else if(u instanceof Int16Array)m=n.SHORT;else if(u instanceof Uint32Array)m=n.UNSIGNED_INT;else if(u instanceof Int32Array)m=n.INT;else if(u instanceof Int8Array)m=n.BYTE;else if(u instanceof Uint8Array)m=n.UNSIGNED_BYTE;else if(u instanceof Uint8ClampedArray)m=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+u);return{buffer:p,type:m,bytesPerElement:u.BYTES_PER_ELEMENT,version:o.version,size:f}}function i(o,l,u){const d=l.array,f=l.updateRanges;if(n.bindBuffer(u,o),f.length===0)n.bufferSubData(u,0,d);else{f.sort((m,v)=>m.start-v.start);let p=0;for(let m=1;m 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`,Tj=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,Ej=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,bj=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,Mj=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,Aj=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,wj=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`,Rj=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`,Cj=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,Dj=`#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`,Nj=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,Oj=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,Lj=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,Ij=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,Uj=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,Pj="gl_FragColor = linearToOutputTexel( gl_FragColor );",zj=`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 ); +}`,Bj=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,Fj=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif +#endif`,Hj=`#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`,Vj=`#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`,Gj=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,kj=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,Wj=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,Xj=`#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`,qj=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,Yj=`#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 +}`,jj=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,Zj=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,Qj=`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`,Kj=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,Jj=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,$j=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,eZ=`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`,tZ=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,nZ=`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`,iZ=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,rZ=`uniform sampler2D dfgLUT; +struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 uv = vec2( roughness, dotNV ); + return texture2D( dfgLUT, uv ).rg; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 dfgV = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNV * dotNV), 0.0, dotNV), material.roughness ); + vec2 dfgL = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNL * dotNL), 0.0, dotNL), material.roughness ); + vec3 FssEss_V = material.specularColor * dfgV.x + material.specularF90 * dfgV.y; + vec3 FssEss_L = material.specularColor * dfgL.x + material.specularF90 * dfgL.y; + float Ess_V = dfgV.x + dfgV.y; + float Ess_L = dfgL.x + dfgL.y; + float Ems_V = 1.0 - Ess_V; + float Ems_L = 1.0 - Ess_L; + vec3 Favg = material.specularColor + ( 1.0 - material.specularColor ) * 0.047619; + vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg * Favg + EPSILON ); + float compensationFactor = Ems_V * Ems_L; + vec3 multiScatter = Fms * compensationFactor; + return singleScatter + multiScatter; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,aZ=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,sZ=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,oZ=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,lZ=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,cZ=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,uZ=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + varying float vFragDepth; + varying float vIsPerspective; +#endif`,hZ=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,dZ=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,fZ=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,pZ=`#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`,mZ=`#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`,gZ=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,vZ=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,_Z=`#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`,xZ=`#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`,yZ=`#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`,SZ=`#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`,TZ=`#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`,EZ=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,bZ=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,MZ=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,AZ=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,wZ=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,RZ=`#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`,CZ=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,DZ=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,NZ=`#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`,OZ=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,LZ=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,IZ=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`,UZ=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,PZ=`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;`,zZ=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,BZ=`#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`,FZ=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,HZ=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,VZ=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + float depth = unpackRGBAToDepth( texture2D( depths, uv ) ); + #ifdef USE_REVERSED_DEPTH_BUFFER + return step( depth, compare ); + #else + return step( compare, depth ); + #endif + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow( sampler2D shadow, vec2 uv, float compare ) { + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + #ifdef USE_REVERSED_DEPTH_BUFFER + float hard_shadow = step( distribution.x, compare ); + #else + float hard_shadow = step( compare, distribution.x ); + #endif + if ( hard_shadow != 1.0 ) { + float distance = compare - distribution.x; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`,GZ=`#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`,kZ=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,WZ=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,XZ=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,qZ=`#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`,YZ=`#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`,jZ=`#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`,ZZ=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,QZ=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,KZ=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,JZ=`#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; }`,$Z=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,eQ=`#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`,tQ=`#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`,nQ=`#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`,iQ=`#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`,rQ=`#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 aQ=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,sQ=`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 +}`,oQ=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,lQ=`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,cQ=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,uQ=`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 +}`,hQ=`#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; +}`,dQ=`#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 +}`,fQ=`#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; +}`,pQ=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,mQ=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,gQ=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,vQ=`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 +}`,_Q=`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 +}`,xQ=`#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 +}`,yQ=`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 +}`,SQ=`#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 +}`,TQ=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,EQ=`#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; +}`,bQ=`#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 +}`,MQ=`#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 +}`,AQ=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,wQ=`#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 +}`,RQ=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,CQ=`#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 +}`,DQ=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,NQ=`#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 +}`,OQ=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,LQ=`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 +}`,IQ=`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 +}`,UQ=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,PQ=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,zQ=`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 +}`,BQ=`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 +}`,Jt={alphahash_fragment:sj,alphahash_pars_fragment:oj,alphamap_fragment:lj,alphamap_pars_fragment:cj,alphatest_fragment:uj,alphatest_pars_fragment:hj,aomap_fragment:dj,aomap_pars_fragment:fj,batching_pars_vertex:pj,batching_vertex:mj,begin_vertex:gj,beginnormal_vertex:vj,bsdfs:_j,iridescence_fragment:xj,bumpmap_pars_fragment:yj,clipping_planes_fragment:Sj,clipping_planes_pars_fragment:Tj,clipping_planes_pars_vertex:Ej,clipping_planes_vertex:bj,color_fragment:Mj,color_pars_fragment:Aj,color_pars_vertex:wj,color_vertex:Rj,common:Cj,cube_uv_reflection_fragment:Dj,defaultnormal_vertex:Nj,displacementmap_pars_vertex:Oj,displacementmap_vertex:Lj,emissivemap_fragment:Ij,emissivemap_pars_fragment:Uj,colorspace_fragment:Pj,colorspace_pars_fragment:zj,envmap_fragment:Bj,envmap_common_pars_fragment:Fj,envmap_pars_fragment:Hj,envmap_pars_vertex:Vj,envmap_physical_pars_fragment:Jj,envmap_vertex:Gj,fog_vertex:kj,fog_pars_vertex:Wj,fog_fragment:Xj,fog_pars_fragment:qj,gradientmap_pars_fragment:Yj,lightmap_pars_fragment:jj,lights_lambert_fragment:Zj,lights_lambert_pars_fragment:Qj,lights_pars_begin:Kj,lights_toon_fragment:$j,lights_toon_pars_fragment:eZ,lights_phong_fragment:tZ,lights_phong_pars_fragment:nZ,lights_physical_fragment:iZ,lights_physical_pars_fragment:rZ,lights_fragment_begin:aZ,lights_fragment_maps:sZ,lights_fragment_end:oZ,logdepthbuf_fragment:lZ,logdepthbuf_pars_fragment:cZ,logdepthbuf_pars_vertex:uZ,logdepthbuf_vertex:hZ,map_fragment:dZ,map_pars_fragment:fZ,map_particle_fragment:pZ,map_particle_pars_fragment:mZ,metalnessmap_fragment:gZ,metalnessmap_pars_fragment:vZ,morphinstance_vertex:_Z,morphcolor_vertex:xZ,morphnormal_vertex:yZ,morphtarget_pars_vertex:SZ,morphtarget_vertex:TZ,normal_fragment_begin:EZ,normal_fragment_maps:bZ,normal_pars_fragment:MZ,normal_pars_vertex:AZ,normal_vertex:wZ,normalmap_pars_fragment:RZ,clearcoat_normal_fragment_begin:CZ,clearcoat_normal_fragment_maps:DZ,clearcoat_pars_fragment:NZ,iridescence_pars_fragment:OZ,opaque_fragment:LZ,packing:IZ,premultiplied_alpha_fragment:UZ,project_vertex:PZ,dithering_fragment:zZ,dithering_pars_fragment:BZ,roughnessmap_fragment:FZ,roughnessmap_pars_fragment:HZ,shadowmap_pars_fragment:VZ,shadowmap_pars_vertex:GZ,shadowmap_vertex:kZ,shadowmask_pars_fragment:WZ,skinbase_vertex:XZ,skinning_pars_vertex:qZ,skinning_vertex:YZ,skinnormal_vertex:jZ,specularmap_fragment:ZZ,specularmap_pars_fragment:QZ,tonemapping_fragment:KZ,tonemapping_pars_fragment:JZ,transmission_fragment:$Z,transmission_pars_fragment:eQ,uv_pars_fragment:tQ,uv_pars_vertex:nQ,uv_vertex:iQ,worldpos_vertex:rQ,background_vert:aQ,background_frag:sQ,backgroundCube_vert:oQ,backgroundCube_frag:lQ,cube_vert:cQ,cube_frag:uQ,depth_vert:hQ,depth_frag:dQ,distanceRGBA_vert:fQ,distanceRGBA_frag:pQ,equirect_vert:mQ,equirect_frag:gQ,linedashed_vert:vQ,linedashed_frag:_Q,meshbasic_vert:xQ,meshbasic_frag:yQ,meshlambert_vert:SQ,meshlambert_frag:TQ,meshmatcap_vert:EQ,meshmatcap_frag:bQ,meshnormal_vert:MQ,meshnormal_frag:AQ,meshphong_vert:wQ,meshphong_frag:RQ,meshphysical_vert:CQ,meshphysical_frag:DQ,meshtoon_vert:NQ,meshtoon_frag:OQ,points_vert:LQ,points_frag:IQ,shadow_vert:UQ,shadow_frag:PQ,sprite_vert:zQ,sprite_frag:BQ},rt={common:{diffuse:{value:new Ye(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Mt},alphaMap:{value:null},alphaMapTransform:{value:new Mt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Mt}},envmap:{envMap:{value:null},envMapRotation:{value:new Mt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Mt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Mt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Mt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Mt},normalScale:{value:new re(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Mt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Mt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Mt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Mt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ye(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Ye(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Mt},alphaTest:{value:0},uvTransform:{value:new Mt}},sprite:{diffuse:{value:new Ye(16777215)},opacity:{value:1},center:{value:new re(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Mt},alphaMap:{value:null},alphaMapTransform:{value:new Mt},alphaTest:{value:0}}},Zs={basic:{uniforms:Vr([rt.common,rt.specularmap,rt.envmap,rt.aomap,rt.lightmap,rt.fog]),vertexShader:Jt.meshbasic_vert,fragmentShader:Jt.meshbasic_frag},lambert:{uniforms:Vr([rt.common,rt.specularmap,rt.envmap,rt.aomap,rt.lightmap,rt.emissivemap,rt.bumpmap,rt.normalmap,rt.displacementmap,rt.fog,rt.lights,{emissive:{value:new Ye(0)}}]),vertexShader:Jt.meshlambert_vert,fragmentShader:Jt.meshlambert_frag},phong:{uniforms:Vr([rt.common,rt.specularmap,rt.envmap,rt.aomap,rt.lightmap,rt.emissivemap,rt.bumpmap,rt.normalmap,rt.displacementmap,rt.fog,rt.lights,{emissive:{value:new Ye(0)},specular:{value:new Ye(1118481)},shininess:{value:30}}]),vertexShader:Jt.meshphong_vert,fragmentShader:Jt.meshphong_frag},standard:{uniforms:Vr([rt.common,rt.envmap,rt.aomap,rt.lightmap,rt.emissivemap,rt.bumpmap,rt.normalmap,rt.displacementmap,rt.roughnessmap,rt.metalnessmap,rt.fog,rt.lights,{emissive:{value:new Ye(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Jt.meshphysical_vert,fragmentShader:Jt.meshphysical_frag},toon:{uniforms:Vr([rt.common,rt.aomap,rt.lightmap,rt.emissivemap,rt.bumpmap,rt.normalmap,rt.displacementmap,rt.gradientmap,rt.fog,rt.lights,{emissive:{value:new Ye(0)}}]),vertexShader:Jt.meshtoon_vert,fragmentShader:Jt.meshtoon_frag},matcap:{uniforms:Vr([rt.common,rt.bumpmap,rt.normalmap,rt.displacementmap,rt.fog,{matcap:{value:null}}]),vertexShader:Jt.meshmatcap_vert,fragmentShader:Jt.meshmatcap_frag},points:{uniforms:Vr([rt.points,rt.fog]),vertexShader:Jt.points_vert,fragmentShader:Jt.points_frag},dashed:{uniforms:Vr([rt.common,rt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Jt.linedashed_vert,fragmentShader:Jt.linedashed_frag},depth:{uniforms:Vr([rt.common,rt.displacementmap]),vertexShader:Jt.depth_vert,fragmentShader:Jt.depth_frag},normal:{uniforms:Vr([rt.common,rt.bumpmap,rt.normalmap,rt.displacementmap,{opacity:{value:1}}]),vertexShader:Jt.meshnormal_vert,fragmentShader:Jt.meshnormal_frag},sprite:{uniforms:Vr([rt.sprite,rt.fog]),vertexShader:Jt.sprite_vert,fragmentShader:Jt.sprite_frag},background:{uniforms:{uvTransform:{value:new Mt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Jt.background_vert,fragmentShader:Jt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Mt}},vertexShader:Jt.backgroundCube_vert,fragmentShader:Jt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Jt.cube_vert,fragmentShader:Jt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Jt.equirect_vert,fragmentShader:Jt.equirect_frag},distanceRGBA:{uniforms:Vr([rt.common,rt.displacementmap,{referencePosition:{value:new D},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Jt.distanceRGBA_vert,fragmentShader:Jt.distanceRGBA_frag},shadow:{uniforms:Vr([rt.lights,rt.fog,{color:{value:new Ye(0)},opacity:{value:1}}]),vertexShader:Jt.shadow_vert,fragmentShader:Jt.shadow_frag}};Zs.physical={uniforms:Vr([Zs.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Mt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Mt},clearcoatNormalScale:{value:new re(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Mt},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Mt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Mt},sheen:{value:0},sheenColor:{value:new Ye(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Mt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Mt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Mt},transmissionSamplerSize:{value:new re},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Mt},attenuationDistance:{value:0},attenuationColor:{value:new Ye(0)},specularColor:{value:new Ye(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Mt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Mt},anisotropyVector:{value:new re},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Mt}}]),vertexShader:Jt.meshphysical_vert,fragmentShader:Jt.meshphysical_frag};const ax={r:0,b:0,g:0},ku=new Ai,FQ=new Me;function HQ(n,e,t,i,r,a,s){const o=new Ye(0);let l=a===!0?0:1,u,d,f=null,p=0,m=null;function v(E){let b=E.isScene===!0?E.background:null;return b&&b.isTexture&&(b=(E.backgroundBlurriness>0?t:e).get(b)),b}function x(E){let b=!1;const R=v(E);R===null?_(o,l):R&&R.isColor&&(_(R,1),b=!0);const w=n.xr.getEnvironmentBlendMode();w==="additive"?i.buffers.color.setClear(0,0,0,1,s):w==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,s),(n.autoClear||b)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function S(E,b){const R=v(b);R&&(R.isCubeTexture||R.mapping===jp)?(d===void 0&&(d=new jn(new $h(1,1,1),new Oi({name:"BackgroundCubeMaterial",uniforms:wp(Zs.backgroundCube.uniforms),vertexShader:Zs.backgroundCube.vertexShader,fragmentShader:Zs.backgroundCube.fragmentShader,side:ki,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(w,L,U){this.matrixWorld.copyPosition(U.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(d)),ku.copy(b.backgroundRotation),ku.x*=-1,ku.y*=-1,ku.z*=-1,R.isCubeTexture&&R.isRenderTargetTexture===!1&&(ku.y*=-1,ku.z*=-1),d.material.uniforms.envMap.value=R,d.material.uniforms.flipEnvMap.value=R.isCubeTexture&&R.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,d.material.uniforms.backgroundRotation.value.setFromMatrix4(FQ.makeRotationFromEuler(ku)),d.material.toneMapped=tn.getTransfer(R.colorSpace)!==Dn,(f!==R||p!==R.version||m!==n.toneMapping)&&(d.material.needsUpdate=!0,f=R,p=R.version,m=n.toneMapping),d.layers.enableAll(),E.unshift(d,d.geometry,d.material,0,0,null)):R&&R.isTexture&&(u===void 0&&(u=new jn(new uu(2,2),new Oi({name:"BackgroundMaterial",uniforms:wp(Zs.background.uniforms),vertexShader:Zs.background.vertexShader,fragmentShader:Zs.background.fragmentShader,side:eo,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),Object.defineProperty(u.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(u)),u.material.uniforms.t2D.value=R,u.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,u.material.toneMapped=tn.getTransfer(R.colorSpace)!==Dn,R.matrixAutoUpdate===!0&&R.updateMatrix(),u.material.uniforms.uvTransform.value.copy(R.matrix),(f!==R||p!==R.version||m!==n.toneMapping)&&(u.material.needsUpdate=!0,f=R,p=R.version,m=n.toneMapping),u.layers.enableAll(),E.unshift(u,u.geometry,u.material,0,0,null))}function _(E,b){E.getRGB(ax,U9(n)),i.buffers.color.setClear(ax.r,ax.g,ax.b,b,s)}function T(){d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0),u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0)}return{getClearColor:function(){return o},setClearColor:function(E,b=1){o.set(E),l=b,_(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(E){l=E,_(o,l)},render:x,addToRenderList:S,dispose:T}}function VQ(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},r=p(null);let a=r,s=!1;function o(C,z,W,K,oe){let ae=!1;const X=f(K,W,z);a!==X&&(a=X,u(a.object)),ae=m(C,K,W,oe),ae&&v(C,K,W,oe),oe!==null&&e.update(oe,n.ELEMENT_ARRAY_BUFFER),(ae||s)&&(s=!1,b(C,z,W,K),oe!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(oe).buffer))}function l(){return n.createVertexArray()}function u(C){return n.bindVertexArray(C)}function d(C){return n.deleteVertexArray(C)}function f(C,z,W){const K=W.wireframe===!0;let oe=i[C.id];oe===void 0&&(oe={},i[C.id]=oe);let ae=oe[z.id];ae===void 0&&(ae={},oe[z.id]=ae);let X=ae[K];return X===void 0&&(X=p(l()),ae[K]=X),X}function p(C){const z=[],W=[],K=[];for(let oe=0;oe=0){const se=oe[Q];let De=ae[Q];if(De===void 0&&(Q==="instanceMatrix"&&C.instanceMatrix&&(De=C.instanceMatrix),Q==="instanceColor"&&C.instanceColor&&(De=C.instanceColor)),se===void 0||se.attribute!==De||De&&se.data!==De.data)return!0;X++}return a.attributesNum!==X||a.index!==K}function v(C,z,W,K){const oe={},ae=z.attributes;let X=0;const te=W.getAttributes();for(const Q in te)if(te[Q].location>=0){let se=ae[Q];se===void 0&&(Q==="instanceMatrix"&&C.instanceMatrix&&(se=C.instanceMatrix),Q==="instanceColor"&&C.instanceColor&&(se=C.instanceColor));const De={};De.attribute=se,se&&se.data&&(De.data=se.data),oe[Q]=De,X++}a.attributes=oe,a.attributesNum=X,a.index=K}function x(){const C=a.newAttributes;for(let z=0,W=C.length;z=0){let ce=oe[te];if(ce===void 0&&(te==="instanceMatrix"&&C.instanceMatrix&&(ce=C.instanceMatrix),te==="instanceColor"&&C.instanceColor&&(ce=C.instanceColor)),ce!==void 0){const se=ce.normalized,De=ce.itemSize,Xe=e.get(ce);if(Xe===void 0)continue;const nt=Xe.buffer,tt=Xe.type,xt=Xe.bytesPerElement,ve=tt===n.INT||tt===n.UNSIGNED_INT||ce.gpuType===$g;if(ce.isInterleavedBufferAttribute){const we=ce.data,Ze=we.stride,de=ce.offset;if(we.isInstancedInterleavedBuffer){for(let it=0;it0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";L="mediump"}return L==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let u=t.precision!==void 0?t.precision:"highp";const d=l(u);d!==u&&(dt("WebGLRenderer:",u,"not supported, using",d,"instead."),u=d);const f=t.logarithmicDepthBuffer===!0,p=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),m=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),v=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),x=n.getParameter(n.MAX_TEXTURE_SIZE),S=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),_=n.getParameter(n.MAX_VERTEX_ATTRIBS),T=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),E=n.getParameter(n.MAX_VARYING_VECTORS),b=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),R=v>0,w=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:l,textureFormatReadable:s,textureTypeReadable:o,precision:u,logarithmicDepthBuffer:f,reversedDepthBuffer:p,maxTextures:m,maxVertexTextures:v,maxTextureSize:x,maxCubemapSize:S,maxAttributes:_,maxVertexUniforms:T,maxVaryings:E,maxFragmentUniforms:b,vertexTextures:R,maxSamples:w}}function WQ(n){const e=this;let t=null,i=0,r=!1,a=!1;const s=new xs,o=new Mt,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(f,p){const m=f.length!==0||p||i!==0||r;return r=p,i=f.length,m},this.beginShadows=function(){a=!0,d(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(f,p){t=d(f,p,0)},this.setState=function(f,p,m){const v=f.clippingPlanes,x=f.clipIntersection,S=f.clipShadows,_=n.get(f);if(!r||v===null||v.length===0||a&&!S)a?d(null):u();else{const T=a?0:i,E=T*4;let b=_.clippingState||null;l.value=b,b=d(v,p,E,m);for(let R=0;R!==E;++R)b[R]=t[R];_.clippingState=b,this.numIntersection=x?this.numPlanes:0,this.numPlanes+=T}};function u(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function d(f,p,m,v){const x=f!==null?f.length:0;let S=null;if(x!==0){if(S=l.value,v!==!0||S===null){const _=m+x*4,T=p.matrixWorldInverse;o.getNormalMatrix(T),(S===null||S.length<_)&&(S=new Float32Array(_));for(let E=0,b=m;E!==x;++E,b+=4)s.copy(f[E]).applyMatrix4(T,o),s.normal.toArray(S,b),S[b+3]=s.constant}l.value=S,l.needsUpdate=!0}return e.numPlanes=x,e.numIntersection=0,S}}function XQ(n){let e=new WeakMap;function t(s,o){return o===bg?s.mapping=Pl:o===Mg&&(s.mapping=$c),s}function i(s){if(s&&s.isTexture){const o=s.mapping;if(o===bg||o===Mg)if(e.has(s)){const l=e.get(s).texture;return t(l,s.mapping)}else{const l=s.image;if(l&&l.height>0){const u=new z9(l.height);return u.fromEquirectangularTexture(n,s),e.set(s,u),s.addEventListener("dispose",r),t(u.texture,s.mapping)}else return null}}return s}function r(s){const o=s.target;o.removeEventListener("dispose",r);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function a(){e=new WeakMap}return{get:i,dispose:a}}const Ic=4,iL=[.125,.215,.35,.446,.526,.582],lh=20,qQ=256,Zm=new Za,rL=new Ye;let vb=null,_b=0,xb=0,yb=!1;const YQ=new D;class j3{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,i=.1,r=100,a={}){const{size:s=256,position:o=YQ}=a;vb=this._renderer.getRenderTarget(),_b=this._renderer.getActiveCubeFace(),xb=this._renderer.getActiveMipmapLevel(),yb=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);const l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,r,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=oL(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=sL(),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?R:0,R,R),f.setRenderTarget(r),_&&f.render(x,l),f.render(e,l)}f.toneMapping=m,f.autoClear=p,e.background=T}_textureToCubeUV(e,t){const i=this._renderer,r=e.mapping===Pl||e.mapping===$c;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=oL()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=sL());const a=r?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=a;const o=a.uniforms;o.envMap.value=e;const l=this._cubeSize;nf(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(s,Zm)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const r=this._lodMeshes.length;for(let a=1;av-Ic?i-v+Ic:0),_=4*(this._cubeSize-x);l.envMap.value=e.texture,l.roughness.value=m,l.mipInt.value=v-t,nf(a,S,_,3*x,2*x),r.setRenderTarget(a),r.render(o,Zm),l.envMap.value=a.texture,l.roughness.value=0,l.mipInt.value=v-i,nf(e,S,_,3*x,2*x),r.setRenderTarget(e),r.render(o,Zm)}_blur(e,t,i,r,a){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,i,r,"latitudinal",a),this._halfBlur(s,e,i,i,r,"longitudinal",a)}_halfBlur(e,t,i,r,a,s,o){const l=this._renderer,u=this._blurMaterial;s!=="latitudinal"&&s!=="longitudinal"&&Ht("blur direction must be either latitudinal or longitudinal!");const d=3,f=this._lodMeshes[r];f.material=u;const p=u.uniforms,m=this._sizeLods[i]-1,v=isFinite(a)?Math.PI/(2*m):2*Math.PI/(2*lh-1),x=a/v,S=isFinite(a)?1+Math.floor(d*x):lh;S>lh&&dt(`sigmaRadians, ${a}, is too large and will clip, as it requested ${S} samples when the maximum is set to ${lh}`);const _=[];let T=0;for(let L=0;LE-Ic?r-E+Ic:0),w=4*(this._cubeSize-b);nf(t,R,w,3*b,2*b),l.setRenderTarget(t),l.render(f,Zm)}}function jQ(n){const e=[],t=[],i=[];let r=n;const a=n-Ic+1+iL.length;for(let s=0;sn-Ic?l=iL[s-n+Ic-1]:s===0&&(l=0),t.push(l);const u=1/(o-2),d=-u,f=1+u,p=[d,d,f,d,f,f,d,d,f,f,d,f],m=6,v=6,x=3,S=2,_=1,T=new Float32Array(x*v*m),E=new Float32Array(S*v*m),b=new Float32Array(_*v*m);for(let w=0;w2?0:-1,N=[L,U,0,L+2/3,U,0,L+2/3,U+1,0,L,U,0,L+2/3,U+1,0,L,U+1,0];T.set(N,x*v*w),E.set(p,S*v*w);const C=[w,w,w,w,w,w];b.set(C,_*v*w)}const R=new Ct;R.setAttribute("position",new bt(T,x)),R.setAttribute("uv",new bt(E,S)),R.setAttribute("faceIndex",new bt(b,_)),i.push(new jn(R,null)),r>Ic&&r--}return{lodMeshes:i,sizeLods:e,sigmas:t}}function aL(n,e,t){const i=new pi(n,e,t);return i.texture.mapping=jp,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function nf(n,e,t,i,r){n.viewport.set(e,t,i,r),n.scissor.set(e,t,i,r)}function ZQ(n,e,t){return new Oi({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:qQ,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:lT(),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 3.2: Transform view direction to hemisphere configuration + vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z)); + + // Section 4.1: Orthonormal basis + float lensq = Vh.x * Vh.x + Vh.y * Vh.y; + vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0); + vec3 T2 = cross(Vh, T1); + + // Section 4.2: Parameterization of projected area + float r = sqrt(Xi.x); + float phi = 2.0 * PI * Xi.y; + float t1 = r * cos(phi); + float t2 = r * sin(phi); + float s = 0.5 * (1.0 + Vh.z); + t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; + + // Section 4.3: Reprojection onto hemisphere + vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh; + + // Section 3.4: Transform back to ellipsoid configuration + return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); + } + + void main() { + vec3 N = normalize(vOutputDirection); + vec3 V = N; // Assume view direction equals normal for pre-filtering + + vec3 prefilteredColor = vec3(0.0); + float totalWeight = 0.0; + + // For very low roughness, just sample the environment directly + if (roughness < 0.001) { + gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); + return; + } + + // Tangent space basis for VNDF sampling + vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + + for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { + vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); + + // For PMREM, V = N, so in tangent space V is always (0, 0, 1) + vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); + + // Transform H back to world space + vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); + vec3 L = normalize(2.0 * dot(V, H) * H - V); + + float NdotL = max(dot(N, L), 0.0); + + if(NdotL > 0.0) { + // Sample environment at fixed mip level + // VNDF importance sampling handles the distribution filtering + vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); + + // Weight by NdotL for the split-sum approximation + // VNDF PDF naturally accounts for the visible microfacet distribution + prefilteredColor += sampleColor * NdotL; + totalWeight += NdotL; + } + } + + if (totalWeight > 0.0) { + prefilteredColor = prefilteredColor / totalWeight; + } + + gl_FragColor = vec4(prefilteredColor, 1.0); + } + `,blending:Lr,depthTest:!1,depthWrite:!1})}function QQ(n,e,t){const i=new Float32Array(lh),r=new D(0,1,0);return new Oi({name:"SphericalGaussianBlur",defines:{n:lh,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:lT(),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:Lr,depthTest:!1,depthWrite:!1})}function sL(){return new Oi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:lT(),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:Lr,depthTest:!1,depthWrite:!1})}function oL(){return new Oi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:lT(),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:Lr,depthTest:!1,depthWrite:!1})}function lT(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function KQ(n){let e=new WeakMap,t=null;function i(o){if(o&&o.isTexture){const l=o.mapping,u=l===bg||l===Mg,d=l===Pl||l===$c;if(u||d){let f=e.get(o);const p=f!==void 0?f.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==p)return t===null&&(t=new j3(n)),f=u?t.fromEquirectangular(o,f):t.fromCubemap(o,f),f.texture.pmremVersion=o.pmremVersion,e.set(o,f),f.texture;if(f!==void 0)return f.texture;{const m=o.image;return u&&m&&m.height>0||d&&m&&r(m)?(t===null&&(t=new j3(n)),f=u?t.fromEquirectangular(o):t.fromCubemap(o),f.texture.pmremVersion=o.pmremVersion,e.set(o,f),o.addEventListener("dispose",a),f.texture):null}}}return o}function r(o){let l=0;const u=6;for(let d=0;de.maxTextureSize&&(w=Math.ceil(R/e.maxTextureSize),R=e.maxTextureSize);const L=new Float32Array(R*w*4*f),U=new PS(L,R,w,f);U.type=fi,U.needsUpdate=!0;const N=b*4;for(let z=0;z0)return n;const r=e*t;let a=cL[r];if(a===void 0&&(a=new Float32Array(r),cL[r]=a),e!==0){i.toArray(a,0);for(let s=1,o=0;s!==e;++s)o+=t,n[s].toArray(a,o)}return a}function Ji(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t":" "} ${o}: ${t[s]}`)}return i.join(` +`)}const gL=new Mt;function KK(n){tn._getMatrix(gL,tn.workingColorSpace,n);const e=`mat3( ${gL.elements.map(t=>t.toFixed(4))} )`;switch(tn.getTransfer(n)){case wg:return[e,"LinearTransferOETF"];case Dn:return[e,"sRGBTransferOETF"];default:return dt("WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function vL(n,e,t){const i=n.getShaderParameter(e,n.COMPILE_STATUS),a=(n.getShaderInfoLog(e)||"").trim();if(i&&a==="")return"";const s=/ERROR: 0:(\d+)/.exec(a);if(s){const o=parseInt(s[1]);return t.toUpperCase()+` + +`+a+` + +`+QK(n.getShaderSource(e),o)}else return a}function JK(n,e){const t=KK(e);return[`vec4 ${n}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` +`)}function $K(n,e){let t;switch(e){case l9:t="Linear";break;case c9:t="Reinhard";break;case u9:t="Cineon";break;case jw:t="ACESFilmic";break;case d9:t="AgX";break;case f9:t="Neutral";break;case h9:t="Custom";break;default:dt("WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const sx=new D;function eJ(){tn.getLuminanceCoefficients(sx);const n=sx.x.toFixed(4),e=sx.y.toFixed(4),t=sx.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` +`)}function tJ(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(R0).join(` +`)}function nJ(n){const e=[];for(const t in n){const i=n[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(` +`)}function iJ(n,e){const t={},i=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let r=0;r/gm;function Z3(n){return n.replace(rJ,sJ)}const aJ=new Map;function sJ(n,e){let t=Jt[e];if(t===void 0){const i=aJ.get(e);if(i!==void 0)t=Jt[i],dt('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return Z3(t)}const oJ=/#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 yL(n){return n.replace(oJ,lJ)}function lJ(n,e,t,i){let r="";for(let a=parseInt(e);a0&&(S+=` +`),_=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,v].filter(R0).join(` +`),_.length>0&&(_+=` +`)):(S=[SL(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,v,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+d:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.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(R0).join(` +`),_=[SL(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,v,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.envMap?"#define "+d:"",t.envMap?"#define "+f:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==As?"#define TONE_MAPPING":"",t.toneMapping!==As?Jt.tonemapping_pars_fragment:"",t.toneMapping!==As?$K("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Jt.colorspace_pars_fragment,JK("linearToOutputTexel",t.outputColorSpace),eJ(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(R0).join(` +`)),s=Z3(s),s=_L(s,t),s=xL(s,t),o=Z3(o),o=_L(o,t),o=xL(o,t),s=yL(s),o=yL(o),t.isRawShaderMaterial!==!0&&(T=`#version 300 es +`,S=[m,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+S,_=["#define varying in",t.glslVersion===No?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===No?"":"#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(` +`)+` +`+_);const E=T+S+s,b=T+_+o,R=mL(r,r.VERTEX_SHADER,E),w=mL(r,r.FRAGMENT_SHADER,b);r.attachShader(x,R),r.attachShader(x,w),t.index0AttributeName!==void 0?r.bindAttribLocation(x,0,t.index0AttributeName):t.morphTargets===!0&&r.bindAttribLocation(x,0,"position"),r.linkProgram(x);function L(z){if(n.debug.checkShaderErrors){const W=r.getProgramInfoLog(x)||"",K=r.getShaderInfoLog(R)||"",oe=r.getShaderInfoLog(w)||"",ae=W.trim(),X=K.trim(),te=oe.trim();let Q=!0,ce=!0;if(r.getProgramParameter(x,r.LINK_STATUS)===!1)if(Q=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(r,x,R,w);else{const se=vL(r,R,"vertex"),De=vL(r,w,"fragment");Ht("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(x,r.VALIDATE_STATUS)+` + +Material Name: `+z.name+` +Material Type: `+z.type+` + +Program Info Log: `+ae+` +`+se+` +`+De)}else ae!==""?dt("WebGLProgram: Program Info Log:",ae):(X===""||te==="")&&(ce=!1);ce&&(z.diagnostics={runnable:Q,programLog:ae,vertexShader:{log:X,prefix:S},fragmentShader:{log:te,prefix:_}})}r.deleteShader(R),r.deleteShader(w),U=new u1(r,x),N=iJ(r,x)}let U;this.getUniforms=function(){return U===void 0&&L(this),U};let N;this.getAttributes=function(){return N===void 0&&L(this),N};let C=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return C===!1&&(C=r.getProgramParameter(x,jK)),C},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(x),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=ZK++,this.cacheKey=e,this.usedTimes=1,this.program=x,this.vertexShader=R,this.fragmentShader=w,this}let mJ=0;class gJ{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,r=this._getShaderStage(t),a=this._getShaderStage(i),s=this._getShaderCacheForMaterial(e);return s.has(r)===!1&&(s.add(r),r.usedTimes++),s.has(a)===!1&&(s.add(a),a.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new vJ(e),t.set(e,i)),i}}class vJ{constructor(e){this.id=mJ++,this.code=e,this.usedTimes=0}}function _J(n,e,t,i,r,a,s){const o=new Ap,l=new gJ,u=new Set,d=[],f=r.logarithmicDepthBuffer,p=r.vertexTextures;let m=r.precision;const v={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function x(N){return u.add(N),N===0?"uv":`uv${N}`}function S(N,C,z,W,K){const oe=W.fog,ae=K.geometry,X=N.isMeshStandardMaterial?W.environment:null,te=(N.isMeshStandardMaterial?t:e).get(N.envMap||X),Q=te&&te.mapping===jp?te.image.height:null,ce=v[N.type];N.precision!==null&&(m=r.getMaxPrecision(N.precision),m!==N.precision&&dt("WebGLProgram.getParameters:",N.precision,"not supported, using",m,"instead."));const se=ae.morphAttributes.position||ae.morphAttributes.normal||ae.morphAttributes.color,De=se!==void 0?se.length:0;let Xe=0;ae.morphAttributes.position!==void 0&&(Xe=1),ae.morphAttributes.normal!==void 0&&(Xe=2),ae.morphAttributes.color!==void 0&&(Xe=3);let nt,tt,xt,ve;if(ce){const kt=Zs[ce];nt=kt.vertexShader,tt=kt.fragmentShader}else nt=N.vertexShader,tt=N.fragmentShader,l.update(N),xt=l.getVertexShaderID(N),ve=l.getFragmentShaderID(N);const we=n.getRenderTarget(),Ze=n.state.buffers.depth.getReversed(),de=K.isInstancedMesh===!0,it=K.isBatchedMesh===!0,wt=!!N.map,ct=!!N.matcap,Qe=!!te,Ee=!!N.aoMap,V=!!N.lightMap,Ae=!!N.bumpMap,Oe=!!N.normalMap,Ve=!!N.displacementMap,Fe=!!N.emissiveMap,$e=!!N.metalnessMap,Je=!!N.roughnessMap,ht=N.anisotropy>0,k=N.clearcoat>0,P=N.dispersion>0,he=N.iridescence>0,be=N.sheen>0,Ie=N.transmission>0,Se=ht&&!!N.anisotropyMap,yt=k&&!!N.clearcoatMap,je=k&&!!N.clearcoatNormalMap,Tt=k&&!!N.clearcoatRoughnessMap,vt=he&&!!N.iridescenceMap,Ue=he&&!!N.iridescenceThicknessMap,He=be&&!!N.sheenColorMap,pt=be&&!!N.sheenRoughnessMap,J=!!N.specularMap,me=!!N.specularColorMap,Le=!!N.specularIntensityMap,j=Ie&&!!N.transmissionMap,ke=Ie&&!!N.thicknessMap,ge=!!N.gradientMap,We=!!N.alphaMap,Ge=N.alphaTest>0,Re=!!N.alphaHash,at=!!N.extensions;let Et=As;N.toneMapped&&(we===null||we.isXRRenderTarget===!0)&&(Et=n.toneMapping);const Gt={shaderID:ce,shaderType:N.type,shaderName:N.name,vertexShader:nt,fragmentShader:tt,defines:N.defines,customVertexShaderID:xt,customFragmentShaderID:ve,isRawShaderMaterial:N.isRawShaderMaterial===!0,glslVersion:N.glslVersion,precision:m,batching:it,batchingColor:it&&K._colorsTexture!==null,instancing:de,instancingColor:de&&K.instanceColor!==null,instancingMorph:de&&K.morphTexture!==null,supportsVertexTextures:p,outputColorSpace:we===null?n.outputColorSpace:we.isXRRenderTarget===!0?we.texture.colorSpace:Xn,alphaToCoverage:!!N.alphaToCoverage,map:wt,matcap:ct,envMap:Qe,envMapMode:Qe&&te.mapping,envMapCubeUVHeight:Q,aoMap:Ee,lightMap:V,bumpMap:Ae,normalMap:Oe,displacementMap:p&&Ve,emissiveMap:Fe,normalMapObjectSpace:Oe&&N.normalMapType===y9,normalMapTangentSpace:Oe&&N.normalMapType===Hl,metalnessMap:$e,roughnessMap:Je,anisotropy:ht,anisotropyMap:Se,clearcoat:k,clearcoatMap:yt,clearcoatNormalMap:je,clearcoatRoughnessMap:Tt,dispersion:P,iridescence:he,iridescenceMap:vt,iridescenceThicknessMap:Ue,sheen:be,sheenColorMap:He,sheenRoughnessMap:pt,specularMap:J,specularColorMap:me,specularIntensityMap:Le,transmission:Ie,transmissionMap:j,thicknessMap:ke,gradientMap:ge,opaque:N.transparent===!1&&N.blending===Eh&&N.alphaToCoverage===!1,alphaMap:We,alphaTest:Ge,alphaHash:Re,combine:N.combine,mapUv:wt&&x(N.map.channel),aoMapUv:Ee&&x(N.aoMap.channel),lightMapUv:V&&x(N.lightMap.channel),bumpMapUv:Ae&&x(N.bumpMap.channel),normalMapUv:Oe&&x(N.normalMap.channel),displacementMapUv:Ve&&x(N.displacementMap.channel),emissiveMapUv:Fe&&x(N.emissiveMap.channel),metalnessMapUv:$e&&x(N.metalnessMap.channel),roughnessMapUv:Je&&x(N.roughnessMap.channel),anisotropyMapUv:Se&&x(N.anisotropyMap.channel),clearcoatMapUv:yt&&x(N.clearcoatMap.channel),clearcoatNormalMapUv:je&&x(N.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Tt&&x(N.clearcoatRoughnessMap.channel),iridescenceMapUv:vt&&x(N.iridescenceMap.channel),iridescenceThicknessMapUv:Ue&&x(N.iridescenceThicknessMap.channel),sheenColorMapUv:He&&x(N.sheenColorMap.channel),sheenRoughnessMapUv:pt&&x(N.sheenRoughnessMap.channel),specularMapUv:J&&x(N.specularMap.channel),specularColorMapUv:me&&x(N.specularColorMap.channel),specularIntensityMapUv:Le&&x(N.specularIntensityMap.channel),transmissionMapUv:j&&x(N.transmissionMap.channel),thicknessMapUv:ke&&x(N.thicknessMap.channel),alphaMapUv:We&&x(N.alphaMap.channel),vertexTangents:!!ae.attributes.tangent&&(Oe||ht),vertexColors:N.vertexColors,vertexAlphas:N.vertexColors===!0&&!!ae.attributes.color&&ae.attributes.color.itemSize===4,pointsUvs:K.isPoints===!0&&!!ae.attributes.uv&&(wt||We),fog:!!oe,useFog:N.fog===!0,fogExp2:!!oe&&oe.isFogExp2,flatShading:N.flatShading===!0&&N.wireframe===!1,sizeAttenuation:N.sizeAttenuation===!0,logarithmicDepthBuffer:f,reversedDepthBuffer:Ze,skinning:K.isSkinnedMesh===!0,morphTargets:ae.morphAttributes.position!==void 0,morphNormals:ae.morphAttributes.normal!==void 0,morphColors:ae.morphAttributes.color!==void 0,morphTargetsCount:De,morphTextureStride:Xe,numDirLights:C.directional.length,numPointLights:C.point.length,numSpotLights:C.spot.length,numSpotLightMaps:C.spotLightMap.length,numRectAreaLights:C.rectArea.length,numHemiLights:C.hemi.length,numDirLightShadows:C.directionalShadowMap.length,numPointLightShadows:C.pointShadowMap.length,numSpotLightShadows:C.spotShadowMap.length,numSpotLightShadowsWithMaps:C.numSpotLightShadowsWithMaps,numLightProbes:C.numLightProbes,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:N.dithering,shadowMapEnabled:n.shadowMap.enabled&&z.length>0,shadowMapType:n.shadowMap.type,toneMapping:Et,decodeVideoTexture:wt&&N.map.isVideoTexture===!0&&tn.getTransfer(N.map.colorSpace)===Dn,decodeVideoTextureEmissive:Fe&&N.emissiveMap.isVideoTexture===!0&&tn.getTransfer(N.emissiveMap.colorSpace)===Dn,premultipliedAlpha:N.premultipliedAlpha,doubleSided:N.side===xr,flipSided:N.side===ki,useDepthPacking:N.depthPacking>=0,depthPacking:N.depthPacking||0,index0AttributeName:N.index0AttributeName,extensionClipCullDistance:at&&N.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(at&&N.extensions.multiDraw===!0||it)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:N.customProgramCacheKey()};return Gt.vertexUv1s=u.has(1),Gt.vertexUv2s=u.has(2),Gt.vertexUv3s=u.has(3),u.clear(),Gt}function _(N){const C=[];if(N.shaderID?C.push(N.shaderID):(C.push(N.customVertexShaderID),C.push(N.customFragmentShaderID)),N.defines!==void 0)for(const z in N.defines)C.push(z),C.push(N.defines[z]);return N.isRawShaderMaterial===!1&&(T(C,N),E(C,N),C.push(n.outputColorSpace)),C.push(N.customProgramCacheKey),C.join()}function T(N,C){N.push(C.precision),N.push(C.outputColorSpace),N.push(C.envMapMode),N.push(C.envMapCubeUVHeight),N.push(C.mapUv),N.push(C.alphaMapUv),N.push(C.lightMapUv),N.push(C.aoMapUv),N.push(C.bumpMapUv),N.push(C.normalMapUv),N.push(C.displacementMapUv),N.push(C.emissiveMapUv),N.push(C.metalnessMapUv),N.push(C.roughnessMapUv),N.push(C.anisotropyMapUv),N.push(C.clearcoatMapUv),N.push(C.clearcoatNormalMapUv),N.push(C.clearcoatRoughnessMapUv),N.push(C.iridescenceMapUv),N.push(C.iridescenceThicknessMapUv),N.push(C.sheenColorMapUv),N.push(C.sheenRoughnessMapUv),N.push(C.specularMapUv),N.push(C.specularColorMapUv),N.push(C.specularIntensityMapUv),N.push(C.transmissionMapUv),N.push(C.thicknessMapUv),N.push(C.combine),N.push(C.fogExp2),N.push(C.sizeAttenuation),N.push(C.morphTargetsCount),N.push(C.morphAttributeCount),N.push(C.numDirLights),N.push(C.numPointLights),N.push(C.numSpotLights),N.push(C.numSpotLightMaps),N.push(C.numHemiLights),N.push(C.numRectAreaLights),N.push(C.numDirLightShadows),N.push(C.numPointLightShadows),N.push(C.numSpotLightShadows),N.push(C.numSpotLightShadowsWithMaps),N.push(C.numLightProbes),N.push(C.shadowMapType),N.push(C.toneMapping),N.push(C.numClippingPlanes),N.push(C.numClipIntersection),N.push(C.depthPacking)}function E(N,C){o.disableAll(),C.supportsVertexTextures&&o.enable(0),C.instancing&&o.enable(1),C.instancingColor&&o.enable(2),C.instancingMorph&&o.enable(3),C.matcap&&o.enable(4),C.envMap&&o.enable(5),C.normalMapObjectSpace&&o.enable(6),C.normalMapTangentSpace&&o.enable(7),C.clearcoat&&o.enable(8),C.iridescence&&o.enable(9),C.alphaTest&&o.enable(10),C.vertexColors&&o.enable(11),C.vertexAlphas&&o.enable(12),C.vertexUv1s&&o.enable(13),C.vertexUv2s&&o.enable(14),C.vertexUv3s&&o.enable(15),C.vertexTangents&&o.enable(16),C.anisotropy&&o.enable(17),C.alphaHash&&o.enable(18),C.batching&&o.enable(19),C.dispersion&&o.enable(20),C.batchingColor&&o.enable(21),C.gradientMap&&o.enable(22),N.push(o.mask),o.disableAll(),C.fog&&o.enable(0),C.useFog&&o.enable(1),C.flatShading&&o.enable(2),C.logarithmicDepthBuffer&&o.enable(3),C.reversedDepthBuffer&&o.enable(4),C.skinning&&o.enable(5),C.morphTargets&&o.enable(6),C.morphNormals&&o.enable(7),C.morphColors&&o.enable(8),C.premultipliedAlpha&&o.enable(9),C.shadowMapEnabled&&o.enable(10),C.doubleSided&&o.enable(11),C.flipSided&&o.enable(12),C.useDepthPacking&&o.enable(13),C.dithering&&o.enable(14),C.transmission&&o.enable(15),C.sheen&&o.enable(16),C.opaque&&o.enable(17),C.pointsUvs&&o.enable(18),C.decodeVideoTexture&&o.enable(19),C.decodeVideoTextureEmissive&&o.enable(20),C.alphaToCoverage&&o.enable(21),N.push(o.mask)}function b(N){const C=v[N.type];let z;if(C){const W=Zs[C];z=oR.clone(W.uniforms)}else z=N.uniforms;return z}function R(N,C){let z;for(let W=0,K=d.length;W0?i.push(_):m.transparent===!0?r.push(_):t.push(_)}function l(f,p,m,v,x,S){const _=s(f,p,m,v,x,S);m.transmission>0?i.unshift(_):m.transparent===!0?r.unshift(_):t.unshift(_)}function u(f,p){t.length>1&&t.sort(f||yJ),i.length>1&&i.sort(p||TL),r.length>1&&r.sort(p||TL)}function d(){for(let f=e,p=n.length;f=a.length?(s=new EL,a.push(s)):s=a[r],s}function t(){n=new WeakMap}return{get:e,dispose:t}}function TJ(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new D,color:new Ye};break;case"SpotLight":t={position:new D,direction:new D,color:new Ye,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new D,color:new Ye,distance:0,decay:0};break;case"HemisphereLight":t={direction:new D,skyColor:new Ye,groundColor:new Ye};break;case"RectAreaLight":t={color:new Ye,position:new D,halfWidth:new D,halfHeight:new D};break}return n[e.id]=t,t}}}function EJ(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new re};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new re};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new re,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let bJ=0;function MJ(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function AJ(n){const e=new TJ,t=EJ(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let u=0;u<9;u++)i.probe.push(new D);const r=new D,a=new Me,s=new Me;function o(u){let d=0,f=0,p=0;for(let N=0;N<9;N++)i.probe[N].set(0,0,0);let m=0,v=0,x=0,S=0,_=0,T=0,E=0,b=0,R=0,w=0,L=0;u.sort(MJ);for(let N=0,C=u.length;N0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=rt.LTC_FLOAT_1,i.rectAreaLTC2=rt.LTC_FLOAT_2):(i.rectAreaLTC1=rt.LTC_HALF_1,i.rectAreaLTC2=rt.LTC_HALF_2)),i.ambient[0]=d,i.ambient[1]=f,i.ambient[2]=p;const U=i.hash;(U.directionalLength!==m||U.pointLength!==v||U.spotLength!==x||U.rectAreaLength!==S||U.hemiLength!==_||U.numDirectionalShadows!==T||U.numPointShadows!==E||U.numSpotShadows!==b||U.numSpotMaps!==R||U.numLightProbes!==L)&&(i.directional.length=m,i.spot.length=x,i.rectArea.length=S,i.point.length=v,i.hemi.length=_,i.directionalShadow.length=T,i.directionalShadowMap.length=T,i.pointShadow.length=E,i.pointShadowMap.length=E,i.spotShadow.length=b,i.spotShadowMap.length=b,i.directionalShadowMatrix.length=T,i.pointShadowMatrix.length=E,i.spotLightMatrix.length=b+R-w,i.spotLightMap.length=R,i.numSpotLightShadowsWithMaps=w,i.numLightProbes=L,U.directionalLength=m,U.pointLength=v,U.spotLength=x,U.rectAreaLength=S,U.hemiLength=_,U.numDirectionalShadows=T,U.numPointShadows=E,U.numSpotShadows=b,U.numSpotMaps=R,U.numLightProbes=L,i.version=bJ++)}function l(u,d){let f=0,p=0,m=0,v=0,x=0;const S=d.matrixWorldInverse;for(let _=0,T=u.length;_=s.length?(o=new bL(n),s.push(o)):o=s[a],o}function i(){e=new WeakMap}return{get:t,dispose:i}}const RJ=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,CJ=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`;function DJ(n,e,t){let i=new ed;const r=new re,a=new re,s=new Pt,o=new _R({depthPacking:x9}),l=new xR,u={},d=t.maxTextureSize,f={[eo]:ki,[ki]:eo,[xr]:xr},p=new Oi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new re},radius:{value:4}},vertexShader:RJ,fragmentShader:CJ}),m=p.clone();m.defines.HORIZONTAL_PASS=1;const v=new Ct;v.setAttribute("position",new bt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const x=new jn(v,p),S=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=MS;let _=this.type;this.render=function(w,L,U){if(S.enabled===!1||S.autoUpdate===!1&&S.needsUpdate===!1||w.length===0)return;const N=n.getRenderTarget(),C=n.getActiveCubeFace(),z=n.getActiveMipmapLevel(),W=n.state;W.setBlending(Lr),W.buffers.depth.getReversed()===!0?W.buffers.color.setClear(0,0,0,0):W.buffers.color.setClear(1,1,1,1),W.buffers.depth.setTest(!0),W.setScissorTest(!1);const K=_!==Xs&&this.type===Xs,oe=_===Xs&&this.type!==Xs;for(let ae=0,X=w.length;aed||r.y>d)&&(r.x>d&&(a.x=Math.floor(d/ce.x),r.x=a.x*ce.x,Q.mapSize.x=a.x),r.y>d&&(a.y=Math.floor(d/ce.y),r.y=a.y*ce.y,Q.mapSize.y=a.y)),Q.map===null||K===!0||oe===!0){const De=this.type!==Xs?{minFilter:Yn,magFilter:Yn}:{};Q.map!==null&&Q.map.dispose(),Q.map=new pi(r.x,r.y,De),Q.map.texture.name=te.name+".shadowMap",Q.camera.updateProjectionMatrix()}n.setRenderTarget(Q.map),n.clear();const se=Q.getViewportCount();for(let De=0;De0||L.map&&L.alphaTest>0||L.alphaToCoverage===!0){const W=C.uuid,K=L.uuid;let oe=u[W];oe===void 0&&(oe={},u[W]=oe);let ae=oe[K];ae===void 0&&(ae=C.clone(),oe[K]=ae,L.addEventListener("dispose",R)),C=ae}if(C.visible=L.visible,C.wireframe=L.wireframe,N===Xs?C.side=L.shadowSide!==null?L.shadowSide:L.side:C.side=L.shadowSide!==null?L.shadowSide:f[L.side],C.alphaMap=L.alphaMap,C.alphaTest=L.alphaToCoverage===!0?.5:L.alphaTest,C.map=L.map,C.clipShadows=L.clipShadows,C.clippingPlanes=L.clippingPlanes,C.clipIntersection=L.clipIntersection,C.displacementMap=L.displacementMap,C.displacementScale=L.displacementScale,C.displacementBias=L.displacementBias,C.wireframeLinewidth=L.wireframeLinewidth,C.linewidth=L.linewidth,U.isPointLight===!0&&C.isMeshDistanceMaterial===!0){const W=n.properties.get(C);W.light=U}return C}function b(w,L,U,N,C){if(w.visible===!1)return;if(w.layers.test(L.layers)&&(w.isMesh||w.isLine||w.isPoints)&&(w.castShadow||w.receiveShadow&&C===Xs)&&(!w.frustumCulled||i.intersectsObject(w))){w.modelViewMatrix.multiplyMatrices(U.matrixWorldInverse,w.matrixWorld);const K=e.update(w),oe=w.material;if(Array.isArray(oe)){const ae=K.groups;for(let X=0,te=ae.length;X=1):Q.indexOf("OpenGL ES")!==-1&&(te=parseFloat(/^OpenGL ES (\d)/.exec(Q)[1]),X=te>=2);let ce=null,se={};const De=n.getParameter(n.SCISSOR_BOX),Xe=n.getParameter(n.VIEWPORT),nt=new Pt().fromArray(De),tt=new Pt().fromArray(Xe);function xt(j,ke,ge,We){const Ge=new Uint8Array(4),Re=n.createTexture();n.bindTexture(j,Re),n.texParameteri(j,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(j,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let at=0;at"u"?!1:/OculusBrowser/g.test(navigator.userAgent),u=new re,d=new WeakMap;let f;const p=new WeakMap;let m=!1;try{m=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function v(k,P){return m?new OffscreenCanvas(k,P):Cg("canvas")}function x(k,P,he){let be=1;const Ie=ht(k);if((Ie.width>he||Ie.height>he)&&(be=he/Math.max(Ie.width,Ie.height)),be<1)if(typeof HTMLImageElement<"u"&&k instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&k instanceof ImageBitmap||typeof VideoFrame<"u"&&k instanceof VideoFrame){const Se=Math.floor(be*Ie.width),yt=Math.floor(be*Ie.height);f===void 0&&(f=v(Se,yt));const je=P?v(Se,yt):f;return je.width=Se,je.height=yt,je.getContext("2d").drawImage(k,0,0,Se,yt),dt("WebGLRenderer: Texture has been resized from ("+Ie.width+"x"+Ie.height+") to ("+Se+"x"+yt+")."),je}else return"data"in k&&dt("WebGLRenderer: Image in DataTexture is too big ("+Ie.width+"x"+Ie.height+")."),k;return k}function S(k){return k.generateMipmaps}function _(k){n.generateMipmap(k)}function T(k){return k.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:k.isWebGL3DRenderTarget?n.TEXTURE_3D:k.isWebGLArrayRenderTarget||k.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function E(k,P,he,be,Ie=!1){if(k!==null){if(n[k]!==void 0)return n[k];dt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+k+"'")}let Se=P;if(P===n.RED&&(he===n.FLOAT&&(Se=n.R32F),he===n.HALF_FLOAT&&(Se=n.R16F),he===n.UNSIGNED_BYTE&&(Se=n.R8)),P===n.RED_INTEGER&&(he===n.UNSIGNED_BYTE&&(Se=n.R8UI),he===n.UNSIGNED_SHORT&&(Se=n.R16UI),he===n.UNSIGNED_INT&&(Se=n.R32UI),he===n.BYTE&&(Se=n.R8I),he===n.SHORT&&(Se=n.R16I),he===n.INT&&(Se=n.R32I)),P===n.RG&&(he===n.FLOAT&&(Se=n.RG32F),he===n.HALF_FLOAT&&(Se=n.RG16F),he===n.UNSIGNED_BYTE&&(Se=n.RG8)),P===n.RG_INTEGER&&(he===n.UNSIGNED_BYTE&&(Se=n.RG8UI),he===n.UNSIGNED_SHORT&&(Se=n.RG16UI),he===n.UNSIGNED_INT&&(Se=n.RG32UI),he===n.BYTE&&(Se=n.RG8I),he===n.SHORT&&(Se=n.RG16I),he===n.INT&&(Se=n.RG32I)),P===n.RGB_INTEGER&&(he===n.UNSIGNED_BYTE&&(Se=n.RGB8UI),he===n.UNSIGNED_SHORT&&(Se=n.RGB16UI),he===n.UNSIGNED_INT&&(Se=n.RGB32UI),he===n.BYTE&&(Se=n.RGB8I),he===n.SHORT&&(Se=n.RGB16I),he===n.INT&&(Se=n.RGB32I)),P===n.RGBA_INTEGER&&(he===n.UNSIGNED_BYTE&&(Se=n.RGBA8UI),he===n.UNSIGNED_SHORT&&(Se=n.RGBA16UI),he===n.UNSIGNED_INT&&(Se=n.RGBA32UI),he===n.BYTE&&(Se=n.RGBA8I),he===n.SHORT&&(Se=n.RGBA16I),he===n.INT&&(Se=n.RGBA32I)),P===n.RGB&&(he===n.UNSIGNED_INT_5_9_9_9_REV&&(Se=n.RGB9_E5),he===n.UNSIGNED_INT_10F_11F_11F_REV&&(Se=n.R11F_G11F_B10F)),P===n.RGBA){const yt=Ie?wg:tn.getTransfer(be);he===n.FLOAT&&(Se=n.RGBA32F),he===n.HALF_FLOAT&&(Se=n.RGBA16F),he===n.UNSIGNED_BYTE&&(Se=yt===Dn?n.SRGB8_ALPHA8:n.RGBA8),he===n.UNSIGNED_SHORT_4_4_4_4&&(Se=n.RGBA4),he===n.UNSIGNED_SHORT_5_5_5_1&&(Se=n.RGB5_A1)}return(Se===n.R16F||Se===n.R32F||Se===n.RG16F||Se===n.RG32F||Se===n.RGBA16F||Se===n.RGBA32F)&&e.get("EXT_color_buffer_float"),Se}function b(k,P){let he;return k?P===null||P===to||P===Ph?he=n.DEPTH24_STENCIL8:P===fi?he=n.DEPTH32F_STENCIL8:P===Uh&&(he=n.DEPTH24_STENCIL8,dt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):P===null||P===to||P===Ph?he=n.DEPTH_COMPONENT24:P===fi?he=n.DEPTH_COMPONENT32F:P===Uh&&(he=n.DEPTH_COMPONENT16),he}function R(k,P){return S(k)===!0||k.isFramebufferTexture&&k.minFilter!==Yn&&k.minFilter!==Bt?Math.log2(Math.max(P.width,P.height))+1:k.mipmaps!==void 0&&k.mipmaps.length>0?k.mipmaps.length:k.isCompressedTexture&&Array.isArray(k.image)?P.mipmaps.length:1}function w(k){const P=k.target;P.removeEventListener("dispose",w),U(P),P.isVideoTexture&&d.delete(P)}function L(k){const P=k.target;P.removeEventListener("dispose",L),C(P)}function U(k){const P=i.get(k);if(P.__webglInit===void 0)return;const he=k.source,be=p.get(he);if(be){const Ie=be[P.__cacheKey];Ie.usedTimes--,Ie.usedTimes===0&&N(k),Object.keys(be).length===0&&p.delete(he)}i.remove(k)}function N(k){const P=i.get(k);n.deleteTexture(P.__webglTexture);const he=k.source,be=p.get(he);delete be[P.__cacheKey],s.memory.textures--}function C(k){const P=i.get(k);if(k.depthTexture&&(k.depthTexture.dispose(),i.remove(k.depthTexture)),k.isWebGLCubeRenderTarget)for(let be=0;be<6;be++){if(Array.isArray(P.__webglFramebuffer[be]))for(let Ie=0;Ie=r.maxTextures&&dt("WebGLTextures: Trying to use "+k+" texture units while this GPU supports only "+r.maxTextures),z+=1,k}function oe(k){const P=[];return P.push(k.wrapS),P.push(k.wrapT),P.push(k.wrapR||0),P.push(k.magFilter),P.push(k.minFilter),P.push(k.anisotropy),P.push(k.internalFormat),P.push(k.format),P.push(k.type),P.push(k.generateMipmaps),P.push(k.premultiplyAlpha),P.push(k.flipY),P.push(k.unpackAlignment),P.push(k.colorSpace),P.join()}function ae(k,P){const he=i.get(k);if(k.isVideoTexture&&$e(k),k.isRenderTargetTexture===!1&&k.isExternalTexture!==!0&&k.version>0&&he.__version!==k.version){const be=k.image;if(be===null)dt("WebGLRenderer: Texture marked for update but no image data found.");else if(be.complete===!1)dt("WebGLRenderer: Texture marked for update but image is incomplete");else{ve(he,k,P);return}}else k.isExternalTexture&&(he.__webglTexture=k.sourceTexture?k.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,he.__webglTexture,n.TEXTURE0+P)}function X(k,P){const he=i.get(k);if(k.isRenderTargetTexture===!1&&k.version>0&&he.__version!==k.version){ve(he,k,P);return}else k.isExternalTexture&&(he.__webglTexture=k.sourceTexture?k.sourceTexture:null);t.bindTexture(n.TEXTURE_2D_ARRAY,he.__webglTexture,n.TEXTURE0+P)}function te(k,P){const he=i.get(k);if(k.isRenderTargetTexture===!1&&k.version>0&&he.__version!==k.version){ve(he,k,P);return}t.bindTexture(n.TEXTURE_3D,he.__webglTexture,n.TEXTURE0+P)}function Q(k,P){const he=i.get(k);if(k.version>0&&he.__version!==k.version){we(he,k,P);return}t.bindTexture(n.TEXTURE_CUBE_MAP,he.__webglTexture,n.TEXTURE0+P)}const ce={[Ir]:n.REPEAT,[Wi]:n.CLAMP_TO_EDGE,[xp]:n.MIRRORED_REPEAT},se={[Yn]:n.NEAREST,[RS]:n.NEAREST_MIPMAP_NEAREST,[hh]:n.NEAREST_MIPMAP_LINEAR,[Bt]:n.LINEAR,[np]:n.LINEAR_MIPMAP_NEAREST,[Ga]:n.LINEAR_MIPMAP_LINEAR},De={[S9]:n.NEVER,[w9]:n.ALWAYS,[T9]:n.LESS,[nR]:n.LEQUAL,[E9]:n.EQUAL,[A9]:n.GEQUAL,[b9]:n.GREATER,[M9]:n.NOTEQUAL};function Xe(k,P){if(P.type===fi&&e.has("OES_texture_float_linear")===!1&&(P.magFilter===Bt||P.magFilter===np||P.magFilter===hh||P.magFilter===Ga||P.minFilter===Bt||P.minFilter===np||P.minFilter===hh||P.minFilter===Ga)&&dt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(k,n.TEXTURE_WRAP_S,ce[P.wrapS]),n.texParameteri(k,n.TEXTURE_WRAP_T,ce[P.wrapT]),(k===n.TEXTURE_3D||k===n.TEXTURE_2D_ARRAY)&&n.texParameteri(k,n.TEXTURE_WRAP_R,ce[P.wrapR]),n.texParameteri(k,n.TEXTURE_MAG_FILTER,se[P.magFilter]),n.texParameteri(k,n.TEXTURE_MIN_FILTER,se[P.minFilter]),P.compareFunction&&(n.texParameteri(k,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(k,n.TEXTURE_COMPARE_FUNC,De[P.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(P.magFilter===Yn||P.minFilter!==hh&&P.minFilter!==Ga||P.type===fi&&e.has("OES_texture_float_linear")===!1)return;if(P.anisotropy>1||i.get(P).__currentAnisotropy){const he=e.get("EXT_texture_filter_anisotropic");n.texParameterf(k,he.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(P.anisotropy,r.getMaxAnisotropy())),i.get(P).__currentAnisotropy=P.anisotropy}}}function nt(k,P){let he=!1;k.__webglInit===void 0&&(k.__webglInit=!0,P.addEventListener("dispose",w));const be=P.source;let Ie=p.get(be);Ie===void 0&&(Ie={},p.set(be,Ie));const Se=oe(P);if(Se!==k.__cacheKey){Ie[Se]===void 0&&(Ie[Se]={texture:n.createTexture(),usedTimes:0},s.memory.textures++,he=!0),Ie[Se].usedTimes++;const yt=Ie[k.__cacheKey];yt!==void 0&&(Ie[k.__cacheKey].usedTimes--,yt.usedTimes===0&&N(P)),k.__cacheKey=Se,k.__webglTexture=Ie[Se].texture}return he}function tt(k,P,he){return Math.floor(Math.floor(k/he)/P)}function xt(k,P,he,be){const Se=k.updateRanges;if(Se.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,P.width,P.height,he,be,P.data);else{Se.sort((Ue,He)=>Ue.start-He.start);let yt=0;for(let Ue=1;Ue0){j&&ke&&t.texStorage2D(n.TEXTURE_2D,We,J,Le[0].width,Le[0].height);for(let Ge=0,Re=Le.length;Ge0){const at=Y3(me.width,me.height,P.format,P.type);for(const Et of P.layerUpdates){const Gt=me.data.subarray(Et*at/me.data.BYTES_PER_ELEMENT,(Et+1)*at/me.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ge,0,0,Et,me.width,me.height,1,He,Gt)}P.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ge,0,0,0,me.width,me.height,Ue.depth,He,me.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,Ge,J,me.width,me.height,Ue.depth,0,me.data,0,0);else dt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else j?ge&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,Ge,0,0,0,me.width,me.height,Ue.depth,He,pt,me.data):t.texImage3D(n.TEXTURE_2D_ARRAY,Ge,J,me.width,me.height,Ue.depth,0,He,pt,me.data)}else{j&&ke&&t.texStorage2D(n.TEXTURE_2D,We,J,Le[0].width,Le[0].height);for(let Ge=0,Re=Le.length;Ge0){const Ge=Y3(Ue.width,Ue.height,P.format,P.type);for(const Re of P.layerUpdates){const at=Ue.data.subarray(Re*Ge/Ue.data.BYTES_PER_ELEMENT,(Re+1)*Ge/Ue.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,Re,Ue.width,Ue.height,1,He,pt,at)}P.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,Ue.width,Ue.height,Ue.depth,He,pt,Ue.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,J,Ue.width,Ue.height,Ue.depth,0,He,pt,Ue.data);else if(P.isData3DTexture)j?(ke&&t.texStorage3D(n.TEXTURE_3D,We,J,Ue.width,Ue.height,Ue.depth),ge&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,Ue.width,Ue.height,Ue.depth,He,pt,Ue.data)):t.texImage3D(n.TEXTURE_3D,0,J,Ue.width,Ue.height,Ue.depth,0,He,pt,Ue.data);else if(P.isFramebufferTexture){if(ke)if(j)t.texStorage2D(n.TEXTURE_2D,We,J,Ue.width,Ue.height);else{let Ge=Ue.width,Re=Ue.height;for(let at=0;at>=1,Re>>=1}}else if(Le.length>0){if(j&&ke){const Ge=ht(Le[0]);t.texStorage2D(n.TEXTURE_2D,We,J,Ge.width,Ge.height)}for(let Ge=0,Re=Le.length;Ge0&&We++;const Re=ht(He[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,We,Le,Re.width,Re.height)}for(let Re=0;Re<6;Re++)if(Ue){j?ge&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Re,0,0,0,He[Re].width,He[Re].height,J,me,He[Re].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Re,0,Le,He[Re].width,He[Re].height,0,J,me,He[Re].data);for(let at=0;at>Se),pt=Math.max(1,P.height>>Se);Ie===n.TEXTURE_3D||Ie===n.TEXTURE_2D_ARRAY?t.texImage3D(Ie,Se,Tt,He,pt,P.depth,0,yt,je,null):t.texImage2D(Ie,Se,Tt,He,pt,0,yt,je,null)}t.bindFramebuffer(n.FRAMEBUFFER,k),Fe(P)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,be,Ie,Ue.__webglTexture,0,Ve(P)):(Ie===n.TEXTURE_2D||Ie>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&Ie<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,be,Ie,Ue.__webglTexture,Se),t.bindFramebuffer(n.FRAMEBUFFER,null)}function de(k,P,he){if(n.bindRenderbuffer(n.RENDERBUFFER,k),P.depthBuffer){const be=P.depthTexture,Ie=be&&be.isDepthTexture?be.type:null,Se=b(P.stencilBuffer,Ie),yt=P.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,je=Ve(P);Fe(P)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,je,Se,P.width,P.height):he?n.renderbufferStorageMultisample(n.RENDERBUFFER,je,Se,P.width,P.height):n.renderbufferStorage(n.RENDERBUFFER,Se,P.width,P.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,yt,n.RENDERBUFFER,k)}else{const be=P.textures;for(let Ie=0;Ie{delete P.__boundDepthTexture,delete P.__depthDisposeCallback,be.removeEventListener("dispose",Ie)};be.addEventListener("dispose",Ie),P.__depthDisposeCallback=Ie}P.__boundDepthTexture=be}if(k.depthTexture&&!P.__autoAllocateDepthBuffer){if(he)throw new Error("target.depthTexture not supported in Cube render targets");const be=k.texture.mipmaps;be&&be.length>0?it(P.__webglFramebuffer[0],k):it(P.__webglFramebuffer,k)}else if(he){P.__webglDepthbuffer=[];for(let be=0;be<6;be++)if(t.bindFramebuffer(n.FRAMEBUFFER,P.__webglFramebuffer[be]),P.__webglDepthbuffer[be]===void 0)P.__webglDepthbuffer[be]=n.createRenderbuffer(),de(P.__webglDepthbuffer[be],k,!1);else{const Ie=k.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Se=P.__webglDepthbuffer[be];n.bindRenderbuffer(n.RENDERBUFFER,Se),n.framebufferRenderbuffer(n.FRAMEBUFFER,Ie,n.RENDERBUFFER,Se)}}else{const be=k.texture.mipmaps;if(be&&be.length>0?t.bindFramebuffer(n.FRAMEBUFFER,P.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,P.__webglFramebuffer),P.__webglDepthbuffer===void 0)P.__webglDepthbuffer=n.createRenderbuffer(),de(P.__webglDepthbuffer,k,!1);else{const Ie=k.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Se=P.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,Se),n.framebufferRenderbuffer(n.FRAMEBUFFER,Ie,n.RENDERBUFFER,Se)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function ct(k,P,he){const be=i.get(k);P!==void 0&&Ze(be.__webglFramebuffer,k,k.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),he!==void 0&&wt(k)}function Qe(k){const P=k.texture,he=i.get(k),be=i.get(P);k.addEventListener("dispose",L);const Ie=k.textures,Se=k.isWebGLCubeRenderTarget===!0,yt=Ie.length>1;if(yt||(be.__webglTexture===void 0&&(be.__webglTexture=n.createTexture()),be.__version=P.version,s.memory.textures++),Se){he.__webglFramebuffer=[];for(let je=0;je<6;je++)if(P.mipmaps&&P.mipmaps.length>0){he.__webglFramebuffer[je]=[];for(let Tt=0;Tt0){he.__webglFramebuffer=[];for(let je=0;je0&&Fe(k)===!1){he.__webglMultisampledFramebuffer=n.createFramebuffer(),he.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,he.__webglMultisampledFramebuffer);for(let je=0;je0)for(let Tt=0;Tt0)for(let Tt=0;Tt0){if(Fe(k)===!1){const P=k.textures,he=k.width,be=k.height;let Ie=n.COLOR_BUFFER_BIT;const Se=k.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,yt=i.get(k),je=P.length>1;if(je)for(let vt=0;vt0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,yt.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,yt.__webglFramebuffer);for(let vt=0;vt0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&P.__useRenderToTexture!==!1}function $e(k){const P=s.render.frame;d.get(k)!==P&&(d.set(k,P),k.update())}function Je(k,P){const he=k.colorSpace,be=k.format,Ie=k.type;return k.isCompressedTexture===!0||k.isVideoTexture===!0||he!==Xn&&he!==Xr&&(tn.getTransfer(he)===Dn?(be!==ai||Ie!==Ni)&&dt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Ht("WebGLTextures: Unsupported texture color space:",he)),P}function ht(k){return typeof HTMLImageElement<"u"&&k instanceof HTMLImageElement?(u.width=k.naturalWidth||k.width,u.height=k.naturalHeight||k.height):typeof VideoFrame<"u"&&k instanceof VideoFrame?(u.width=k.displayWidth,u.height=k.displayHeight):(u.width=k.width,u.height=k.height),u}this.allocateTextureUnit=K,this.resetTextureUnits=W,this.setTexture2D=ae,this.setTexture2DArray=X,this.setTexture3D=te,this.setTextureCube=Q,this.rebindTextures=ct,this.setupRenderTarget=Qe,this.updateRenderTargetMipmap=Ee,this.updateMultisampleRenderTarget=Oe,this.setupDepthRenderbuffer=wt,this.setupFrameBufferTexture=Ze,this.useMultisampledRTT=Fe}function I7(n,e){function t(i,r=Xr){let a;const s=tn.getTransfer(r);if(i===Ni)return n.UNSIGNED_BYTE;if(i===NS)return n.UNSIGNED_SHORT_4_4_4_4;if(i===OS)return n.UNSIGNED_SHORT_5_5_5_1;if(i===Zw)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===Qw)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===CS)return n.BYTE;if(i===DS)return n.SHORT;if(i===Uh)return n.UNSIGNED_SHORT;if(i===$g)return n.INT;if(i===to)return n.UNSIGNED_INT;if(i===fi)return n.FLOAT;if(i===Jn)return n.HALF_FLOAT;if(i===Kw)return n.ALPHA;if(i===Jw)return n.RGB;if(i===ai)return n.RGBA;if(i===yp)return n.DEPTH_COMPONENT;if(i===zh)return n.DEPTH_STENCIL;if(i===Qs)return n.RED;if(i===ev)return n.RED_INTEGER;if(i===Mo)return n.RG;if(i===LS)return n.RG_INTEGER;if(i===IS)return n.RGBA_INTEGER;if(i===Q0||i===K0||i===J0||i===$0)if(s===Dn)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(i===Q0)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===K0)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===J0)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===$0)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(i===Q0)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===K0)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===J0)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===$0)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===ty||i===ny||i===iy||i===ry)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===ty)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===ny)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===iy)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===ry)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===ay||i===sy||i===oy)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(i===ay||i===sy)return s===Dn?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===oy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===ly||i===cy||i===uy||i===hy||i===dy||i===fy||i===py||i===my||i===gy||i===vy||i===_y||i===xy||i===yy||i===Sy)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(i===ly)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===cy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===uy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===hy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===dy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===fy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===py)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===my)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===gy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===vy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===_y)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===xy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===yy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===Sy)return s===Dn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Ty||i===Ey||i===by)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(i===Ty)return s===Dn?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===Ey)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===by)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===My||i===Ay||i===wy||i===Ry)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(i===My)return a.COMPRESSED_RED_RGTC1_EXT;if(i===Ay)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===wy)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Ry)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===Ph?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const IJ=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,UJ=` +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 PJ{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new uR(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new Oi({vertexShader:IJ,fragmentShader:UJ,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new jn(new uu(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class zJ extends Mi{constructor(e,t){super();const i=this;let r=null,a=1,s=null,o="local-floor",l=1,u=null,d=null,f=null,p=null,m=null,v=null;const x=typeof XRWebGLBinding<"u",S=new PJ,_={},T=t.getContextAttributes();let E=null,b=null;const R=[],w=[],L=new re;let U=null;const N=new si;N.viewport=new Pt;const C=new si;C.viewport=new Pt;const z=[N,C],W=new y7;let K=null,oe=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ve){let we=R[ve];return we===void 0&&(we=new c1,R[ve]=we),we.getTargetRaySpace()},this.getControllerGrip=function(ve){let we=R[ve];return we===void 0&&(we=new c1,R[ve]=we),we.getGripSpace()},this.getHand=function(ve){let we=R[ve];return we===void 0&&(we=new c1,R[ve]=we),we.getHandSpace()};function ae(ve){const we=w.indexOf(ve.inputSource);if(we===-1)return;const Ze=R[we];Ze!==void 0&&(Ze.update(ve.inputSource,ve.frame,u||s),Ze.dispatchEvent({type:ve.type,data:ve.inputSource}))}function X(){r.removeEventListener("select",ae),r.removeEventListener("selectstart",ae),r.removeEventListener("selectend",ae),r.removeEventListener("squeeze",ae),r.removeEventListener("squeezestart",ae),r.removeEventListener("squeezeend",ae),r.removeEventListener("end",X),r.removeEventListener("inputsourceschange",te);for(let ve=0;ve=0&&(w[de]=null,R[de].disconnect(Ze))}for(let we=0;we=w.length){w.push(Ze),de=wt;break}else if(w[wt]===null){w[wt]=Ze,de=wt;break}if(de===-1)break}const it=R[de];it&&it.connect(Ze)}}const Q=new D,ce=new D;function se(ve,we,Ze){Q.setFromMatrixPosition(we.matrixWorld),ce.setFromMatrixPosition(Ze.matrixWorld);const de=Q.distanceTo(ce),it=we.projectionMatrix.elements,wt=Ze.projectionMatrix.elements,ct=it[14]/(it[10]-1),Qe=it[14]/(it[10]+1),Ee=(it[9]+1)/it[5],V=(it[9]-1)/it[5],Ae=(it[8]-1)/it[0],Oe=(wt[8]+1)/wt[0],Ve=ct*Ae,Fe=ct*Oe,$e=de/(-Ae+Oe),Je=$e*-Ae;if(we.matrixWorld.decompose(ve.position,ve.quaternion,ve.scale),ve.translateX(Je),ve.translateZ($e),ve.matrixWorld.compose(ve.position,ve.quaternion,ve.scale),ve.matrixWorldInverse.copy(ve.matrixWorld).invert(),it[10]===-1)ve.projectionMatrix.copy(we.projectionMatrix),ve.projectionMatrixInverse.copy(we.projectionMatrixInverse);else{const ht=ct+$e,k=Qe+$e,P=Ve-Je,he=Fe+(de-Je),be=Ee*Qe/k*ht,Ie=V*Qe/k*ht;ve.projectionMatrix.makePerspective(P,he,be,Ie,ht,k),ve.projectionMatrixInverse.copy(ve.projectionMatrix).invert()}}function De(ve,we){we===null?ve.matrixWorld.copy(ve.matrix):ve.matrixWorld.multiplyMatrices(we.matrixWorld,ve.matrix),ve.matrixWorldInverse.copy(ve.matrixWorld).invert()}this.updateCamera=function(ve){if(r===null)return;let we=ve.near,Ze=ve.far;S.texture!==null&&(S.depthNear>0&&(we=S.depthNear),S.depthFar>0&&(Ze=S.depthFar)),W.near=C.near=N.near=we,W.far=C.far=N.far=Ze,(K!==W.near||oe!==W.far)&&(r.updateRenderState({depthNear:W.near,depthFar:W.far}),K=W.near,oe=W.far),W.layers.mask=ve.layers.mask|6,N.layers.mask=W.layers.mask&3,C.layers.mask=W.layers.mask&5;const de=ve.parent,it=W.cameras;De(W,de);for(let wt=0;wt0&&(S.alphaTest.value=_.alphaTest);const T=e.get(_),E=T.envMap,b=T.envMapRotation;E&&(S.envMap.value=E,Wu.copy(b),Wu.x*=-1,Wu.y*=-1,Wu.z*=-1,E.isCubeTexture&&E.isRenderTargetTexture===!1&&(Wu.y*=-1,Wu.z*=-1),S.envMapRotation.value.setFromMatrix4(BJ.makeRotationFromEuler(Wu)),S.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,S.reflectivity.value=_.reflectivity,S.ior.value=_.ior,S.refractionRatio.value=_.refractionRatio),_.lightMap&&(S.lightMap.value=_.lightMap,S.lightMapIntensity.value=_.lightMapIntensity,t(_.lightMap,S.lightMapTransform)),_.aoMap&&(S.aoMap.value=_.aoMap,S.aoMapIntensity.value=_.aoMapIntensity,t(_.aoMap,S.aoMapTransform))}function s(S,_){S.diffuse.value.copy(_.color),S.opacity.value=_.opacity,_.map&&(S.map.value=_.map,t(_.map,S.mapTransform))}function o(S,_){S.dashSize.value=_.dashSize,S.totalSize.value=_.dashSize+_.gapSize,S.scale.value=_.scale}function l(S,_,T,E){S.diffuse.value.copy(_.color),S.opacity.value=_.opacity,S.size.value=_.size*T,S.scale.value=E*.5,_.map&&(S.map.value=_.map,t(_.map,S.uvTransform)),_.alphaMap&&(S.alphaMap.value=_.alphaMap,t(_.alphaMap,S.alphaMapTransform)),_.alphaTest>0&&(S.alphaTest.value=_.alphaTest)}function u(S,_){S.diffuse.value.copy(_.color),S.opacity.value=_.opacity,S.rotation.value=_.rotation,_.map&&(S.map.value=_.map,t(_.map,S.mapTransform)),_.alphaMap&&(S.alphaMap.value=_.alphaMap,t(_.alphaMap,S.alphaMapTransform)),_.alphaTest>0&&(S.alphaTest.value=_.alphaTest)}function d(S,_){S.specular.value.copy(_.specular),S.shininess.value=Math.max(_.shininess,1e-4)}function f(S,_){_.gradientMap&&(S.gradientMap.value=_.gradientMap)}function p(S,_){S.metalness.value=_.metalness,_.metalnessMap&&(S.metalnessMap.value=_.metalnessMap,t(_.metalnessMap,S.metalnessMapTransform)),S.roughness.value=_.roughness,_.roughnessMap&&(S.roughnessMap.value=_.roughnessMap,t(_.roughnessMap,S.roughnessMapTransform)),_.envMap&&(S.envMapIntensity.value=_.envMapIntensity)}function m(S,_,T){S.ior.value=_.ior,_.sheen>0&&(S.sheenColor.value.copy(_.sheenColor).multiplyScalar(_.sheen),S.sheenRoughness.value=_.sheenRoughness,_.sheenColorMap&&(S.sheenColorMap.value=_.sheenColorMap,t(_.sheenColorMap,S.sheenColorMapTransform)),_.sheenRoughnessMap&&(S.sheenRoughnessMap.value=_.sheenRoughnessMap,t(_.sheenRoughnessMap,S.sheenRoughnessMapTransform))),_.clearcoat>0&&(S.clearcoat.value=_.clearcoat,S.clearcoatRoughness.value=_.clearcoatRoughness,_.clearcoatMap&&(S.clearcoatMap.value=_.clearcoatMap,t(_.clearcoatMap,S.clearcoatMapTransform)),_.clearcoatRoughnessMap&&(S.clearcoatRoughnessMap.value=_.clearcoatRoughnessMap,t(_.clearcoatRoughnessMap,S.clearcoatRoughnessMapTransform)),_.clearcoatNormalMap&&(S.clearcoatNormalMap.value=_.clearcoatNormalMap,t(_.clearcoatNormalMap,S.clearcoatNormalMapTransform),S.clearcoatNormalScale.value.copy(_.clearcoatNormalScale),_.side===ki&&S.clearcoatNormalScale.value.negate())),_.dispersion>0&&(S.dispersion.value=_.dispersion),_.iridescence>0&&(S.iridescence.value=_.iridescence,S.iridescenceIOR.value=_.iridescenceIOR,S.iridescenceThicknessMinimum.value=_.iridescenceThicknessRange[0],S.iridescenceThicknessMaximum.value=_.iridescenceThicknessRange[1],_.iridescenceMap&&(S.iridescenceMap.value=_.iridescenceMap,t(_.iridescenceMap,S.iridescenceMapTransform)),_.iridescenceThicknessMap&&(S.iridescenceThicknessMap.value=_.iridescenceThicknessMap,t(_.iridescenceThicknessMap,S.iridescenceThicknessMapTransform))),_.transmission>0&&(S.transmission.value=_.transmission,S.transmissionSamplerMap.value=T.texture,S.transmissionSamplerSize.value.set(T.width,T.height),_.transmissionMap&&(S.transmissionMap.value=_.transmissionMap,t(_.transmissionMap,S.transmissionMapTransform)),S.thickness.value=_.thickness,_.thicknessMap&&(S.thicknessMap.value=_.thicknessMap,t(_.thicknessMap,S.thicknessMapTransform)),S.attenuationDistance.value=_.attenuationDistance,S.attenuationColor.value.copy(_.attenuationColor)),_.anisotropy>0&&(S.anisotropyVector.value.set(_.anisotropy*Math.cos(_.anisotropyRotation),_.anisotropy*Math.sin(_.anisotropyRotation)),_.anisotropyMap&&(S.anisotropyMap.value=_.anisotropyMap,t(_.anisotropyMap,S.anisotropyMapTransform))),S.specularIntensity.value=_.specularIntensity,S.specularColor.value.copy(_.specularColor),_.specularColorMap&&(S.specularColorMap.value=_.specularColorMap,t(_.specularColorMap,S.specularColorMapTransform)),_.specularIntensityMap&&(S.specularIntensityMap.value=_.specularIntensityMap,t(_.specularIntensityMap,S.specularIntensityMapTransform))}function v(S,_){_.matcap&&(S.matcap.value=_.matcap)}function x(S,_){const T=e.get(_).light;S.referencePosition.value.setFromMatrixPosition(T.matrixWorld),S.nearDistance.value=T.shadow.camera.near,S.farDistance.value=T.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:r}}function HJ(n,e,t,i){let r={},a={},s=[];const o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(T,E){const b=E.program;i.uniformBlockBinding(T,b)}function u(T,E){let b=r[T.id];b===void 0&&(v(T),b=d(T),r[T.id]=b,T.addEventListener("dispose",S));const R=E.program;i.updateUBOMapping(T,R);const w=e.render.frame;a[T.id]!==w&&(p(T),a[T.id]=w)}function d(T){const E=f();T.__bindingPointIndex=E;const b=n.createBuffer(),R=T.__size,w=T.usage;return n.bindBuffer(n.UNIFORM_BUFFER,b),n.bufferData(n.UNIFORM_BUFFER,R,w),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,E,b),b}function f(){for(let T=0;T0&&(b+=R-w),T.__size=b,T.__cache={},this}function x(T){const E={boundary:0,storage:0};return typeof T=="number"||typeof T=="boolean"?(E.boundary=4,E.storage=4):T.isVector2?(E.boundary=8,E.storage=8):T.isVector3||T.isColor?(E.boundary=16,E.storage=12):T.isVector4?(E.boundary=16,E.storage=16):T.isMatrix3?(E.boundary=48,E.storage=48):T.isMatrix4?(E.boundary=64,E.storage=64):T.isTexture?dt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):dt("WebGLRenderer: Unsupported uniform value type.",T),E}function S(T){const E=T.target;E.removeEventListener("dispose",S);const b=s.indexOf(E.__bindingPointIndex);s.splice(b,1),n.deleteBuffer(r[E.id]),delete r[E.id],delete a[E.id]}function _(){for(const T in r)n.deleteBuffer(r[T]);s=[],r={},a={}}return{bind:l,update:u,dispose:_}}const VJ=new Uint16Array([11481,15204,11534,15171,11808,15015,12385,14843,12894,14716,13396,14600,13693,14483,13976,14366,14237,14171,14405,13961,14511,13770,14605,13598,14687,13444,14760,13305,14822,13066,14876,12857,14923,12675,14963,12517,14997,12379,15025,12230,15049,12023,15070,11843,15086,11687,15100,11551,15111,11433,15120,11330,15127,11217,15132,11060,15135,10922,15138,10801,15139,10695,15139,10600,13012,14923,13020,14917,13064,14886,13176,14800,13349,14666,13513,14526,13724,14398,13960,14230,14200,14020,14383,13827,14488,13651,14583,13491,14667,13348,14740,13132,14803,12908,14856,12713,14901,12542,14938,12394,14968,12241,14992,12017,15010,11822,15024,11654,15034,11507,15041,11380,15044,11269,15044,11081,15042,10913,15037,10764,15031,10635,15023,10520,15014,10419,15003,10330,13657,14676,13658,14673,13670,14660,13698,14622,13750,14547,13834,14442,13956,14317,14112,14093,14291,13889,14407,13704,14499,13538,14586,13389,14664,13201,14733,12966,14792,12758,14842,12577,14882,12418,14915,12272,14940,12033,14959,11826,14972,11646,14980,11490,14983,11355,14983,11212,14979,11008,14971,10830,14961,10675,14950,10540,14936,10420,14923,10315,14909,10204,14894,10041,14089,14460,14090,14459,14096,14452,14112,14431,14141,14388,14186,14305,14252,14130,14341,13941,14399,13756,14467,13585,14539,13430,14610,13272,14677,13026,14737,12808,14790,12617,14833,12449,14869,12303,14896,12065,14916,11845,14929,11655,14937,11490,14939,11347,14936,11184,14930,10970,14921,10783,14912,10621,14900,10480,14885,10356,14867,10247,14848,10062,14827,9894,14805,9745,14400,14208,14400,14206,14402,14198,14406,14174,14415,14122,14427,14035,14444,13913,14469,13767,14504,13613,14548,13463,14598,13324,14651,13082,14704,12858,14752,12658,14795,12483,14831,12330,14860,12106,14881,11875,14895,11675,14903,11501,14905,11351,14903,11178,14900,10953,14892,10757,14880,10589,14865,10442,14847,10313,14827,10162,14805,9965,14782,9792,14757,9642,14731,9507,14562,13883,14562,13883,14563,13877,14566,13862,14570,13830,14576,13773,14584,13689,14595,13582,14613,13461,14637,13336,14668,13120,14704,12897,14741,12695,14776,12516,14808,12358,14835,12150,14856,11910,14870,11701,14878,11519,14882,11361,14884,11187,14880,10951,14871,10748,14858,10572,14842,10418,14823,10286,14801,10099,14777,9897,14751,9722,14725,9567,14696,9430,14666,9309,14702,13604,14702,13604,14702,13600,14703,13591,14705,13570,14707,13533,14709,13477,14712,13400,14718,13305,14727,13106,14743,12907,14762,12716,14784,12539,14807,12380,14827,12190,14844,11943,14855,11727,14863,11539,14870,11376,14871,11204,14868,10960,14858,10748,14845,10565,14829,10406,14809,10269,14786,10058,14761,9852,14734,9671,14705,9512,14674,9374,14641,9253,14608,9076,14821,13366,14821,13365,14821,13364,14821,13358,14821,13344,14821,13320,14819,13252,14817,13145,14815,13011,14814,12858,14817,12698,14823,12539,14832,12389,14841,12214,14850,11968,14856,11750,14861,11558,14866,11390,14867,11226,14862,10972,14853,10754,14840,10565,14823,10401,14803,10259,14780,10032,14754,9820,14725,9635,14694,9473,14661,9333,14627,9203,14593,8988,14557,8798,14923,13014,14922,13014,14922,13012,14922,13004,14920,12987,14919,12957,14915,12907,14909,12834,14902,12738,14894,12623,14888,12498,14883,12370,14880,12203,14878,11970,14875,11759,14873,11569,14874,11401,14872,11243,14865,10986,14855,10762,14842,10568,14825,10401,14804,10255,14781,10017,14754,9799,14725,9611,14692,9445,14658,9301,14623,9139,14587,8920,14548,8729,14509,8562,15008,12672,15008,12672,15008,12671,15007,12667,15005,12656,15001,12637,14997,12605,14989,12556,14978,12490,14966,12407,14953,12313,14940,12136,14927,11934,14914,11742,14903,11563,14896,11401,14889,11247,14879,10992,14866,10767,14851,10570,14833,10400,14812,10252,14789,10007,14761,9784,14731,9592,14698,9424,14663,9279,14627,9088,14588,8868,14548,8676,14508,8508,14467,8360,15080,12386,15080,12386,15079,12385,15078,12383,15076,12378,15072,12367,15066,12347,15057,12315,15045,12253,15030,12138,15012,11998,14993,11845,14972,11685,14951,11530,14935,11383,14920,11228,14904,10981,14887,10762,14870,10567,14850,10397,14827,10248,14803,9997,14774,9771,14743,9578,14710,9407,14674,9259,14637,9048,14596,8826,14555,8632,14514,8464,14471,8317,14427,8182,15139,12008,15139,12008,15138,12008,15137,12007,15135,12003,15130,11990,15124,11969,15115,11929,15102,11872,15086,11794,15064,11693,15041,11581,15013,11459,14987,11336,14966,11170,14944,10944,14921,10738,14898,10552,14875,10387,14850,10239,14824,9983,14794,9758,14762,9563,14728,9392,14692,9244,14653,9014,14611,8791,14569,8597,14526,8427,14481,8281,14436,8110,14391,7885,15188,11617,15188,11617,15187,11617,15186,11618,15183,11617,15179,11612,15173,11601,15163,11581,15150,11546,15133,11495,15110,11427,15083,11346,15051,11246,15024,11057,14996,10868,14967,10687,14938,10517,14911,10362,14882,10206,14853,9956,14821,9737,14787,9543,14752,9375,14715,9228,14675,8980,14632,8760,14589,8565,14544,8395,14498,8248,14451,8049,14404,7824,14357,7630,15228,11298,15228,11298,15227,11299,15226,11301,15223,11303,15219,11302,15213,11299,15204,11290,15191,11271,15174,11217,15150,11129,15119,11015,15087,10886,15057,10744,15024,10599,14990,10455,14957,10318,14924,10143,14891,9911,14856,9701,14820,9516,14782,9352,14744,9200,14703,8946,14659,8725,14615,8533,14568,8366,14521,8220,14472,7992,14423,7770,14374,7578,14315,7408,15260,10819,15260,10819,15259,10822,15258,10826,15256,10832,15251,10836,15246,10841,15237,10838,15225,10821,15207,10788,15183,10734,15151,10660,15120,10571,15087,10469,15049,10359,15012,10249,14974,10041,14937,9837,14900,9647,14860,9475,14820,9320,14779,9147,14736,8902,14691,8688,14646,8499,14598,8335,14549,8189,14499,7940,14448,7720,14397,7529,14347,7363,14256,7218,15285,10410,15285,10411,15285,10413,15284,10418,15282,10425,15278,10434,15272,10442,15264,10449,15252,10445,15235,10433,15210,10403,15179,10358,15149,10301,15113,10218,15073,10059,15033,9894,14991,9726,14951,9565,14909,9413,14865,9273,14822,9073,14777,8845,14730,8641,14682,8459,14633,8300,14583,8129,14531,7883,14479,7670,14426,7482,14373,7321,14305,7176,14201,6939,15305,9939,15305,9940,15305,9945,15304,9955,15302,9967,15298,9989,15293,10010,15286,10033,15274,10044,15258,10045,15233,10022,15205,9975,15174,9903,15136,9808,15095,9697,15053,9578,15009,9451,14965,9327,14918,9198,14871,8973,14825,8766,14775,8579,14725,8408,14675,8259,14622,8058,14569,7821,14515,7615,14460,7435,14405,7276,14350,7108,14256,6866,14149,6653,15321,9444,15321,9445,15321,9448,15320,9458,15317,9470,15314,9490,15310,9515,15302,9540,15292,9562,15276,9579,15251,9577,15226,9559,15195,9519,15156,9463,15116,9389,15071,9304,15025,9208,14978,9023,14927,8838,14878,8661,14827,8496,14774,8344,14722,8206,14667,7973,14612,7749,14556,7555,14499,7382,14443,7229,14385,7025,14322,6791,14210,6588,14100,6409,15333,8920,15333,8921,15332,8927,15332,8943,15329,8965,15326,9002,15322,9048,15316,9106,15307,9162,15291,9204,15267,9221,15244,9221,15212,9196,15175,9134,15133,9043,15088,8930,15040,8801,14990,8665,14938,8526,14886,8391,14830,8261,14775,8087,14719,7866,14661,7664,14603,7482,14544,7322,14485,7178,14426,6936,14367,6713,14281,6517,14166,6348,14054,6198,15341,8360,15341,8361,15341,8366,15341,8379,15339,8399,15336,8431,15332,8473,15326,8527,15318,8585,15302,8632,15281,8670,15258,8690,15227,8690,15191,8664,15149,8612,15104,8543,15055,8456,15001,8360,14948,8259,14892,8122,14834,7923,14776,7734,14716,7558,14656,7397,14595,7250,14534,7070,14472,6835,14410,6628,14350,6443,14243,6283,14125,6135,14010,5889,15348,7715,15348,7717,15348,7725,15347,7745,15345,7780,15343,7836,15339,7905,15334,8e3,15326,8103,15310,8193,15293,8239,15270,8270,15240,8287,15204,8283,15163,8260,15118,8223,15067,8143,15014,8014,14958,7873,14899,7723,14839,7573,14778,7430,14715,7293,14652,7164,14588,6931,14524,6720,14460,6531,14396,6362,14330,6210,14207,6015,14086,5781,13969,5576,15352,7114,15352,7116,15352,7128,15352,7159,15350,7195,15348,7237,15345,7299,15340,7374,15332,7457,15317,7544,15301,7633,15280,7703,15251,7754,15216,7775,15176,7767,15131,7733,15079,7670,15026,7588,14967,7492,14906,7387,14844,7278,14779,7171,14714,6965,14648,6770,14581,6587,14515,6420,14448,6269,14382,6123,14299,5881,14172,5665,14049,5477,13929,5310,15355,6329,15355,6330,15355,6339,15355,6362,15353,6410,15351,6472,15349,6572,15344,6688,15337,6835,15323,6985,15309,7142,15287,7220,15260,7277,15226,7310,15188,7326,15142,7318,15090,7285,15036,7239,14976,7177,14914,7045,14849,6892,14782,6736,14714,6581,14645,6433,14576,6293,14506,6164,14438,5946,14369,5733,14270,5540,14140,5369,14014,5216,13892,5043,15357,5483,15357,5484,15357,5496,15357,5528,15356,5597,15354,5692,15351,5835,15347,6011,15339,6195,15328,6317,15314,6446,15293,6566,15268,6668,15235,6746,15197,6796,15152,6811,15101,6790,15046,6748,14985,6673,14921,6583,14854,6479,14785,6371,14714,6259,14643,6149,14571,5946,14499,5750,14428,5567,14358,5401,14242,5250,14109,5111,13980,4870,13856,4657,15359,4555,15359,4557,15358,4573,15358,4633,15357,4715,15355,4841,15353,5061,15349,5216,15342,5391,15331,5577,15318,5770,15299,5967,15274,6150,15243,6223,15206,6280,15161,6310,15111,6317,15055,6300,14994,6262,14928,6208,14860,6141,14788,5994,14715,5838,14641,5684,14566,5529,14492,5384,14418,5247,14346,5121,14216,4892,14079,4682,13948,4496,13822,4330,15359,3498,15359,3501,15359,3520,15359,3598,15358,3719,15356,3860,15355,4137,15351,4305,15344,4563,15334,4809,15321,5116,15303,5273,15280,5418,15250,5547,15214,5653,15170,5722,15120,5761,15064,5763,15002,5733,14935,5673,14865,5597,14792,5504,14716,5400,14640,5294,14563,5185,14486,5041,14410,4841,14335,4655,14191,4482,14051,4325,13918,4183,13790,4012,15360,2282,15360,2285,15360,2306,15360,2401,15359,2547,15357,2748,15355,3103,15352,3349,15345,3675,15336,4020,15324,4272,15307,4496,15285,4716,15255,4908,15220,5086,15178,5170,15128,5214,15072,5234,15010,5231,14943,5206,14871,5166,14796,5102,14718,4971,14639,4833,14559,4687,14480,4541,14402,4401,14315,4268,14167,4142,14025,3958,13888,3747,13759,3556,15360,923,15360,925,15360,946,15360,1052,15359,1214,15357,1494,15356,1892,15352,2274,15346,2663,15338,3099,15326,3393,15309,3679,15288,3980,15260,4183,15226,4325,15185,4437,15136,4517,15080,4570,15018,4591,14950,4581,14877,4545,14800,4485,14720,4411,14638,4325,14556,4231,14475,4136,14395,3988,14297,3803,14145,3628,13999,3465,13861,3314,13729,3177,15360,263,15360,264,15360,272,15360,325,15359,407,15358,548,15356,780,15352,1144,15347,1580,15339,2099,15328,2425,15312,2795,15292,3133,15264,3329,15232,3517,15191,3689,15143,3819,15088,3923,15025,3978,14956,3999,14882,3979,14804,3931,14722,3855,14639,3756,14554,3645,14470,3529,14388,3409,14279,3289,14124,3173,13975,3055,13834,2848,13701,2658,15360,49,15360,49,15360,52,15360,75,15359,111,15358,201,15356,283,15353,519,15348,726,15340,1045,15329,1415,15314,1795,15295,2173,15269,2410,15237,2649,15197,2866,15150,3054,15095,3140,15032,3196,14963,3228,14888,3236,14808,3224,14725,3191,14639,3146,14553,3088,14466,2976,14382,2836,14262,2692,14103,2549,13952,2409,13808,2278,13674,2154,15360,4,15360,4,15360,4,15360,13,15359,33,15358,59,15357,112,15353,199,15348,302,15341,456,15331,628,15316,827,15297,1082,15272,1332,15241,1601,15202,1851,15156,2069,15101,2172,15039,2256,14970,2314,14894,2348,14813,2358,14728,2344,14640,2311,14551,2263,14463,2203,14376,2133,14247,2059,14084,1915,13930,1761,13784,1609,13648,1464,15360,0,15360,0,15360,0,15360,3,15359,18,15358,26,15357,53,15354,80,15348,97,15341,165,15332,238,15318,326,15299,427,15275,529,15245,654,15207,771,15161,885,15108,994,15046,1089,14976,1170,14900,1229,14817,1266,14731,1284,14641,1282,14550,1260,14460,1223,14370,1174,14232,1116,14066,1050,13909,981,13761,910,13623,839]);let al=null;function GJ(){return al===null&&(al=new Ur(VJ,32,32,Mo,Jn),al.minFilter=Bt,al.magFilter=Bt,al.wrapS=Wi,al.wrapT=Wi,al.generateMipmaps=!1,al.needsUpdate=!0),al}class uT{constructor(e={}){const{canvas:t=D9(),context:i=null,depth:r=!0,stencil:a=!1,alpha:s=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:u=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:f=!1,reversedDepthBuffer:p=!1}=e;this.isWebGLRenderer=!0;let m;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");m=i.getContextAttributes().alpha}else m=s;const v=new Set([IS,LS,ev]),x=new Set([Ni,to,Uh,Ph,NS,OS]),S=new Uint32Array(4),_=new Int32Array(4);let T=null,E=null;const b=[],R=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=As,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const w=this;let L=!1;this._outputColorSpace=mn;let U=0,N=0,C=null,z=-1,W=null;const K=new Pt,oe=new Pt;let ae=null;const X=new Ye(0);let te=0,Q=t.width,ce=t.height,se=1,De=null,Xe=null;const nt=new Pt(0,0,Q,ce),tt=new Pt(0,0,Q,ce);let xt=!1;const ve=new ed;let we=!1,Ze=!1;const de=new Me,it=new D,wt=new Pt,ct={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Qe=!1;function Ee(){return C===null?se:1}let V=i;function Ae(I,G){return t.getContext(I,G)}try{const I={alpha:!0,depth:r,stencil:a,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:u,powerPreference:d,failIfMajorPerformanceCaveat:f};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${$s}`),t.addEventListener("webglcontextlost",Ge,!1),t.addEventListener("webglcontextrestored",Re,!1),t.addEventListener("webglcontextcreationerror",at,!1),V===null){const G="webgl2";if(V=Ae(G,I),V===null)throw Ae(G)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(I){throw I("WebGLRenderer: "+I.message),I}let Oe,Ve,Fe,$e,Je,ht,k,P,he,be,Ie,Se,yt,je,Tt,vt,Ue,He,pt,J,me,Le,j,ke;function ge(){Oe=new JQ(V),Oe.init(),Le=new I7(V,Oe),Ve=new kQ(V,Oe,e,Le),Fe=new OJ(V,Oe),Ve.reversedDepthBuffer&&p&&Fe.buffers.depth.setReversed(!0),$e=new tK(V),Je=new xJ,ht=new LJ(V,Oe,Fe,Je,Ve,Le,$e),k=new XQ(w),P=new KQ(w),he=new aj(V),j=new VQ(V,he),be=new $Q(V,he,$e,j),Ie=new iK(V,be,he,$e),pt=new nK(V,Ve,ht),vt=new WQ(Je),Se=new _J(w,k,P,Oe,Ve,j,vt),yt=new FJ(w,Je),je=new SJ,Tt=new wJ(Oe),He=new HQ(w,k,P,Fe,Ie,m,l),Ue=new DJ(w,Ie,Ve),ke=new HJ(V,$e,Ve,Fe),J=new GQ(V,Oe,$e),me=new eK(V,Oe,$e),$e.programs=Se.programs,w.capabilities=Ve,w.extensions=Oe,w.properties=Je,w.renderLists=je,w.shadowMap=Ue,w.state=Fe,w.info=$e}ge();const We=new zJ(w,V);this.xr=We,this.getContext=function(){return V},this.getContextAttributes=function(){return V.getContextAttributes()},this.forceContextLoss=function(){const I=Oe.get("WEBGL_lose_context");I&&I.loseContext()},this.forceContextRestore=function(){const I=Oe.get("WEBGL_lose_context");I&&I.restoreContext()},this.getPixelRatio=function(){return se},this.setPixelRatio=function(I){I!==void 0&&(se=I,this.setSize(Q,ce,!1))},this.getSize=function(I){return I.set(Q,ce)},this.setSize=function(I,G,Z=!0){if(We.isPresenting){dt("WebGLRenderer: Can't change size while VR device is presenting.");return}Q=I,ce=G,t.width=Math.floor(I*se),t.height=Math.floor(G*se),Z===!0&&(t.style.width=I+"px",t.style.height=G+"px"),this.setViewport(0,0,I,G)},this.getDrawingBufferSize=function(I){return I.set(Q*se,ce*se).floor()},this.setDrawingBufferSize=function(I,G,Z){Q=I,ce=G,se=Z,t.width=Math.floor(I*Z),t.height=Math.floor(G*Z),this.setViewport(0,0,I,G)},this.getCurrentViewport=function(I){return I.copy(K)},this.getViewport=function(I){return I.copy(nt)},this.setViewport=function(I,G,Z,F){I.isVector4?nt.set(I.x,I.y,I.z,I.w):nt.set(I,G,Z,F),Fe.viewport(K.copy(nt).multiplyScalar(se).round())},this.getScissor=function(I){return I.copy(tt)},this.setScissor=function(I,G,Z,F){I.isVector4?tt.set(I.x,I.y,I.z,I.w):tt.set(I,G,Z,F),Fe.scissor(oe.copy(tt).multiplyScalar(se).round())},this.getScissorTest=function(){return xt},this.setScissorTest=function(I){Fe.setScissorTest(xt=I)},this.setOpaqueSort=function(I){De=I},this.setTransparentSort=function(I){Xe=I},this.getClearColor=function(I){return I.copy(He.getClearColor())},this.setClearColor=function(){He.setClearColor(...arguments)},this.getClearAlpha=function(){return He.getClearAlpha()},this.setClearAlpha=function(){He.setClearAlpha(...arguments)},this.clear=function(I=!0,G=!0,Z=!0){let F=0;if(I){let q=!1;if(C!==null){const ne=C.texture.format;q=v.has(ne)}if(q){const ne=C.texture.type,le=x.has(ne),pe=He.getClearColor(),xe=He.getClearAlpha(),Te=pe.r,Ce=pe.g,ze=pe.b;le?(S[0]=Te,S[1]=Ce,S[2]=ze,S[3]=xe,V.clearBufferuiv(V.COLOR,0,S)):(_[0]=Te,_[1]=Ce,_[2]=ze,_[3]=xe,V.clearBufferiv(V.COLOR,0,_))}else F|=V.COLOR_BUFFER_BIT}G&&(F|=V.DEPTH_BUFFER_BIT),Z&&(F|=V.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),V.clear(F)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Ge,!1),t.removeEventListener("webglcontextrestored",Re,!1),t.removeEventListener("webglcontextcreationerror",at,!1),He.dispose(),je.dispose(),Tt.dispose(),Je.dispose(),k.dispose(),P.dispose(),Ie.dispose(),j.dispose(),ke.dispose(),Se.dispose(),We.dispose(),We.removeEventListener("sessionstart",ro),We.removeEventListener("sessionend",ao),Li.stop()};function Ge(I){I.preventDefault(),Dg("WebGLRenderer: Context Lost."),L=!0}function Re(){Dg("WebGLRenderer: Context Restored."),L=!1;const I=$e.autoReset,G=Ue.enabled,Z=Ue.autoUpdate,F=Ue.needsUpdate,q=Ue.type;ge(),$e.autoReset=I,Ue.enabled=G,Ue.autoUpdate=Z,Ue.needsUpdate=F,Ue.type=q}function at(I){Ht("WebGLRenderer: A WebGL context could not be created. Reason: ",I.statusMessage)}function Et(I){const G=I.target;G.removeEventListener("dispose",Et),Gt(G)}function Gt(I){kt(I),Je.remove(I)}function kt(I){const G=Je.get(I).programs;G!==void 0&&(G.forEach(function(Z){Se.releaseProgram(Z)}),I.isShaderMaterial&&Se.releaseShaderCache(I))}this.renderBufferDirect=function(I,G,Z,F,q,ne){G===null&&(G=ct);const le=q.isMesh&&q.matrixWorld.determinant()<0,pe=zo(I,G,Z,F,q);Fe.setMaterial(F,le);let xe=Z.index,Te=1;if(F.wireframe===!0){if(xe=be.getWireframeAttribute(Z),xe===void 0)return;Te=2}const Ce=Z.drawRange,ze=Z.attributes.position;let Be=Ce.start*Te,qe=(Ce.start+Ce.count)*Te;ne!==null&&(Be=Math.max(Be,ne.start*Te),qe=Math.min(qe,(ne.start+ne.count)*Te)),xe!==null?(Be=Math.max(Be,0),qe=Math.min(qe,xe.count)):ze!=null&&(Be=Math.max(Be,0),qe=Math.min(qe,ze.count));const ut=qe-Be;if(ut<0||ut===1/0)return;j.setup(q,F,pe,Z,xe);let At,Rt=J;if(xe!==null&&(At=he.get(xe),Rt=me,Rt.setIndex(At)),q.isMesh)F.wireframe===!0?(Fe.setLineWidth(F.wireframeLinewidth*Ee()),Rt.setMode(V.LINES)):Rt.setMode(V.TRIANGLES);else if(q.isLine){let mt=F.linewidth;mt===void 0&&(mt=1),Fe.setLineWidth(mt*Ee()),q.isLineSegments?Rt.setMode(V.LINES):q.isLineLoop?Rt.setMode(V.LINE_LOOP):Rt.setMode(V.LINE_STRIP)}else q.isPoints?Rt.setMode(V.POINTS):q.isSprite&&Rt.setMode(V.TRIANGLES);if(q.isBatchedMesh)if(q._multiDrawInstances!==null)bp("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Rt.renderMultiDrawInstances(q._multiDrawStarts,q._multiDrawCounts,q._multiDrawCount,q._multiDrawInstances);else if(Oe.get("WEBGL_multi_draw"))Rt.renderMultiDraw(q._multiDrawStarts,q._multiDrawCounts,q._multiDrawCount);else{const mt=q._multiDrawStarts,Dt=q._multiDrawCounts,st=q._multiDrawCount,Kt=xe?he.get(xe).bytesPerElement:1,Pn=Je.get(F).currentProgram.getUniforms();for(let Yt=0;Yt{function ne(){if(F.forEach(function(le){Je.get(le).currentProgram.isReady()&&F.delete(le)}),F.size===0){q(I);return}setTimeout(ne,10)}Oe.get("KHR_parallel_shader_compile")!==null?ne():setTimeout(ne,10)})};let gi=null;function Po(I){gi&&gi(I)}function ro(){Li.stop()}function ao(){Li.start()}const Li=new C7;Li.setAnimationLoop(Po),typeof self<"u"&&Li.setContext(self),this.setAnimationLoop=function(I){gi=I,We.setAnimationLoop(I),I===null?Li.stop():Li.start()},We.addEventListener("sessionstart",ro),We.addEventListener("sessionend",ao),this.render=function(I,G){if(G!==void 0&&G.isCamera!==!0){Ht("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(L===!0)return;if(I.matrixWorldAutoUpdate===!0&&I.updateMatrixWorld(),G.parent===null&&G.matrixWorldAutoUpdate===!0&&G.updateMatrixWorld(),We.enabled===!0&&We.isPresenting===!0&&(We.cameraAutoUpdate===!0&&We.updateCamera(G),G=We.getCamera()),I.isScene===!0&&I.onBeforeRender(w,I,G,C),E=Tt.get(I,R.length),E.init(G),R.push(E),de.multiplyMatrices(G.projectionMatrix,G.matrixWorldInverse),ve.setFromProjectionMatrix(de,ka,G.reversedDepth),Ze=this.localClippingEnabled,we=vt.init(this.clippingPlanes,Ze),T=je.get(I,b.length),T.init(),b.push(T),We.enabled===!0&&We.isPresenting===!0){const ne=w.xr.getDepthSensingMesh();ne!==null&&so(ne,G,-1/0,w.sortObjects)}so(I,G,0,w.sortObjects),T.finish(),w.sortObjects===!0&&T.sort(De,Xe),Qe=We.enabled===!1||We.isPresenting===!1||We.hasDepthSensing()===!1,Qe&&He.addToRenderList(T,I),this.info.render.frame++,we===!0&&vt.beginShadows();const Z=E.state.shadowsArray;Ue.render(Z,I,G),we===!0&&vt.endShadows(),this.info.autoReset===!0&&this.info.reset();const F=T.opaque,q=T.transmissive;if(E.setupLights(),G.isArrayCamera){const ne=G.cameras;if(q.length>0)for(let le=0,pe=ne.length;le0&&er(F,q,I,G),Qe&&He.render(I),Er(T,I,G);C!==null&&N===0&&(ht.updateMultisampleRenderTarget(C),ht.updateRenderTargetMipmap(C)),I.isScene===!0&&I.onAfterRender(w,I,G),j.resetDefaultState(),z=-1,W=null,R.pop(),R.length>0?(E=R[R.length-1],we===!0&&vt.setGlobalState(w.clippingPlanes,E.state.camera)):E=null,b.pop(),b.length>0?T=b[b.length-1]:T=null};function so(I,G,Z,F){if(I.visible===!1)return;if(I.layers.test(G.layers)){if(I.isGroup)Z=I.renderOrder;else if(I.isLOD)I.autoUpdate===!0&&I.update(G);else if(I.isLight)E.pushLight(I),I.castShadow&&E.pushShadow(I);else if(I.isSprite){if(!I.frustumCulled||ve.intersectsSprite(I)){F&&wt.setFromMatrixPosition(I.matrixWorld).applyMatrix4(de);const le=Ie.update(I),pe=I.material;pe.visible&&T.push(I,le,pe,Z,wt.z,null)}}else if((I.isMesh||I.isLine||I.isPoints)&&(!I.frustumCulled||ve.intersectsObject(I))){const le=Ie.update(I),pe=I.material;if(F&&(I.boundingSphere!==void 0?(I.boundingSphere===null&&I.computeBoundingSphere(),wt.copy(I.boundingSphere.center)):(le.boundingSphere===null&&le.computeBoundingSphere(),wt.copy(le.boundingSphere.center)),wt.applyMatrix4(I.matrixWorld).applyMatrix4(de)),Array.isArray(pe)){const xe=le.groups;for(let Te=0,Ce=xe.length;Te0&&$r(q,G,Z),ne.length>0&&$r(ne,G,Z),le.length>0&&$r(le,G,Z),Fe.buffers.depth.setTest(!0),Fe.buffers.depth.setMask(!0),Fe.buffers.color.setMask(!0),Fe.setPolygonOffset(!1)}function er(I,G,Z,F){if((Z.isScene===!0?Z.overrideMaterial:null)!==null)return;E.state.transmissionRenderTarget[F.id]===void 0&&(E.state.transmissionRenderTarget[F.id]=new pi(1,1,{generateMipmaps:!0,type:Oe.has("EXT_color_buffer_half_float")||Oe.has("EXT_color_buffer_float")?Jn:Ni,minFilter:Ga,samples:4,stencilBuffer:a,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:tn.workingColorSpace}));const ne=E.state.transmissionRenderTarget[F.id],le=F.viewport||K;ne.setSize(le.z*w.transmissionResolutionScale,le.w*w.transmissionResolutionScale);const pe=w.getRenderTarget(),xe=w.getActiveCubeFace(),Te=w.getActiveMipmapLevel();w.setRenderTarget(ne),w.getClearColor(X),te=w.getClearAlpha(),te<1&&w.setClearColor(16777215,.5),w.clear(),Qe&&He.render(Z);const Ce=w.toneMapping;w.toneMapping=As;const ze=F.viewport;if(F.viewport!==void 0&&(F.viewport=void 0),E.setupLightsView(F),we===!0&&vt.setGlobalState(w.clippingPlanes,F),$r(I,Z,F),ht.updateMultisampleRenderTarget(ne),ht.updateRenderTargetMipmap(ne),Oe.has("WEBGL_multisampled_render_to_texture")===!1){let Be=!1;for(let qe=0,ut=G.length;qe0),ze=!!Z.morphAttributes.position,Be=!!Z.morphAttributes.normal,qe=!!Z.morphAttributes.color;let ut=As;F.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(ut=w.toneMapping);const At=Z.morphAttributes.position||Z.morphAttributes.normal||Z.morphAttributes.color,Rt=At!==void 0?At.length:0,mt=Je.get(F),Dt=E.state.lights;if(we===!0&&(Ze===!0||I!==W)){const An=I===W&&F.id===z;vt.setState(F,I,An)}let st=!1;F.version===mt.__version?(mt.needsLights&&mt.lightsStateVersion!==Dt.state.version||mt.outputColorSpace!==pe||q.isBatchedMesh&&mt.batching===!1||!q.isBatchedMesh&&mt.batching===!0||q.isBatchedMesh&&mt.batchingColor===!0&&q.colorTexture===null||q.isBatchedMesh&&mt.batchingColor===!1&&q.colorTexture!==null||q.isInstancedMesh&&mt.instancing===!1||!q.isInstancedMesh&&mt.instancing===!0||q.isSkinnedMesh&&mt.skinning===!1||!q.isSkinnedMesh&&mt.skinning===!0||q.isInstancedMesh&&mt.instancingColor===!0&&q.instanceColor===null||q.isInstancedMesh&&mt.instancingColor===!1&&q.instanceColor!==null||q.isInstancedMesh&&mt.instancingMorph===!0&&q.morphTexture===null||q.isInstancedMesh&&mt.instancingMorph===!1&&q.morphTexture!==null||mt.envMap!==xe||F.fog===!0&&mt.fog!==ne||mt.numClippingPlanes!==void 0&&(mt.numClippingPlanes!==vt.numPlanes||mt.numIntersection!==vt.numIntersection)||mt.vertexAlphas!==Te||mt.vertexTangents!==Ce||mt.morphTargets!==ze||mt.morphNormals!==Be||mt.morphColors!==qe||mt.toneMapping!==ut||mt.morphTargetsCount!==Rt)&&(st=!0):(st=!0,mt.__version=F.version);let Kt=mt.currentProgram;st===!0&&(Kt=Ja(F,G,q));let Pn=!1,Yt=!1,Wt=!1;const Ot=Kt.getUniforms(),Wn=mt.uniforms;if(Fe.useProgram(Kt.program)&&(Pn=!0,Yt=!0,Wt=!0),F.id!==z&&(z=F.id,Yt=!0),Pn||W!==I){Fe.buffers.depth.getReversed()&&I.reversedDepth!==!0&&(I._reversedDepth=!0,I.updateProjectionMatrix()),Ot.setValue(V,"projectionMatrix",I.projectionMatrix),Ot.setValue(V,"viewMatrix",I.matrixWorldInverse);const Zn=Ot.map.cameraPosition;Zn!==void 0&&Zn.setValue(V,it.setFromMatrixPosition(I.matrixWorld)),Ve.logarithmicDepthBuffer&&Ot.setValue(V,"logDepthBufFC",2/(Math.log(I.far+1)/Math.LN2)),(F.isMeshPhongMaterial||F.isMeshToonMaterial||F.isMeshLambertMaterial||F.isMeshBasicMaterial||F.isMeshStandardMaterial||F.isShaderMaterial)&&Ot.setValue(V,"isOrthographic",I.isOrthographicCamera===!0),W!==I&&(W=I,Yt=!0,Wt=!0)}if(q.isSkinnedMesh){Ot.setOptional(V,q,"bindMatrix"),Ot.setOptional(V,q,"bindMatrixInverse");const An=q.skeleton;An&&(An.boneTexture===null&&An.computeBoneTexture(),Ot.setValue(V,"boneTexture",An.boneTexture,ht))}q.isBatchedMesh&&(Ot.setOptional(V,q,"batchingTexture"),Ot.setValue(V,"batchingTexture",q._matricesTexture,ht),Ot.setOptional(V,q,"batchingIdTexture"),Ot.setValue(V,"batchingIdTexture",q._indirectTexture,ht),Ot.setOptional(V,q,"batchingColorTexture"),q._colorsTexture!==null&&Ot.setValue(V,"batchingColorTexture",q._colorsTexture,ht));const Ii=Z.morphAttributes;if((Ii.position!==void 0||Ii.normal!==void 0||Ii.color!==void 0)&&pt.update(q,Z,Kt),(Yt||mt.receiveShadow!==q.receiveShadow)&&(mt.receiveShadow=q.receiveShadow,Ot.setValue(V,"receiveShadow",q.receiveShadow)),F.isMeshGouraudMaterial&&F.envMap!==null&&(Wn.envMap.value=xe,Wn.flipEnvMap.value=xe.isCubeTexture&&xe.isRenderTargetTexture===!1?-1:1),F.isMeshStandardMaterial&&F.envMap===null&&G.environment!==null&&(Wn.envMapIntensity.value=G.environmentIntensity),Wn.dfgLUT!==void 0&&(Wn.dfgLUT.value=GJ()),Yt&&(Ot.setValue(V,"toneMappingExposure",w.toneMappingExposure),mt.needsLights&&Sa(Wn,Wt),ne&&F.fog===!0&&yt.refreshFogUniforms(Wn,ne),yt.refreshMaterialUniforms(Wn,F,se,ce,E.state.transmissionRenderTarget[I.id]),u1.upload(V,oo(mt),Wn,ht)),F.isShaderMaterial&&F.uniformsNeedUpdate===!0&&(u1.upload(V,oo(mt),Wn,ht),F.uniformsNeedUpdate=!1),F.isSpriteMaterial&&Ot.setValue(V,"center",q.center),Ot.setValue(V,"modelViewMatrix",q.modelViewMatrix),Ot.setValue(V,"normalMatrix",q.normalMatrix),Ot.setValue(V,"modelMatrix",q.matrixWorld),F.isShaderMaterial||F.isRawShaderMaterial){const An=F.uniformsGroups;for(let Zn=0,cd=An.length;Zn0&&ht.useMultisampledRTT(I)===!1?q=Je.get(I).__webglMultisampledFramebuffer:Array.isArray(Ce)?q=Ce[Z]:q=Ce,K.copy(I.viewport),oe.copy(I.scissor),ae=I.scissorTest}else K.copy(nt).multiplyScalar(se).floor(),oe.copy(tt).multiplyScalar(se).floor(),ae=xt;if(Z!==0&&(q=O),Fe.bindFramebuffer(V.FRAMEBUFFER,q)&&F&&Fe.drawBuffers(I,q),Fe.viewport(K),Fe.scissor(oe),Fe.setScissorTest(ae),ne){const xe=Je.get(I.texture);V.framebufferTexture2D(V.FRAMEBUFFER,V.COLOR_ATTACHMENT0,V.TEXTURE_CUBE_MAP_POSITIVE_X+G,xe.__webglTexture,Z)}else if(le){const xe=G;for(let Te=0;Te=0&&G<=I.width-F&&Z>=0&&Z<=I.height-q&&(I.textures.length>1&&V.readBuffer(V.COLOR_ATTACHMENT0+pe),V.readPixels(G,Z,F,q,Le.convert(Ce),Le.convert(ze),ne))}finally{const Te=C!==null?Je.get(C).__webglFramebuffer:null;Fe.bindFramebuffer(V.FRAMEBUFFER,Te)}}},this.readRenderTargetPixelsAsync=async function(I,G,Z,F,q,ne,le,pe=0){if(!(I&&I.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let xe=Je.get(I).__webglFramebuffer;if(I.isWebGLCubeRenderTarget&&le!==void 0&&(xe=xe[le]),xe)if(G>=0&&G<=I.width-F&&Z>=0&&Z<=I.height-q){Fe.bindFramebuffer(V.FRAMEBUFFER,xe);const Te=I.textures[pe],Ce=Te.format,ze=Te.type;if(!Ve.textureFormatReadable(Ce))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Ve.textureTypeReadable(ze))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Be=V.createBuffer();V.bindBuffer(V.PIXEL_PACK_BUFFER,Be),V.bufferData(V.PIXEL_PACK_BUFFER,ne.byteLength,V.STREAM_READ),I.textures.length>1&&V.readBuffer(V.COLOR_ATTACHMENT0+pe),V.readPixels(G,Z,F,q,Le.convert(Ce),Le.convert(ze),0);const qe=C!==null?Je.get(C).__webglFramebuffer:null;Fe.bindFramebuffer(V.FRAMEBUFFER,qe);const ut=V.fenceSync(V.SYNC_GPU_COMMANDS_COMPLETE,0);return V.flush(),await xX(V,ut,4),V.bindBuffer(V.PIXEL_PACK_BUFFER,Be),V.getBufferSubData(V.PIXEL_PACK_BUFFER,0,ne),V.deleteBuffer(Be),V.deleteSync(ut),ne}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(I,G=null,Z=0){const F=Math.pow(2,-Z),q=Math.floor(I.image.width*F),ne=Math.floor(I.image.height*F),le=G!==null?G.x:0,pe=G!==null?G.y:0;ht.setTexture2D(I,0),V.copyTexSubImage2D(V.TEXTURE_2D,Z,0,0,le,pe,q,ne),Fe.unbindTexture()};const B=V.createFramebuffer(),Y=V.createFramebuffer();this.copyTextureToTexture=function(I,G,Z=null,F=null,q=0,ne=null){ne===null&&(q!==0?(bp("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),ne=q,q=0):ne=0);let le,pe,xe,Te,Ce,ze,Be,qe,ut;const At=I.isCompressedTexture?I.mipmaps[ne]:I.image;if(Z!==null)le=Z.max.x-Z.min.x,pe=Z.max.y-Z.min.y,xe=Z.isBox3?Z.max.z-Z.min.z:1,Te=Z.min.x,Ce=Z.min.y,ze=Z.isBox3?Z.min.z:0;else{const Ii=Math.pow(2,-q);le=Math.floor(At.width*Ii),pe=Math.floor(At.height*Ii),I.isDataArrayTexture?xe=At.depth:I.isData3DTexture?xe=Math.floor(At.depth*Ii):xe=1,Te=0,Ce=0,ze=0}F!==null?(Be=F.x,qe=F.y,ut=F.z):(Be=0,qe=0,ut=0);const Rt=Le.convert(G.format),mt=Le.convert(G.type);let Dt;G.isData3DTexture?(ht.setTexture3D(G,0),Dt=V.TEXTURE_3D):G.isDataArrayTexture||G.isCompressedArrayTexture?(ht.setTexture2DArray(G,0),Dt=V.TEXTURE_2D_ARRAY):(ht.setTexture2D(G,0),Dt=V.TEXTURE_2D),V.pixelStorei(V.UNPACK_FLIP_Y_WEBGL,G.flipY),V.pixelStorei(V.UNPACK_PREMULTIPLY_ALPHA_WEBGL,G.premultiplyAlpha),V.pixelStorei(V.UNPACK_ALIGNMENT,G.unpackAlignment);const st=V.getParameter(V.UNPACK_ROW_LENGTH),Kt=V.getParameter(V.UNPACK_IMAGE_HEIGHT),Pn=V.getParameter(V.UNPACK_SKIP_PIXELS),Yt=V.getParameter(V.UNPACK_SKIP_ROWS),Wt=V.getParameter(V.UNPACK_SKIP_IMAGES);V.pixelStorei(V.UNPACK_ROW_LENGTH,At.width),V.pixelStorei(V.UNPACK_IMAGE_HEIGHT,At.height),V.pixelStorei(V.UNPACK_SKIP_PIXELS,Te),V.pixelStorei(V.UNPACK_SKIP_ROWS,Ce),V.pixelStorei(V.UNPACK_SKIP_IMAGES,ze);const Ot=I.isDataArrayTexture||I.isData3DTexture,Wn=G.isDataArrayTexture||G.isData3DTexture;if(I.isDepthTexture){const Ii=Je.get(I),An=Je.get(G),Zn=Je.get(Ii.__renderTarget),cd=Je.get(An.__renderTarget);Fe.bindFramebuffer(V.READ_FRAMEBUFFER,Zn.__webglFramebuffer),Fe.bindFramebuffer(V.DRAW_FRAMEBUFFER,cd.__webglFramebuffer);for(let $a=0;$a"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?KJ:QJ;B7.useSyncExternalStore=Np.useSyncExternalStore!==void 0?Np.useSyncExternalStore:JJ;z7.exports=B7;var $J=z7.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var hT=ie,e$=$J;function t$(n,e){return n===e&&(n!==0||1/n===1/e)||n!==n&&e!==e}var n$=typeof Object.is=="function"?Object.is:t$,i$=e$.useSyncExternalStore,r$=hT.useRef,a$=hT.useEffect,s$=hT.useMemo,o$=hT.useDebugValue;P7.useSyncExternalStoreWithSelector=function(n,e,t,i,r){var a=r$(null);if(a.current===null){var s={hasValue:!1,value:null};a.current=s}else s=a.current;a=s$(function(){function l(m){if(!u){if(u=!0,d=m,m=i(m),r!==void 0&&s.hasValue){var v=s.value;if(r(v,m))return f=v}return f=m}if(v=f,n$(d,m))return v;var x=i(m);return r!==void 0&&r(v,x)?(d=m,v):(d=m,f=x)}var u=!1,d,f,p=t===void 0?null:t;return[function(){return l(e())},p===null?void 0:function(){return l(p())}]},[e,t,i,r]);var o=i$(n,a[0],a[1]);return a$(function(){s.hasValue=!0,s.value=o},[o]),o$(o),o};U7.exports=P7;var l$=U7.exports;const c$=aS(l$),ML=n=>{let e;const t=new Set,i=(u,d)=>{const f=typeof u=="function"?u(e):u;if(!Object.is(f,e)){const p=e;e=d??(typeof f!="object"||f===null)?f:Object.assign({},e,f),t.forEach(m=>m(e,p))}},r=()=>e,o={setState:i,getState:r,getInitialState:()=>l,subscribe:u=>(t.add(u),()=>t.delete(u))},l=e=n(i,r,o);return o},u$=n=>n?ML(n):ML,{useSyncExternalStoreWithSelector:h$}=c$,d$=n=>n;function f$(n,e=d$,t){const i=h$(n.subscribe,n.getState,n.getInitialState,e,t);return QA.useDebugValue(i),i}const AL=(n,e)=>{const t=u$(n),i=(r,a=e)=>f$(t,r,a);return Object.assign(i,t),i},p$=(n,e)=>n?AL(n,e):AL,m$=n=>typeof n=="object"&&typeof n.then=="function",mh=[];function F7(n,e,t=(i,r)=>i===r){if(n===e)return!0;if(!n||!e)return!1;const i=n.length;if(e.length!==i)return!1;for(let r=0;r0&&(a.timeout&&clearTimeout(a.timeout),a.timeout=setTimeout(a.remove,i.lifespan)),a.response;if(!t)throw a.promise}const r={keys:e,equal:i.equal,remove:()=>{const a=mh.indexOf(r);a!==-1&&mh.splice(a,1)},promise:(m$(n)?n:n(...e)).then(a=>{r.response=a,i.lifespan&&i.lifespan>0&&(r.timeout=setTimeout(r.remove,i.lifespan))}).catch(a=>r.error=a)};if(mh.push(r),!t)throw r.promise}const g$=(n,e,t)=>H7(n,e,!1,t),v$=(n,e,t)=>void H7(n,e,!0,t),_$=n=>{if(n===void 0||n.length===0)mh.splice(0,mh.length);else{const e=mh.find(t=>F7(n,t.keys,t.equal));e&&e.remove()}};var V7={exports:{}},G7={exports:{}},k7={exports:{}},W7={};/** + * @license React + * scheduler.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(n){function e(X,te){var Q=X.length;X.push(te);e:for(;0>>1,se=X[ce];if(0>>1;cer(nt,Q))ttr(xt,nt)?(X[ce]=xt,X[tt]=Q,ce=tt):(X[ce]=nt,X[Xe]=Q,ce=Xe);else if(ttr(xt,Q))X[ce]=xt,X[tt]=Q,ce=tt;else break e}}return te}function r(X,te){var Q=X.sortIndex-te.sortIndex;return Q!==0?Q:X.id-te.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;n.unstable_now=function(){return a.now()}}else{var s=Date,o=s.now();n.unstable_now=function(){return s.now()-o}}var l=[],u=[],d=1,f=null,p=3,m=!1,v=!1,x=!1,S=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;function E(X){for(var te=t(u);te!==null;){if(te.callback===null)i(u);else if(te.startTime<=X)i(u),te.sortIndex=te.expirationTime,e(l,te);else break;te=t(u)}}function b(X){if(x=!1,E(X),!v)if(t(l)!==null)v=!0,oe();else{var te=t(u);te!==null&&ae(b,te.startTime-X)}}var R=!1,w=-1,L=5,U=-1;function N(){return!(n.unstable_now()-UX&&N());){var ce=f.callback;if(typeof ce=="function"){f.callback=null,p=f.priorityLevel;var se=ce(f.expirationTime<=X);if(X=n.unstable_now(),typeof se=="function"){f.callback=se,E(X),te=!0;break t}f===t(l)&&i(l),E(X)}else i(l);f=t(l)}if(f!==null)te=!0;else{var De=t(u);De!==null&&ae(b,De.startTime-X),te=!1}}break e}finally{f=null,p=Q,m=!1}te=void 0}}finally{te?z():R=!1}}}var z;if(typeof T=="function")z=function(){T(C)};else if(typeof MessageChannel<"u"){var W=new MessageChannel,K=W.port2;W.port1.onmessage=C,z=function(){K.postMessage(null)}}else z=function(){S(C,0)};function oe(){R||(R=!0,z())}function ae(X,te){w=S(function(){X(n.unstable_now())},te)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(X){X.callback=null},n.unstable_continueExecution=function(){v||m||(v=!0,oe())},n.unstable_forceFrameRate=function(X){0>X||125ce?(X.sortIndex=Q,e(u,X),t(l)===null&&X===t(u)&&(x?(_(w),w=-1):x=!0,ae(b,Q-ce))):(X.sortIndex=se,e(l,X),v||m||(v=!0,oe())),X},n.unstable_shouldYield=N,n.unstable_wrapCallback=function(X){var te=p;return function(){var Q=p;p=te;try{return X.apply(this,arguments)}finally{p=Q}}}})(W7);k7.exports=W7;var Q3=k7.exports;/** + * @license React + * react-reconciler.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(n){n.exports=function(e){function t(c,h,g,y){return new rH(c,h,g,y)}function i(){}function r(c){var h="https://react.dev/errors/"+c;if(1)":-1M||fe[y]!==Ne[M]){var et=` +`+fe[y].replace(" at new "," at ");return c.displayName&&et.includes("")&&(et=et.replace("",c.displayName)),et}while(1<=y&&0<=M);break}}}finally{E2=!1,Error.prepareStackTrace=g}return(g=c?c.displayName||c.name:"")?o(g):""}function u(c){switch(c.tag){case 26:case 27:case 5:return o(c.type);case 16:return o("Lazy");case 13:return o("Suspense");case 19:return o("SuspenseList");case 0:case 15:return c=l(c.type,!1),c;case 11:return c=l(c.type.render,!1),c;case 1:return c=l(c.type,!0),c;default:return""}}function d(c){try{var h="";do h+=u(c),c=c.return;while(c);return h}catch(g){return` +Error generating stack: `+g.message+` +`+g.stack}}function f(c){var h=c,g=c;if(c.alternate)for(;h.return;)h=h.return;else{c=h;do h=c,h.flags&4098&&(g=h.return),c=h.return;while(c)}return h.tag===3?g:null}function p(c){if(f(c)!==c)throw Error(r(188))}function m(c){var h=c.alternate;if(!h){if(h=f(c),h===null)throw Error(r(188));return h!==c?null:c}for(var g=c,y=h;;){var M=g.return;if(M===null)break;var A=M.alternate;if(A===null){if(y=M.return,y!==null){g=y;continue}break}if(M.child===A.child){for(A=M.child;A;){if(A===g)return p(M),c;if(A===y)return p(M),h;A=A.sibling}throw Error(r(188))}if(g.return!==y.return)g=M,y=A;else{for(var H=!1,ee=M.child;ee;){if(ee===g){H=!0,g=M,y=A;break}if(ee===y){H=!0,y=M,g=A;break}ee=ee.sibling}if(!H){for(ee=A.child;ee;){if(ee===g){H=!0,g=A,y=M;break}if(ee===y){H=!0,y=A,g=M;break}ee=ee.sibling}if(!H)throw Error(r(189))}}if(g.alternate!==y)throw Error(r(190))}if(g.tag!==3)throw Error(r(188));return g.stateNode.current===g?c:h}function v(c){var h=c.tag;if(h===5||h===26||h===27||h===6)return c;for(c=c.child;c!==null;){if(h=v(c),h!==null)return h;c=c.sibling}return null}function x(c){var h=c.tag;if(h===5||h===26||h===27||h===6)return c;for(c=c.child;c!==null;){if(c.tag!==4&&(h=x(c),h!==null))return h;c=c.sibling}return null}function S(c){return{current:c}}function _(c){0>vd||(c.current=C2[vd],C2[vd]=null,vd--)}function T(c,h){vd++,C2[vd]=c.current,c.current=h}function E(c){return c>>>=0,c===0?32:31-(MV(c)/AV|0)|0}function b(c){var h=c&42;if(h!==0)return h;switch(c&-c){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: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 c&4194176;case 4194304:case 8388608:case 16777216:case 33554432:return c&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return c}}function R(c,h){var g=c.pendingLanes;if(g===0)return 0;var y=0,M=c.suspendedLanes,A=c.pingedLanes,H=c.warmLanes;c=c.finishedLanes!==0;var ee=g&134217727;return ee!==0?(g=ee&~M,g!==0?y=b(g):(A&=ee,A!==0?y=b(A):c||(H=ee&~H,H!==0&&(y=b(H))))):(ee=g&~M,ee!==0?y=b(ee):A!==0?y=b(A):c||(H=g&~H,H!==0&&(y=b(H)))),y===0?0:h!==0&&h!==y&&!(h&M)&&(M=y&-y,H=h&-h,M>=H||M===32&&(H&4194176)!==0)?h:y}function w(c,h){return(c.pendingLanes&~(c.suspendedLanes&~c.pingedLanes)&h)===0}function L(c,h){switch(c){case 1:case 2:case 4:case 8:return h+250;case 16:case 32:case 64: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 h+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 U(){var c=Uv;return Uv<<=1,!(Uv&4194176)&&(Uv=128),c}function N(){var c=Pv;return Pv<<=1,!(Pv&62914560)&&(Pv=4194304),c}function C(c){for(var h=[],g=0;31>g;g++)h.push(c);return h}function z(c,h){c.pendingLanes|=h,h!==268435456&&(c.suspendedLanes=0,c.pingedLanes=0,c.warmLanes=0)}function W(c,h,g,y,M,A){var H=c.pendingLanes;c.pendingLanes=g,c.suspendedLanes=0,c.pingedLanes=0,c.warmLanes=0,c.expiredLanes&=g,c.entangledLanes&=g,c.errorRecoveryDisabledLanes&=g,c.shellSuspendCounter=0;var ee=c.entanglements,fe=c.expirationTimes,Ne=c.hiddenUpdates;for(g=H&~g;0>=H,M-=H,ko=1<<32-wa(h)+M|g<_n?(ir=Ft,Ft=null):ir=Ft.sibling;var xn=_t(_e,Ft,ye[_n],Ke);if(xn===null){Ft===null&&(Ft=ir);break}c&&Ft&&xn.alternate===null&&h(_e,Ft),ue=A(xn,ue,_n),ni===null?Nt=xn:ni.sibling=xn,ni=xn,Ft=ir}if(_n===ye.length)return g(_e,Ft),vn&&se(_e,_n),Nt;if(Ft===null){for(;_n_n?(ir=Ft,Ft=null):ir=Ft.sibling;var nc=_t(_e,Ft,xn.value,Ke);if(nc===null){Ft===null&&(Ft=ir);break}c&&Ft&&nc.alternate===null&&h(_e,Ft),ue=A(nc,ue,_n),ni===null?Nt=nc:ni.sibling=nc,ni=nc,Ft=ir}if(xn.done)return g(_e,Ft),vn&&se(_e,_n),Nt;if(Ft===null){for(;!xn.done;_n++,xn=ye.next())xn=gt(_e,xn.value,Ke),xn!==null&&(ue=A(xn,ue,_n),ni===null?Nt=xn:ni.sibling=xn,ni=xn);return vn&&se(_e,_n),Nt}for(Ft=y(Ft);!xn.done;_n++,xn=ye.next())xn=jt(Ft,_e,_n,xn.value,Ke),xn!==null&&(c&&xn.alternate!==null&&Ft.delete(xn.key===null?_n:xn.key),ue=A(xn,ue,_n),ni===null?Nt=xn:ni.sibling=xn,ni=xn);return c&&Ft.forEach(function(HV){return h(_e,HV)}),vn&&se(_e,_n),Nt}function Cu(_e,ue,ye,Ke){if(typeof ye=="object"&&ye!==null&&ye.type===md&&ye.key===null&&(ye=ye.props.children),typeof ye=="object"&&ye!==null){switch(ye.$$typeof){case Ov:e:{for(var Nt=ye.key;ue!==null;){if(ue.key===Nt){if(Nt=ye.type,Nt===md){if(ue.tag===7){g(_e,ue.sibling),Ke=M(ue,ye.props.children),Ke.return=_e,_e=Ke;break e}}else if(ue.elementType===Nt||typeof Nt=="object"&&Nt!==null&&Nt.$$typeof===jl&&mi(Nt)===ue.type){g(_e,ue.sibling),Ke=M(ue,ye.props),Gt(Ke,ye),Ke.return=_e,_e=Ke;break e}g(_e,ue);break}else h(_e,ue);ue=ue.sibling}ye.type===md?(Ke=vu(ye.props.children,_e.mode,Ke,ye.key),Ke.return=_e,_e=Ke):(Ke=Nv(ye.type,ye.key,ye.props,null,_e.mode,Ke),Gt(Ke,ye),Ke.return=_e,_e=Ke)}return H(_e);case pd:e:{for(Nt=ye.key;ue!==null;){if(ue.key===Nt)if(ue.tag===4&&ue.stateNode.containerInfo===ye.containerInfo&&ue.stateNode.implementation===ye.implementation){g(_e,ue.sibling),Ke=M(ue,ye.children||[]),Ke.return=_e,_e=Ke;break e}else{g(_e,ue);break}else h(_e,ue);ue=ue.sibling}Ke=p2(ye,_e.mode,Ke),Ke.return=_e,_e=Ke}return H(_e);case jl:return Nt=ye._init,ye=Nt(ye._payload),Cu(_e,ue,ye,Ke)}if(Lv(ye))return os(_e,ue,ye,Ke);if(a(ye)){if(Nt=a(ye),typeof Nt!="function")throw Error(r(150));return ye=Nt.call(ye),Cm(_e,ue,ye,Ke)}if(typeof ye.then=="function")return Cu(_e,ue,Et(ye),Ke);if(ye.$$typeof===Yl)return Cu(_e,ue,Mv(_e,ye),Ke);kt(_e,ye)}return typeof ye=="string"&&ye!==""||typeof ye=="number"||typeof ye=="bigint"?(ye=""+ye,ue!==null&&ue.tag===6?(g(_e,ue.sibling),Ke=M(ue,ye),Ke.return=_e,_e=Ke):(g(_e,ue),Ke=f2(ye,_e.mode,Ke),Ke.return=_e,_e=Ke),H(_e)):g(_e,ue)}return function(_e,ue,ye,Ke){try{Tm=0;var Nt=Cu(_e,ue,ye,Ke);return wd=null,Nt}catch(Ft){if(Ft===Sm)throw Ft;var ni=t(29,Ft,null,_e.mode);return ni.lanes=Ke,ni.return=_e,ni}finally{}}}function Po(c,h){c=jo,T(Wv,c),T(Rd,h),jo=c|h.baseLanes}function ro(){T(Wv,jo),T(Rd,Rd.current)}function ao(){jo=Wv.current,_(Rd),_(Wv)}function Li(c){var h=c.alternate;T(ji,ji.current&1),T(as,c),uo===null&&(h===null||Rd.current!==null||h.memoizedState!==null)&&(uo=c)}function so(c){if(c.tag===22){if(T(ji,ji.current),T(as,c),uo===null){var h=c.alternate;h!==null&&h.memoizedState!==null&&(uo=c)}}else Er()}function Er(){T(ji,ji.current),T(as,as.current)}function er(c){_(as),uo===c&&(uo=null),_(ji)}function $r(c){for(var h=c;h!==null;){if(h.tag===13){var g=h.memoizedState;if(g!==null&&(g=g.dehydrated,g===null||A2(g)||w2(g)))return h}else if(h.tag===19&&h.memoizedProps.revealOrder!==void 0){if(h.flags&128)return h}else if(h.child!==null){h.child.return=h,h=h.child;continue}if(h===c)break;for(;h.sibling===null;){if(h.return===null||h.return===c)return null;h=h.return}h.sibling.return=h.return,h=h.sibling}return null}function Un(){throw Error(r(321))}function Ja(c,h){if(h===null)return!1;for(var g=0;gA?A:8);var H=Vt.T,ee={};Vt.T=ee,LT(c,!1,h,g);try{var fe=M(),Ne=Vt.S;if(Ne!==null&&Ne(ee,fe),fe!==null&&typeof fe=="object"&&typeof fe.then=="function"){var et=je(fe,y);om(c,h,et,Ma(c))}else om(c,h,y,Ma(c))}catch(gt){om(c,h,{then:function(){},status:"rejected",reason:gt},Ma())}finally{ta(A),Vt.T=H}}function bC(c){var h=c.memoizedState;if(h!==null)return h;h={memoizedState:gd,baseState:gd,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:q,lastRenderedState:gd},next:null};var g={};return h.next={memoizedState:g,baseState:g,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:q,lastRenderedState:g},next:null},c.memoizedState=h,c=c.alternate,c!==null&&(c.memoizedState=h),h}function OT(){return Mr(xu)}function MC(){return I().memoizedState}function AC(){return I().memoizedState}function VF(c){for(var h=c.return;h!==null;){switch(h.tag){case 24:case 3:var g=Ma();c=Ue(g);var y=He(h,c,g);y!==null&&(zr(y,h,g),pt(y,h,g)),h={cache:qT()},c.payload=h;return}h=h.return}}function GF(c,h,g){var y=Ma();g={lane:y,revertLane:0,action:g,hasEagerState:!1,eagerState:null,next:null},Tv(c)?RC(h,g):(g=Ae(c,h,g,y),g!==null&&(zr(g,c,y),CC(g,h,y)))}function wC(c,h,g){var y=Ma();om(c,h,g,y)}function om(c,h,g,y){var M={lane:y,revertLane:0,action:g,hasEagerState:!1,eagerState:null,next:null};if(Tv(c))RC(h,M);else{var A=c.alternate;if(c.lanes===0&&(A===null||A.lanes===0)&&(A=h.lastRenderedReducer,A!==null))try{var H=h.lastRenderedState,ee=A(H,g);if(M.hasEagerState=!0,M.eagerState=ee,Ca(ee,H))return V(c,h,M,0),Qn===null&&Ee(),!1}catch{}finally{}if(g=Ae(c,h,M,y),g!==null)return zr(g,c,y),CC(g,h,y),!0}return!1}function LT(c,h,g,y){if(y={lane:2,revertLane:Ie(),action:y,hasEagerState:!1,eagerState:null,next:null},Tv(c)){if(h)throw Error(r(479))}else h=Ae(c,g,y,2),h!==null&&zr(h,c,2)}function Tv(c){var h=c.alternate;return c===en||h!==null&&h===en}function RC(c,h){Cd=Xv=!0;var g=c.pending;g===null?h.next=h:(h.next=g.next,g.next=h),c.pending=h}function CC(c,h,g){if(g&4194176){var y=h.lanes;y&=c.pendingLanes,g|=y,h.lanes=g,oe(c,g)}}function IT(c,h,g,y){h=c.memoizedState,g=g(y,h),g=g==null?h:g2({},h,g),c.memoizedState=g,c.lanes===0&&(c.updateQueue.baseState=g)}function DC(c,h,g,y,M,A,H){return c=c.stateNode,typeof c.shouldComponentUpdate=="function"?c.shouldComponentUpdate(y,A,H):h.prototype&&h.prototype.isPureReactComponent?!ge(g,y)||!ge(M,A):!0}function NC(c,h,g,y){c=h.state,typeof h.componentWillReceiveProps=="function"&&h.componentWillReceiveProps(g,y),typeof h.UNSAFE_componentWillReceiveProps=="function"&&h.UNSAFE_componentWillReceiveProps(g,y),h.state!==c&&H2.enqueueReplaceState(h,h.state,null)}function du(c,h){var g=h;if("ref"in h){g={};for(var y in h)y!=="ref"&&(g[y]=h[y])}if(c=c.defaultProps){g===h&&(g=g2({},g));for(var M in c)g[M]===void 0&&(g[M]=c[M])}return g}function Ev(c,h){try{var g=c.onUncaughtError;g(h.value,{componentStack:h.stack})}catch(y){setTimeout(function(){throw y})}}function OC(c,h,g){try{var y=c.onCaughtError;y(g.value,{componentStack:g.stack,errorBoundary:h.tag===1?h.stateNode:null})}catch(M){setTimeout(function(){throw M})}}function UT(c,h,g){return g=Ue(g),g.tag=3,g.payload={element:null},g.callback=function(){Ev(c,h)},g}function LC(c){return c=Ue(c),c.tag=3,c}function IC(c,h,g,y){var M=g.type.getDerivedStateFromError;if(typeof M=="function"){var A=y.value;c.payload=function(){return M(A)},c.callback=function(){OC(h,g,y)}}var H=g.stateNode;H!==null&&typeof H.componentDidCatch=="function"&&(c.callback=function(){OC(h,g,y),typeof M!="function"&&(tc===null?tc=new Set([this]):tc.add(this));var ee=y.stack;this.componentDidCatch(y.value,{componentStack:ee!==null?ee:""})})}function kF(c,h,g,y,M){if(g.flags|=32768,y!==null&&typeof y=="object"&&typeof y.then=="function"){if(h=g.alternate,h!==null&&cm(h,g,M,!0),g=as.current,g!==null){switch(g.tag){case 13:return uo===null?c2():g.alternate===null&&Si===0&&(Si=3),g.flags&=-257,g.flags|=65536,g.lanes=M,y===kv?g.flags|=16384:(h=g.updateQueue,h===null?g.updateQueue=new Set([y]):h.add(y),h2(c,y,M)),!1;case 22:return g.flags|=65536,y===kv?g.flags|=16384:(h=g.updateQueue,h===null?(h={transitions:null,markerInstances:null,retryQueue:new Set([y])},g.updateQueue=h):(g=h.retryQueue,g===null?h.retryQueue=new Set([y]):g.add(y)),h2(c,y,M)),!1}throw Error(r(435,g.tag))}return h2(c,y,M),c2(),!1}if(vn)return h=as.current,h!==null?(!(h.flags&65536)&&(h.flags|=256),h.flags|=65536,h.lanes=M,y!==O2&&(c=Error(r(422),{cause:y}),Qe(ce(c,g)))):(y!==O2&&(h=Error(r(423),{cause:y}),Qe(ce(h,g))),c=c.current.alternate,c.flags|=65536,M&=-M,c.lanes|=M,y=ce(y,g),M=UT(c.stateNode,y,M),J(c,M),Si!==4&&(Si=2)),!1;var A=Error(r(520),{cause:y});if(A=ce(A,g),Mm===null?Mm=[A]:Mm.push(A),Si!==4&&(Si=2),h===null)return!0;y=ce(y,g),g=h;do{switch(g.tag){case 3:return g.flags|=65536,c=M&-M,g.lanes|=c,c=UT(g.stateNode,y,c),J(g,c),!1;case 1:if(h=g.type,A=g.stateNode,(g.flags&128)===0&&(typeof h.getDerivedStateFromError=="function"||A!==null&&typeof A.componentDidCatch=="function"&&(tc===null||!tc.has(A))))return g.flags|=65536,M&=-M,g.lanes|=M,M=LC(M),IC(M,c,g,y),J(g,M),!1}g=g.return}while(g!==null);return!1}function fr(c,h,g,y){h.child=c===null?gD(h,null,g,y):Su(h,c.child,g,y)}function UC(c,h,g,y,M){g=g.render;var A=h.ref;if("ref"in y){var H={};for(var ee in y)ee!=="ref"&&(H[ee]=y[ee])}else H=y;return fu(h),y=oo(c,h,g,H,A,M),ee=br(),c!==null&&!tr?(O(c,h,M),Bo(c,h,M)):(vn&&ee&&Xe(h),h.flags|=1,fr(c,h,y,M),h.child)}function PC(c,h,g,y,M){if(c===null){var A=g.type;return typeof A=="function"&&!d2(A)&&A.defaultProps===void 0&&g.compare===null?(h.tag=15,h.type=A,zC(c,h,A,y,M)):(c=Nv(g.type,null,y,h,h.mode,M),c.ref=h.ref,c.return=h,h.child=c)}if(A=c.child,!kT(c,M)){var H=A.memoizedProps;if(g=g.compare,g=g!==null?g:ge,g(H,y)&&c.ref===h.ref)return Bo(c,h,M)}return h.flags|=1,c=ql(A,y),c.ref=h.ref,c.return=h,h.child=c}function zC(c,h,g,y,M){if(c!==null){var A=c.memoizedProps;if(ge(A,y)&&c.ref===h.ref)if(tr=!1,h.pendingProps=y=A,kT(c,M))c.flags&131072&&(tr=!0);else return h.lanes=c.lanes,Bo(c,h,M)}return PT(c,h,g,y,M)}function BC(c,h,g){var y=h.pendingProps,M=y.children,A=(h.stateNode._pendingVisibility&2)!==0,H=c!==null?c.memoizedState:null;if(lm(c,h),y.mode==="hidden"||A){if(h.flags&128){if(y=H!==null?H.baseLanes|g:g,c!==null){for(M=h.child=c.child,A=0;M!==null;)A=A|M.lanes|M.childLanes,M=M.sibling;h.childLanes=A&~y}else h.childLanes=0,h.child=null;return FC(c,h,y,g)}if(g&536870912)h.memoizedState={baseLanes:0,cachePool:null},c!==null&&Av(h,H!==null?H.cachePool:null),H!==null?Po(h,H):ro(),so(h);else return h.lanes=h.childLanes=536870912,FC(c,h,H!==null?H.baseLanes|g:g,g)}else H!==null?(Av(h,H.cachePool),Po(h,H),Er(),h.memoizedState=null):(c!==null&&Av(h,null),ro(),Er());return fr(c,h,M,g),h.child}function FC(c,h,g,y){var M=YT();return M=M===null?null:{parent:Go?xi._currentValue:xi._currentValue2,pool:M},h.memoizedState={baseLanes:g,cachePool:M},c!==null&&Av(h,null),ro(),so(h),c!==null&&cm(c,h,y,!0),null}function lm(c,h){var g=h.ref;if(g===null)c!==null&&c.ref!==null&&(h.flags|=2097664);else{if(typeof g!="function"&&typeof g!="object")throw Error(r(284));(c===null||c.ref!==g)&&(h.flags|=2097664)}}function PT(c,h,g,y,M){return fu(h),g=oo(c,h,g,y,void 0,M),y=br(),c!==null&&!tr?(O(c,h,M),Bo(c,h,M)):(vn&&y&&Xe(h),h.flags|=1,fr(c,h,g,M),h.child)}function HC(c,h,g,y,M,A){return fu(h),h.updateQueue=null,g=zo(h,y,g,M),lo(c),y=br(),c!==null&&!tr?(O(c,h,A),Bo(c,h,A)):(vn&&y&&Xe(h),h.flags|=1,fr(c,h,g,A),h.child)}function VC(c,h,g,y,M){if(fu(h),h.stateNode===null){var A=_d,H=g.contextType;typeof H=="object"&&H!==null&&(A=Mr(H)),A=new g(y,A),h.memoizedState=A.state!==null&&A.state!==void 0?A.state:null,A.updater=H2,h.stateNode=A,A._reactInternals=h,A=h.stateNode,A.props=y,A.state=h.memoizedState,A.refs={},Tt(h),H=g.contextType,A.context=typeof H=="object"&&H!==null?Mr(H):_d,A.state=h.memoizedState,H=g.getDerivedStateFromProps,typeof H=="function"&&(IT(h,g,H,y),A.state=h.memoizedState),typeof g.getDerivedStateFromProps=="function"||typeof A.getSnapshotBeforeUpdate=="function"||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(H=A.state,typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount(),H!==A.state&&H2.enqueueReplaceState(A,A.state,null),Le(h,y,A,M),me(),A.state=h.memoizedState),typeof A.componentDidMount=="function"&&(h.flags|=4194308),y=!0}else if(c===null){A=h.stateNode;var ee=h.memoizedProps,fe=du(g,ee);A.props=fe;var Ne=A.context,et=g.contextType;H=_d,typeof et=="object"&&et!==null&&(H=Mr(et));var gt=g.getDerivedStateFromProps;et=typeof gt=="function"||typeof A.getSnapshotBeforeUpdate=="function",ee=h.pendingProps!==ee,et||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(ee||Ne!==H)&&NC(h,A,y,H),Kl=!1;var _t=h.memoizedState;A.state=_t,Le(h,y,A,M),me(),Ne=h.memoizedState,ee||_t!==Ne||Kl?(typeof gt=="function"&&(IT(h,g,gt,y),Ne=h.memoizedState),(fe=Kl||DC(h,g,fe,y,_t,Ne,H))?(et||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount()),typeof A.componentDidMount=="function"&&(h.flags|=4194308)):(typeof A.componentDidMount=="function"&&(h.flags|=4194308),h.memoizedProps=y,h.memoizedState=Ne),A.props=y,A.state=Ne,A.context=H,y=fe):(typeof A.componentDidMount=="function"&&(h.flags|=4194308),y=!1)}else{A=h.stateNode,vt(c,h),H=h.memoizedProps,et=du(g,H),A.props=et,gt=h.pendingProps,_t=A.context,Ne=g.contextType,fe=_d,typeof Ne=="object"&&Ne!==null&&(fe=Mr(Ne)),ee=g.getDerivedStateFromProps,(Ne=typeof ee=="function"||typeof A.getSnapshotBeforeUpdate=="function")||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(H!==gt||_t!==fe)&&NC(h,A,y,fe),Kl=!1,_t=h.memoizedState,A.state=_t,Le(h,y,A,M),me();var jt=h.memoizedState;H!==gt||_t!==jt||Kl||c!==null&&c.dependencies!==null&&bv(c.dependencies)?(typeof ee=="function"&&(IT(h,g,ee,y),jt=h.memoizedState),(et=Kl||DC(h,g,et,y,_t,jt,fe)||c!==null&&c.dependencies!==null&&bv(c.dependencies))?(Ne||typeof A.UNSAFE_componentWillUpdate!="function"&&typeof A.componentWillUpdate!="function"||(typeof A.componentWillUpdate=="function"&&A.componentWillUpdate(y,jt,fe),typeof A.UNSAFE_componentWillUpdate=="function"&&A.UNSAFE_componentWillUpdate(y,jt,fe)),typeof A.componentDidUpdate=="function"&&(h.flags|=4),typeof A.getSnapshotBeforeUpdate=="function"&&(h.flags|=1024)):(typeof A.componentDidUpdate!="function"||H===c.memoizedProps&&_t===c.memoizedState||(h.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||H===c.memoizedProps&&_t===c.memoizedState||(h.flags|=1024),h.memoizedProps=y,h.memoizedState=jt),A.props=y,A.state=jt,A.context=fe,y=et):(typeof A.componentDidUpdate!="function"||H===c.memoizedProps&&_t===c.memoizedState||(h.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||H===c.memoizedProps&&_t===c.memoizedState||(h.flags|=1024),y=!1)}return A=y,lm(c,h),y=(h.flags&128)!==0,A||y?(A=h.stateNode,g=y&&typeof g.getDerivedStateFromError!="function"?null:A.render(),h.flags|=1,c!==null&&y?(h.child=Su(h,c.child,null,M),h.child=Su(h,null,g,M)):fr(c,h,g,M),h.memoizedState=A.state,c=h.child):c=Bo(c,h,M),c}function GC(c,h,g,y){return ct(),h.flags|=256,fr(c,h,g,y),h.child}function zT(c){return{baseLanes:c,cachePool:jC()}}function BT(c,h,g){return c=c!==null?c.childLanes&~g:0,h&&(c|=ss),c}function kC(c,h,g){var y=h.pendingProps,M=!1,A=(h.flags&128)!==0,H;if((H=A)||(H=c!==null&&c.memoizedState===null?!1:(ji.current&2)!==0),H&&(M=!0,h.flags&=-129),H=(h.flags&32)!==0,h.flags&=-33,c===null){if(vn){if(M?Li(h):Er(),vn){var ee=Rr,fe;(fe=ee)&&(ee=sV(ee,co),ee!==null?(h.memoizedState={dehydrated:ee,treeContext:yu!==null?{id:ko,overflow:Wo}:null,retryLane:536870912},fe=t(18,null,null,0),fe.stateNode=ee,fe.return=h,h.child=fe,Br=h,Rr=null,fe=!0):fe=!1),fe||Ze(h)}if(ee=h.memoizedState,ee!==null&&(ee=ee.dehydrated,ee!==null))return w2(ee)?h.lanes=16:h.lanes=536870912,null;er(h)}return ee=y.children,y=y.fallback,M?(Er(),M=h.mode,ee=HT({mode:"hidden",children:ee},M),y=vu(y,M,g,null),ee.return=h,y.return=h,ee.sibling=y,h.child=ee,M=h.child,M.memoizedState=zT(g),M.childLanes=BT(c,H,g),h.memoizedState=V2,y):(Li(h),FT(h,ee))}if(fe=c.memoizedState,fe!==null&&(ee=fe.dehydrated,ee!==null)){if(A)h.flags&256?(Li(h),h.flags&=-257,h=VT(c,h,g)):h.memoizedState!==null?(Er(),h.child=c.child,h.flags|=128,h=null):(Er(),M=y.fallback,ee=h.mode,y=HT({mode:"visible",children:y.children},ee),M=vu(M,ee,g,null),M.flags|=2,y.return=h,M.return=h,y.sibling=M,h.child=y,Su(h,c.child,null,g),y=h.child,y.memoizedState=zT(g),y.childLanes=BT(c,H,g),h.memoizedState=V2,h=M);else if(Li(h),w2(ee))H=JH(ee).digest,y=Error(r(419)),y.stack="",y.digest=H,Qe({value:y,source:null,stack:null}),h=VT(c,h,g);else if(tr||cm(c,h,g,!1),H=(g&c.childLanes)!==0,tr||H){if(H=Qn,H!==null){if(y=g&-g,y&42)y=1;else switch(y){case 2:y=1;break;case 8:y=4;break;case 32:y=16;break;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:case 4194304:case 8388608:case 16777216:case 33554432:y=64;break;case 268435456:y=134217728;break;default:y=0}if(y=y&(H.suspendedLanes|g)?0:y,y!==0&&y!==fe.retryLane)throw fe.retryLane=y,Oe(c,y),zr(H,c,y),_D}A2(ee)||c2(),h=VT(c,h,g)}else A2(ee)?(h.flags|=128,h.child=c.child,h=tH.bind(null,c),$H(ee,h),h=null):(c=fe.treeContext,es&&(Rr=iV(ee),Br=h,vn=!0,Is=null,co=!1,c!==null&&(ns[is++]=ko,ns[is++]=Wo,ns[is++]=yu,ko=c.id,Wo=c.overflow,yu=h)),h=FT(h,y.children),h.flags|=4096);return h}return M?(Er(),M=y.fallback,ee=h.mode,fe=c.child,A=fe.sibling,y=ql(fe,{mode:"hidden",children:y.children}),y.subtreeFlags=fe.subtreeFlags&31457280,A!==null?M=ql(A,M):(M=vu(M,ee,g,null),M.flags|=2),M.return=h,y.return=h,y.sibling=M,h.child=y,y=M,M=h.child,ee=c.child.memoizedState,ee===null?ee=zT(g):(fe=ee.cachePool,fe!==null?(A=Go?xi._currentValue:xi._currentValue2,fe=fe.parent!==A?{parent:A,pool:A}:fe):fe=jC(),ee={baseLanes:ee.baseLanes|g,cachePool:fe}),M.memoizedState=ee,M.childLanes=BT(c,H,g),h.memoizedState=V2,y):(Li(h),g=c.child,c=g.sibling,g=ql(g,{mode:"visible",children:y.children}),g.return=h,g.sibling=null,c!==null&&(H=h.deletions,H===null?(h.deletions=[c],h.flags|=16):H.push(c)),h.child=g,h.memoizedState=null,g)}function FT(c,h){return h=HT({mode:"visible",children:h},c.mode),h.return=c,c.child=h}function HT(c,h){return L4(c,h,0,null)}function VT(c,h,g){return Su(h,c.child,null,g),c=FT(h,h.pendingProps.children),c.flags|=2,h.memoizedState=null,c}function WC(c,h,g){c.lanes|=h;var y=c.alternate;y!==null&&(y.lanes|=h),WT(c.return,h,g)}function GT(c,h,g,y,M){var A=c.memoizedState;A===null?c.memoizedState={isBackwards:h,rendering:null,renderingStartTime:0,last:y,tail:g,tailMode:M}:(A.isBackwards=h,A.rendering=null,A.renderingStartTime=0,A.last=y,A.tail=g,A.tailMode=M)}function XC(c,h,g){var y=h.pendingProps,M=y.revealOrder,A=y.tail;if(fr(c,h,y.children,g),y=ji.current,y&2)y=y&1|2,h.flags|=128;else{if(c!==null&&c.flags&128)e:for(c=h.child;c!==null;){if(c.tag===13)c.memoizedState!==null&&WC(c,g,h);else if(c.tag===19)WC(c,g,h);else if(c.child!==null){c.child.return=c,c=c.child;continue}if(c===h)break e;for(;c.sibling===null;){if(c.return===null||c.return===h)break e;c=c.return}c.sibling.return=c.return,c=c.sibling}y&=1}switch(T(ji,y),M){case"forwards":for(g=h.child,M=null;g!==null;)c=g.alternate,c!==null&&$r(c)===null&&(M=g),g=g.sibling;g=M,g===null?(M=h.child,h.child=null):(M=g.sibling,g.sibling=null),GT(h,!1,M,g,A);break;case"backwards":for(g=null,M=h.child,h.child=null;M!==null;){if(c=M.alternate,c!==null&&$r(c)===null){h.child=M;break}c=M.sibling,M.sibling=g,g=M,M=c}GT(h,!0,g,null,A);break;case"together":GT(h,!1,null,null,void 0);break;default:h.memoizedState=null}return h.child}function Bo(c,h,g){if(c!==null&&(h.dependencies=c.dependencies),ec|=h.lanes,!(g&h.childLanes))if(c!==null){if(cm(c,h,g,!1),(g&h.childLanes)===0)return null}else return null;if(c!==null&&h.child!==c.child)throw Error(r(153));if(h.child!==null){for(c=h.child,g=ql(c,c.pendingProps),h.child=g,g.return=h;c.sibling!==null;)c=c.sibling,g=g.sibling=ql(c,c.pendingProps),g.return=h;g.sibling=null}return h.child}function kT(c,h){return c.lanes&h?!0:(c=c.dependencies,!!(c!==null&&bv(c)))}function WF(c,h,g){switch(h.tag){case 3:tt(h,h.stateNode.containerInfo),Gl(h,xi,c.memoizedState.cache),ct();break;case 27:case 5:ve(h);break;case 4:tt(h,h.stateNode.containerInfo);break;case 10:Gl(h,h.type,h.memoizedProps.value);break;case 13:var y=h.memoizedState;if(y!==null)return y.dehydrated!==null?(Li(h),h.flags|=128,null):g&h.child.childLanes?kC(c,h,g):(Li(h),c=Bo(c,h,g),c!==null?c.sibling:null);Li(h);break;case 19:var M=(c.flags&128)!==0;if(y=(g&h.childLanes)!==0,y||(cm(c,h,g,!1),y=(g&h.childLanes)!==0),M){if(y)return XC(c,h,g);h.flags|=128}if(M=h.memoizedState,M!==null&&(M.rendering=null,M.tail=null,M.lastEffect=null),T(ji,ji.current),y)break;return null;case 22:case 23:return h.lanes=0,BC(c,h,g);case 24:Gl(h,xi,c.memoizedState.cache)}return Bo(c,h,g)}function qC(c,h,g){if(c!==null)if(c.memoizedProps!==h.pendingProps)tr=!0;else{if(!kT(c,g)&&!(h.flags&128))return tr=!1,WF(c,h,g);tr=!!(c.flags&131072)}else tr=!1,vn&&h.flags&1048576&&De(h,Fv,h.index);switch(h.lanes=0,h.tag){case 16:e:{c=h.pendingProps;var y=h.elementType,M=y._init;if(y=M(y._payload),h.type=y,typeof y=="function")d2(y)?(c=du(y,c),h.tag=1,h=VC(null,h,y,c,g)):(h.tag=0,h=PT(null,h,y,c,g));else{if(y!=null){if(M=y.$$typeof,M===_2){h.tag=11,h=UC(null,h,y,c,g);break e}else if(M===S2){h.tag=14,h=PC(null,h,y,c,g);break e}}throw h=s(y)||y,Error(r(306,h,""))}}return h;case 0:return PT(c,h,h.type,h.pendingProps,g);case 1:return y=h.type,M=du(y,h.pendingProps),VC(c,h,y,M,g);case 3:e:{if(tt(h,h.stateNode.containerInfo),c===null)throw Error(r(387));var A=h.pendingProps;M=h.memoizedState,y=M.element,vt(c,h),Le(h,A,null,g);var H=h.memoizedState;if(A=H.cache,Gl(h,xi,A),A!==M.cache&&XT(h,[xi],g,!0),me(),A=H.element,es&&M.isDehydrated)if(M={element:A,isDehydrated:!1,cache:H.cache},h.updateQueue.baseState=M,h.memoizedState=M,h.flags&256){h=GC(c,h,A,g);break e}else if(A!==y){y=ce(Error(r(424)),h),Qe(y),h=GC(c,h,A,g);break e}else for(es&&(Rr=nV(h.stateNode.containerInfo),Br=h,vn=!0,Is=null,co=!0),g=gD(h,null,A,g),h.child=g;g;)g.flags=g.flags&-3|4096,g=g.sibling;else{if(ct(),A===y){h=Bo(c,h,g);break e}fr(c,h,A,g)}h=h.child}return h;case 26:if(ts)return lm(c,h),c===null?(g=sD(h.type,null,h.pendingProps,null))?h.memoizedState=g:vn||(h.stateNode=_V(h.type,h.pendingProps,Ql.current,h)):h.memoizedState=sD(h.type,c.memoizedProps,h.pendingProps,c.memoizedState),null;case 27:if(wr)return ve(h),c===null&&wr&&vn&&(y=h.stateNode=dD(h.type,h.pendingProps,Ql.current,pr.current,!1),Br=h,co=!0,Rr=iD(y)),y=h.pendingProps.children,c!==null||vn?fr(c,h,y,g):h.child=Su(h,null,y,g),lm(c,h),h.child;case 5:return c===null&&vn&&(mV(h.type,h.pendingProps,pr.current),(M=y=Rr)&&(y=rV(y,h.type,h.pendingProps,co),y!==null?(h.stateNode=y,Br=h,Rr=iD(y),co=!1,M=!0):M=!1),M||Ze(h)),ve(h),M=h.type,A=h.pendingProps,H=c!==null?c.memoizedProps:null,y=A.children,Iv(M,A)?y=null:H!==null&&Iv(M,H)&&(h.flags|=32),h.memoizedState!==null&&(M=oo(c,h,Sa,null,null,g),Go?xu._currentValue=M:xu._currentValue2=M),lm(c,h),fr(c,h,y,g),h.child;case 6:return c===null&&vn&&(gV(h.pendingProps,pr.current),(c=g=Rr)&&(g=aV(g,h.pendingProps,co),g!==null?(h.stateNode=g,Br=h,Rr=null,c=!0):c=!1),c||Ze(h)),null;case 13:return kC(c,h,g);case 4:return tt(h,h.stateNode.containerInfo),y=h.pendingProps,c===null?h.child=Su(h,null,y,g):fr(c,h,y,g),h.child;case 11:return UC(c,h,h.type,h.pendingProps,g);case 7:return fr(c,h,h.pendingProps,g),h.child;case 8:return fr(c,h,h.pendingProps.children,g),h.child;case 12:return fr(c,h,h.pendingProps.children,g),h.child;case 10:return y=h.pendingProps,Gl(h,h.type,y.value),fr(c,h,y.children,g),h.child;case 9:return M=h.type._context,y=h.pendingProps.children,fu(h),M=Mr(M),y=y(M),h.flags|=1,fr(c,h,y,g),h.child;case 14:return PC(c,h,h.type,h.pendingProps,g);case 15:return zC(c,h,h.type,h.pendingProps,g);case 19:return XC(c,h,g);case 22:return BC(c,h,g);case 24:return fu(h),y=Mr(xi),c===null?(M=YT(),M===null&&(M=Qn,A=qT(),M.pooledCache=A,A.refCount++,A!==null&&(M.pooledCacheLanes|=g),M=A),h.memoizedState={parent:y,cache:M},Tt(h),Gl(h,xi,M)):(c.lanes&g&&(vt(c,h),Le(h,null,null,g),me()),M=c.memoizedState,A=h.memoizedState,M.parent!==y?(M={parent:y,cache:y},h.memoizedState=M,h.lanes===0&&(h.memoizedState=h.updateQueue.baseState=M),Gl(h,xi,y)):(y=A.cache,Gl(h,xi,y),y!==M.cache&&XT(h,[xi],g,!0))),fr(c,h,h.pendingProps.children,g),h.child;case 29:throw h.pendingProps}throw Error(r(156,h.tag))}function Gl(c,h,g){Go?(T(Yv,h._currentValue),h._currentValue=g):(T(Yv,h._currentValue2),h._currentValue2=g)}function Fo(c){var h=Yv.current;Go?c._currentValue=h:c._currentValue2=h,_(Yv)}function WT(c,h,g){for(;c!==null;){var y=c.alternate;if((c.childLanes&h)!==h?(c.childLanes|=h,y!==null&&(y.childLanes|=h)):y!==null&&(y.childLanes&h)!==h&&(y.childLanes|=h),c===g)break;c=c.return}}function XT(c,h,g,y){var M=c.child;for(M!==null&&(M.return=c);M!==null;){var A=M.dependencies;if(A!==null){var H=M.child;A=A.firstContext;e:for(;A!==null;){var ee=A;A=M;for(var fe=0;feAm&&(h.flags|=128,y=!0,hm(M,!1),h.lanes=4194304)}else{if(!y)if(c=$r(A),c!==null){if(h.flags|=128,y=!0,c=c.updateQueue,h.updateQueue=c,wv(h,c),hm(M,!0),M.tail===null&&M.tailMode==="hidden"&&!A.alternate&&!vn)return vi(h),null}else 2*Ls()-M.renderingStartTime>Am&&g!==536870912&&(h.flags|=128,y=!0,hm(M,!1),h.lanes=4194304);M.isBackwards?(A.sibling=h.child,h.child=A):(c=M.last,c!==null?c.sibling=A:h.child=A,M.last=A)}return M.tail!==null?(h=M.tail,M.rendering=h,M.tail=h.sibling,M.renderingStartTime=Ls(),h.sibling=null,c=ji.current,T(ji,y?c&1|2:c&1),h):(vi(h),null);case 22:case 23:return er(h),ao(),y=h.memoizedState!==null,c!==null?c.memoizedState!==null!==y&&(h.flags|=8192):y&&(h.flags|=8192),y?g&536870912&&!(h.flags&128)&&(vi(h),h.subtreeFlags&6&&(h.flags|=8192)):vi(h),g=h.updateQueue,g!==null&&wv(h,g.retryQueue),g=null,c!==null&&c.memoizedState!==null&&c.memoizedState.cachePool!==null&&(g=c.memoizedState.cachePool.pool),y=null,h.memoizedState!==null&&h.memoizedState.cachePool!==null&&(y=h.memoizedState.cachePool.pool),y!==g&&(h.flags|=2048),c!==null&&_(Au),null;case 24:return g=null,c!==null&&(g=c.memoizedState.cache),h.memoizedState.cache!==g&&(h.flags|=2048),Fo(xi),vi(h),null;case 25:return null}throw Error(r(156,h.tag))}function qF(c,h){switch(nt(h),h.tag){case 1:return c=h.flags,c&65536?(h.flags=c&-65537|128,h):null;case 3:return Fo(xi),xt(),c=h.flags,c&65536&&!(c&128)?(h.flags=c&-65537|128,h):null;case 26:case 27:case 5:return we(h),null;case 13:if(er(h),c=h.memoizedState,c!==null&&c.dehydrated!==null){if(h.alternate===null)throw Error(r(340));ct()}return c=h.flags,c&65536?(h.flags=c&-65537|128,h):null;case 19:return _(ji),null;case 4:return xt(),null;case 10:return Fo(h.type),null;case 22:case 23:return er(h),ao(),c!==null&&_(Au),c=h.flags,c&65536?(h.flags=c&-65537|128,h):null;case 24:return Fo(xi),null;case 25:return null;default:return null}}function $C(c,h){switch(nt(h),h.tag){case 3:Fo(xi),xt();break;case 26:case 27:case 5:we(h);break;case 4:xt();break;case 13:er(h);break;case 19:_(ji);break;case 10:Fo(h.type);break;case 22:case 23:er(h),ao(),c!==null&&_(Au);break;case 24:Fo(xi)}}function dm(c,h){try{var g=h.updateQueue,y=g!==null?g.lastEffect:null;if(y!==null){var M=y.next;g=M;do{if((g.tag&c)===c){y=void 0;var A=g.create,H=g.inst;y=A(),H.destroy=y}g=g.next}while(g!==M)}}catch(ee){wn(h,h.return,ee)}}function kl(c,h,g){try{var y=h.updateQueue,M=y!==null?y.lastEffect:null;if(M!==null){var A=M.next;y=A;do{if((y.tag&c)===c){var H=y.inst,ee=H.destroy;if(ee!==void 0){H.destroy=void 0,M=h;var fe=g;try{ee()}catch(Ne){wn(M,fe,Ne)}}}y=y.next}while(y!==A)}}catch(Ne){wn(h,h.return,Ne)}}function e4(c){var h=c.updateQueue;if(h!==null){var g=c.stateNode;try{ke(h,g)}catch(y){wn(c,c.return,y)}}}function t4(c,h,g){g.props=du(c.type,c.memoizedProps),g.state=c.memoizedState;try{g.componentWillUnmount()}catch(y){wn(c,h,y)}}function pu(c,h){try{var g=c.ref;if(g!==null){var y=c.stateNode;switch(c.tag){case 26:case 27:case 5:var M=mm(y);break;default:M=y}typeof g=="function"?c.refCleanup=g(M):g.current=M}}catch(A){wn(c,h,A)}}function Ea(c,h){var g=c.ref,y=c.refCleanup;if(g!==null)if(typeof y=="function")try{y()}catch(M){wn(c,h,M)}finally{c.refCleanup=null,c=c.alternate,c!=null&&(c.refCleanup=null)}else if(typeof g=="function")try{g(null)}catch(M){wn(c,h,M)}else g.current=null}function n4(c){var h=c.type,g=c.memoizedProps,y=c.stateNode;try{FH(y,h,g,c)}catch(M){wn(c,c.return,M)}}function i4(c,h,g){try{HH(c.stateNode,c.type,g,h,c)}catch(y){wn(c,c.return,y)}}function r4(c){return c.tag===5||c.tag===3||(ts?c.tag===26:!1)||(wr?c.tag===27:!1)||c.tag===4}function KT(c){e:for(;;){for(;c.sibling===null;){if(c.return===null||r4(c.return))return null;c=c.return}for(c.sibling.return=c.return,c=c.sibling;c.tag!==5&&c.tag!==6&&(!wr||c.tag!==27)&&c.tag!==18;){if(c.flags&2||c.child===null||c.tag===4)continue e;c.child.return=c,c=c.child}if(!(c.flags&2))return c.stateNode}}function JT(c,h,g){var y=c.tag;if(y===5||y===6)c=c.stateNode,h?GH(g,c,h):zH(g,c);else if(!(y===4||wr&&y===27)&&(c=c.child,c!==null))for(JT(c,h,g),c=c.sibling;c!==null;)JT(c,h,g),c=c.sibling}function Rv(c,h,g){var y=c.tag;if(y===5||y===6)c=c.stateNode,h?VH(g,c,h):PH(g,c);else if(!(y===4||wr&&y===27)&&(c=c.child,c!==null))for(Rv(c,h,g),c=c.sibling;c!==null;)Rv(c,h,g),c=c.sibling}function a4(c,h,g){c=c.containerInfo;try{$4(c,g)}catch(y){wn(h,h.return,y)}}function YF(c,h){for(mH(c.containerInfo),nr=h;nr!==null;)if(c=nr,h=c.child,(c.subtreeFlags&1028)!==0&&h!==null)h.return=c,nr=h;else for(;nr!==null;){c=nr;var g=c.alternate;switch(h=c.flags,c.tag){case 0:break;case 11:case 15:break;case 1:if(h&1024&&g!==null){h=void 0;var y=c,M=g.memoizedProps;g=g.memoizedState;var A=y.stateNode;try{var H=du(y.type,M,y.elementType===y.type);h=A.getSnapshotBeforeUpdate(H,g),A.__reactInternalSnapshotBeforeUpdate=h}catch(ee){wn(y,y.return,ee)}}break;case 3:h&1024&&Ar&&ZH(c.stateNode.containerInfo);break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if(h&1024)throw Error(r(163))}if(h=c.sibling,h!==null){h.return=c.return,nr=h;break}nr=c.return}return H=SD,SD=!1,H}function s4(c,h,g){var y=g.flags;switch(g.tag){case 0:case 11:case 15:Ho(c,g),y&4&&dm(5,g);break;case 1:if(Ho(c,g),y&4)if(c=g.stateNode,h===null)try{c.componentDidMount()}catch(ee){wn(g,g.return,ee)}else{var M=du(g.type,h.memoizedProps);h=h.memoizedState;try{c.componentDidUpdate(M,h,c.__reactInternalSnapshotBeforeUpdate)}catch(ee){wn(g,g.return,ee)}}y&64&&e4(g),y&512&&pu(g,g.return);break;case 3:if(Ho(c,g),y&64&&(y=g.updateQueue,y!==null)){if(c=null,g.child!==null)switch(g.child.tag){case 27:case 5:c=mm(g.child.stateNode);break;case 1:c=g.child.stateNode}try{ke(y,c)}catch(ee){wn(g,g.return,ee)}}break;case 26:if(ts){Ho(c,g),y&512&&pu(g,g.return);break}case 27:case 5:Ho(c,g),h===null&&y&4&&n4(g),y&512&&pu(g,g.return);break;case 12:Ho(c,g);break;case 13:Ho(c,g),y&4&&l4(c,g);break;case 22:if(M=g.memoizedState!==null||qo,!M){h=h!==null&&h.memoizedState!==null||yi;var A=qo,H=yi;qo=M,(yi=h)&&!H?Wl(c,g,(g.subtreeFlags&8772)!==0):Ho(c,g),qo=A,yi=H}y&512&&(g.memoizedProps.mode==="manual"?pu(g,g.return):Ea(g,g.return));break;default:Ho(c,g)}}function o4(c){var h=c.alternate;h!==null&&(c.alternate=null,o4(h)),c.child=null,c.deletions=null,c.sibling=null,c.tag===5&&(h=c.stateNode,h!==null&&EH(h)),c.stateNode=null,c.return=null,c.dependencies=null,c.memoizedProps=null,c.memoizedState=null,c.pendingProps=null,c.stateNode=null,c.updateQueue=null}function Os(c,h,g){for(g=g.child;g!==null;)$T(c,h,g),g=g.sibling}function $T(c,h,g){if(Ra&&typeof Ra.onCommitFiberUnmount=="function")try{Ra.onCommitFiberUnmount(_m,g)}catch{}switch(g.tag){case 26:if(ts){yi||Ea(g,h),Os(c,h,g),g.memoizedState?lD(g.memoizedState):g.stateNode&&uD(g.stateNode);break}case 27:if(wr){yi||Ea(g,h);var y=Pi,M=Da;Pi=g.stateNode,Os(c,h,g),bV(g.stateNode),Pi=y,Da=M;break}case 5:yi||Ea(g,h);case 6:if(Ar){if(y=Pi,M=Da,Pi=null,Os(c,h,g),Pi=y,Da=M,Pi!==null)if(Da)try{WH(Pi,g.stateNode)}catch(A){wn(g,h,A)}else try{kH(Pi,g.stateNode)}catch(A){wn(g,h,A)}}else Os(c,h,g);break;case 18:Ar&&Pi!==null&&(Da?pV(Pi,g.stateNode):fV(Pi,g.stateNode));break;case 4:Ar?(y=Pi,M=Da,Pi=g.stateNode.containerInfo,Da=!0,Os(c,h,g),Pi=y,Da=M):(Zl&&a4(g.stateNode,g,K4()),Os(c,h,g));break;case 0:case 11:case 14:case 15:yi||kl(2,g,h),yi||kl(4,g,h),Os(c,h,g);break;case 1:yi||(Ea(g,h),y=g.stateNode,typeof y.componentWillUnmount=="function"&&t4(g,h,y)),Os(c,h,g);break;case 21:Os(c,h,g);break;case 22:yi||Ea(g,h),yi=(y=yi)||g.memoizedState!==null,Os(c,h,g),yi=y;break;default:Os(c,h,g)}}function l4(c,h){if(es&&h.memoizedState===null&&(c=h.alternate,c!==null&&(c=c.memoizedState,c!==null&&(c=c.dehydrated,c!==null))))try{dV(c)}catch(g){wn(h,h.return,g)}}function jF(c){switch(c.tag){case 13:case 19:var h=c.stateNode;return h===null&&(h=c.stateNode=new yD),h;case 22:return c=c.stateNode,h=c._retryCache,h===null&&(h=c._retryCache=new yD),h;default:throw Error(r(435,c.tag))}}function e2(c,h){var g=jF(c);h.forEach(function(y){var M=nH.bind(null,c,y);g.has(y)||(g.add(y),y.then(M,M))})}function ea(c,h){var g=h.deletions;if(g!==null)for(var y=0;y";case Zv:return":has("+(a2(c)||"")+")";case Qv:return'[role="'+c.value+'"]';case Jv:return'"'+c.value+'"';case Kv:return'[data-testname="'+c.value+'"]';default:throw Error(r(365))}}function g4(c,h){var g=[];c=[c,0];for(var y=0;yg?32:g;g=Vt.T;var M=_u();try{if(ta(y),Vt.T=null,Ru===null)var A=!1;else{y=j2,j2=null;var H=Ru,ee=wm;if(Ru=null,wm=0,Bn&6)throw Error(r(331));var fe=Bn;if(Bn|=4,p4(H.current),h4(H,H.current,ee,y),Bn=fe,Je(0,!1),Ra&&typeof Ra.onPostCommitFiberRoot=="function")try{Ra.onPostCommitFiberRoot(_m,H)}catch{}A=!0}return A}finally{ta(M),Vt.T=g,C4(c,h)}}return!1}function D4(c,h,g){h=ce(g,h),h=UT(c.stateNode,h,2),c=He(c,h,2),c!==null&&(z(c,2),$e(c))}function wn(c,h,g){if(c.tag===3)D4(c,c,g);else for(;h!==null;){if(h.tag===3){D4(h,c,g);break}else if(h.tag===1){var y=h.stateNode;if(typeof h.type.getDerivedStateFromError=="function"||typeof y.componentDidCatch=="function"&&(tc===null||!tc.has(y))){c=ce(g,c),g=LC(2),y=He(h,g,2),y!==null&&(IC(g,y,h,c),z(y,2),$e(y));break}}h=h.return}}function h2(c,h,g){var y=c.pingCache;if(y===null){y=c.pingCache=new FV;var M=new Set;y.set(h,M)}else M=y.get(h),M===void 0&&(M=new Set,y.set(h,M));M.has(g)||(k2=!0,M.add(g),c=eH.bind(null,c,h,g),h.then(c,c))}function eH(c,h,g){var y=c.pingCache;y!==null&&y.delete(h),c.pingedLanes|=c.suspendedLanes&g,c.warmLanes&=~g,Qn===c&&(dn&g)===g&&(Si===4||Si===3&&(dn&62914560)===dn&&300>Ls()-q2?!(Bn&2)&&dd(c,0):W2|=g,Ld===dn&&(Ld=0)),$e(c)}function N4(c,h){h===0&&(h=N()),c=Oe(c,h),c!==null&&(z(c,h),$e(c))}function tH(c){var h=c.memoizedState,g=0;h!==null&&(g=h.retryLane),N4(c,g)}function nH(c,h){var g=0;switch(c.tag){case 13:var y=c.stateNode,M=c.memoizedState;M!==null&&(g=M.retryLane);break;case 19:y=c.stateNode;break;case 22:y=c.stateNode._retryCache;break;default:throw Error(r(314))}y!==null&&y.delete(h),N4(c,g)}function iH(c,h){return zv(c,h)}function rH(c,h,g,y){this.tag=c,this.key=g,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=h,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=y,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function d2(c){return c=c.prototype,!(!c||!c.isReactComponent)}function ql(c,h){var g=c.alternate;return g===null?(g=t(c.tag,h,c.key,c.mode),g.elementType=c.elementType,g.type=c.type,g.stateNode=c.stateNode,g.alternate=c,c.alternate=g):(g.pendingProps=h,g.type=c.type,g.flags=0,g.subtreeFlags=0,g.deletions=null),g.flags=c.flags&31457280,g.childLanes=c.childLanes,g.lanes=c.lanes,g.child=c.child,g.memoizedProps=c.memoizedProps,g.memoizedState=c.memoizedState,g.updateQueue=c.updateQueue,h=c.dependencies,g.dependencies=h===null?null:{lanes:h.lanes,firstContext:h.firstContext},g.sibling=c.sibling,g.index=c.index,g.ref=c.ref,g.refCleanup=c.refCleanup,g}function O4(c,h){c.flags&=31457282;var g=c.alternate;return g===null?(c.childLanes=0,c.lanes=h,c.child=null,c.subtreeFlags=0,c.memoizedProps=null,c.memoizedState=null,c.updateQueue=null,c.dependencies=null,c.stateNode=null):(c.childLanes=g.childLanes,c.lanes=g.lanes,c.child=g.child,c.subtreeFlags=0,c.deletions=null,c.memoizedProps=g.memoizedProps,c.memoizedState=g.memoizedState,c.updateQueue=g.updateQueue,c.type=g.type,h=g.dependencies,c.dependencies=h===null?null:{lanes:h.lanes,firstContext:h.firstContext}),c}function Nv(c,h,g,y,M,A){var H=0;if(y=c,typeof c=="function")d2(c)&&(H=1);else if(typeof c=="string")H=ts&&wr?aD(c,g,pr.current)?26:fD(c)?27:5:ts?aD(c,g,pr.current)?26:5:wr&&fD(c)?27:5;else e:switch(c){case md:return vu(g.children,M,A,h);case F4:H=8,M|=24;break;case v2:return c=t(12,g,h,M|2),c.elementType=v2,c.lanes=A,c;case x2:return c=t(13,g,h,M),c.elementType=x2,c.lanes=A,c;case y2:return c=t(19,g,h,M),c.elementType=y2,c.lanes=A,c;case V4:return L4(g,M,A,h);default:if(typeof c=="object"&&c!==null)switch(c.$$typeof){case lH:case Yl:H=10;break e;case H4:H=9;break e;case _2:H=11;break e;case S2:H=14;break e;case jl:H=16,y=null;break e}H=29,g=Error(r(130,c===null?"null":typeof c,"")),y=null}return h=t(H,g,h,M),h.elementType=c,h.type=y,h.lanes=A,h}function vu(c,h,g,y){return c=t(7,c,y,h),c.lanes=g,c}function L4(c,h,g,y){c=t(22,c,y,h),c.elementType=V4,c.lanes=g;var M={_visibility:1,_pendingVisibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null,_current:null,detach:function(){var A=M._current;if(A===null)throw Error(r(456));if(!(M._pendingVisibility&2)){var H=Oe(A,2);H!==null&&(M._pendingVisibility|=2,zr(H,A,2))}},attach:function(){var A=M._current;if(A===null)throw Error(r(456));if(M._pendingVisibility&2){var H=Oe(A,2);H!==null&&(M._pendingVisibility&=-3,zr(H,A,2))}}};return c.stateNode=M,c}function f2(c,h,g){return c=t(6,c,null,h),c.lanes=g,c}function p2(c,h,g){return h=t(4,c.children!==null?c.children:[],c.key,h),h.lanes=g,h.stateNode={containerInfo:c.containerInfo,pendingChildren:null,implementation:c.implementation},h}function aH(c,h,g,y,M,A,H,ee){this.tag=1,this.containerInfo=c,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=M2,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=C(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.finishedLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=C(0),this.hiddenUpdates=C(null),this.identifierPrefix=y,this.onUncaughtError=M,this.onCaughtError=A,this.onRecoverableError=H,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=ee,this.incompleteTransitions=new Map}function I4(c,h,g,y,M,A,H,ee,fe,Ne,et,gt){return c=new aH(c,h,g,H,ee,fe,Ne,gt),h=1,A===!0&&(h|=24),A=t(3,null,null,h),c.current=A,A.stateNode=c,h=qT(),h.refCount++,c.pooledCache=h,h.refCount++,A.memoizedState={element:y,isDehydrated:g,cache:h},Tt(A),c}function U4(c){return c?(c=_d,c):_d}function P4(c){var h=c._reactInternals;if(h===void 0)throw typeof c.render=="function"?Error(r(188)):(c=Object.keys(c).join(","),Error(r(268,c)));return c=m(h),c=c!==null?v(c):null,c===null?null:mm(c.stateNode)}function z4(c,h,g,y,M,A){M=U4(M),y.context===null?y.context=M:y.pendingContext=M,y=Ue(h),y.payload={element:g},A=A===void 0?null:A,A!==null&&(y.callback=A),g=He(c,y,h),g!==null&&(zr(g,c,h),pt(g,c,h))}function B4(c,h){if(c=c.memoizedState,c!==null&&c.dehydrated!==null){var g=c.retryLane;c.retryLane=g!==0&&g=Ne&&A>=gt&&M<=et&&H<=_t){c.splice(h,1);break}else if(y!==Ne||g.width!==fe.width||_tH){if(!(A!==gt||g.height!==fe.height||etM)){Ne>y&&(fe.width+=Ne-y,fe.x=y),etA&&(fe.height+=gt-A,fe.y=A),_tg&&(g=ee)),ee ")+` + +No matching component was found for: + `)+c.join(" > ")}return null},nn.getPublicRootInstance=function(c){if(c=c.current,!c.child)return null;switch(c.child.tag){case 27:case 5:return mm(c.child.stateNode);default:return c.child.stateNode}},nn.injectIntoDevTools=function(){var c={bundleType:0,version:hH,rendererPackageName:dH,currentDispatcherRef:Vt,findFiberByHostInstance:Y4,reconcilerVersion:"19.0.0"};if(W4!==null&&(c.rendererConfig=W4),typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")c=!1;else{var h=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(h.isDisabled||!h.supportsFiber)c=!0;else{try{_m=h.inject(c),Ra=h}catch{}c=!!h.checkDCE}}return c},nn.isAlreadyRendering=function(){return!1},nn.observeVisibleRects=function(c,h,g,y){if(!gm)throw Error(r(363));c=s2(c,h);var M=UH(c,g,y).disconnect;return{disconnect:function(){M()}}},nn.shouldError=function(){return null},nn.shouldSuspend=function(){return!1},nn.startHostTransition=function(c,h,g,y){if(c.tag!==5)throw Error(r(476));var M=bC(c).queue;EC(c,M,h,gd,g===null?i:function(){var A=bC(c).next.queue;return om(c,A,{},Ma()),g(y)})},nn.updateContainer=function(c,h,g,y){var M=h.current,A=Ma();return z4(M,A,c,h,g,y),A},nn.updateContainerSync=function(c,h,g,y){return h.tag===0&&gu(),z4(h.current,2,c,h,g,y),2},nn},n.exports.default=n.exports,Object.defineProperty(n.exports,"__esModule",{value:!0})})(G7);var x$=G7.exports;V7.exports=x$;var y$=V7.exports;const S$=aS(y$);function OR(n,e,t){if(!n)return;if(t(n)===!0)return n;let i=e?n.return:n.child;for(;i;){const r=OR(i,e,t);if(r)return r;i=e?null:i.sibling}}function X7(n){try{return Object.defineProperties(n,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return n}}const LR=X7(ie.createContext(null));let q7=class extends ie.Component{render(){return ie.createElement(LR.Provider,{value:this._reactInternals},this.props.children)}};function Y7(){const n=ie.useContext(LR);if(n===null)throw new Error("its-fine: useFiber must be called within a !");const e=ie.useId();return ie.useMemo(()=>{for(const t of[n,n==null?void 0:n.alternate]){if(!t)continue;const i=OR(t,!1,r=>{let a=r.memoizedState;for(;a;){if(a.memoizedState===e)return!0;a=a.next}});if(i)return i}},[n,e])}const T$=Symbol.for("react.context"),E$=n=>n!==null&&typeof n=="object"&&"$$typeof"in n&&n.$$typeof===T$;function b$(){const n=Y7(),[e]=ie.useState(()=>new Map);e.clear();let t=n;for(;t;){const i=t.type;E$(i)&&i!==LR&&!e.has(i)&&e.set(i,ie.use(X7(i))),t=t.return}return e}function M$(){const n=b$();return ie.useMemo(()=>Array.from(n.keys()).reduce((e,t)=>i=>ie.createElement(e,null,ie.createElement(t.Provider,{...i,value:n.get(t)})),e=>ie.createElement(q7,{...e})),[n])}function j7(n){let e=n.root;for(;e.getState().previousRoot;)e=e.getState().previousRoot;return e}const Z7=n=>n&&n.isOrthographicCamera,A$=n=>n&&n.hasOwnProperty("current"),w$=n=>n!=null&&(typeof n=="string"||typeof n=="number"||n.isColor),uv=((n,e)=>typeof window<"u"&&(((n=window.document)==null?void 0:n.createElement)||((e=window.navigator)==null?void 0:e.product)==="ReactNative"))()?ie.useLayoutEffect:ie.useEffect;function Q7(n){const e=ie.useRef(n);return uv(()=>void(e.current=n),[n]),e}function R$(){const n=Y7(),e=M$();return ie.useMemo(()=>({children:t})=>{const r=!!OR(n,!0,a=>a.type===ie.StrictMode)?ie.StrictMode:ie.Fragment;return ot.jsx(r,{children:ot.jsx(e,{children:t})})},[n,e])}function C$({set:n}){return uv(()=>(n(new Promise(()=>null)),()=>n(!1)),[n]),null}const D$=(n=>(n=class extends ie.Component{constructor(...t){super(...t),this.state={error:!1}}componentDidCatch(t){this.props.set(t)}render(){return this.state.error?null:this.props.children}},n.getDerivedStateFromError=()=>({error:!0}),n))();function K7(n){var e;const t=typeof window<"u"?(e=window.devicePixelRatio)!=null?e:2:1;return Array.isArray(n)?Math.min(Math.max(n[0],t),n[1]):n}function rf(n){var e;return(e=n.__r3f)==null?void 0:e.root.getState()}const di={obj:n=>n===Object(n)&&!di.arr(n)&&typeof n!="function",fun:n=>typeof n=="function",str:n=>typeof n=="string",num:n=>typeof n=="number",boo:n=>typeof n=="boolean",und:n=>n===void 0,nul:n=>n===null,arr:n=>Array.isArray(n),equ(n,e,{arrays:t="shallow",objects:i="reference",strict:r=!0}={}){if(typeof n!=typeof e||!!n!=!!e)return!1;if(di.str(n)||di.num(n)||di.boo(n))return n===e;const a=di.obj(n);if(a&&i==="reference")return n===e;const s=di.arr(n);if(s&&t==="reference")return n===e;if((s||a)&&n===e)return!0;let o;for(o in n)if(!(o in e))return!1;if(a&&t==="shallow"&&i==="shallow"){for(o in r?e:n)if(!di.equ(n[o],e[o],{strict:r,objects:"reference"}))return!1}else for(o in r?e:n)if(n[o]!==e[o])return!1;if(di.und(o)){if(s&&n.length===0&&e.length===0||a&&Object.keys(n).length===0&&Object.keys(e).length===0)return!0;if(n!==e)return!1}return!0}};function N$(n){const e={nodes:{},materials:{},meshes:{}};return n&&n.traverse(t=>{t.name&&(e.nodes[t.name]=t),t.material&&!e.materials[t.material.name]&&(e.materials[t.material.name]=t.material),t.isMesh&&!e.meshes[t.name]&&(e.meshes[t.name]=t)}),e}function O$(n){n.type!=="Scene"&&(n.dispose==null||n.dispose());for(const e in n){const t=n[e];(t==null?void 0:t.type)!=="Scene"&&(t==null||t.dispose==null||t.dispose())}}const J7=["children","key","ref"];function L$(n){const e={};for(const t in n)J7.includes(t)||(e[t]=n[t]);return e}function Uy(n,e,t,i){const r=n;let a=r==null?void 0:r.__r3f;return a||(a={root:e,type:t,parent:null,children:[],props:L$(i),object:r,eventCount:0,handlers:{},isHidden:!1},r&&(r.__r3f=a)),a}function Ig(n,e){if(!e.includes("-"))return{root:n,key:e,target:n[e]};if(e in n)return{root:n,key:e,target:n[e]};let t=n;const i=e.split("-");for(const r of i){if(typeof t!="object"||t===null){if(t!==void 0){const a=i.slice(i.indexOf(r)).join("-");return{root:t,key:a,target:void 0}}return{root:n,key:e,target:void 0}}e=r,n=t,t=t[e]}return{root:n,key:e,target:t}}const wL=/-\d+$/;function Py(n,e){if(di.str(e.props.attach)){if(wL.test(e.props.attach)){const r=e.props.attach.replace(wL,""),{root:a,key:s}=Ig(n.object,r);Array.isArray(a[s])||(a[s]=[])}const{root:t,key:i}=Ig(n.object,e.props.attach);e.previousAttach=t[i],t[i]=e.object}else di.fun(e.props.attach)&&(e.previousAttach=e.props.attach(n.object,e.object))}function zy(n,e){if(di.str(e.props.attach)){const{root:t,key:i}=Ig(n.object,e.props.attach),r=e.previousAttach;r===void 0?delete t[i]:t[i]=r}else e.previousAttach==null||e.previousAttach(n.object,e.object);delete e.previousAttach}const K3=[...J7,"args","dispose","attach","object","onUpdate","dispose"],RL=new Map;function I$(n){let e=RL.get(n.constructor);try{e||(e=new n.constructor,RL.set(n.constructor,e))}catch{}return e}function U$(n,e){const t={};for(const i in e)if(!K3.includes(i)&&!di.equ(e[i],n.props[i])){t[i]=e[i];for(const r in e)r.startsWith(`${i}-`)&&(t[r]=e[r])}for(const i in n.props){if(K3.includes(i)||e.hasOwnProperty(i))continue;const{root:r,key:a}=Ig(n.object,i);if(r.constructor&&r.constructor.length===0){const s=I$(r);di.und(s)||(t[a]=s[a])}else t[a]=0}return t}const P$=["map","emissiveMap","sheenColorMap","specularColorMap","envMap"],z$=/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/;function wc(n,e){var t;const i=n.__r3f,r=i&&j7(i).getState(),a=i==null?void 0:i.eventCount;for(const o in e){let l=e[o];if(K3.includes(o))continue;if(i&&z$.test(o)){typeof l=="function"?i.handlers[o]=l:delete i.handlers[o],i.eventCount=Object.keys(i.handlers).length;continue}if(l===void 0)continue;let{root:u,key:d,target:f}=Ig(n,o);if(f===void 0&&(typeof u!="object"||u===null))throw Error(`R3F: Cannot set "${o}". Ensure it is an object before setting "${d}".`);if(f instanceof Ap&&l instanceof Ap)f.mask=l.mask;else if(f instanceof Ye&&w$(l))f.set(l);else if(f!==null&&typeof f=="object"&&typeof f.set=="function"&&typeof f.copy=="function"&&l!=null&&l.constructor&&f.constructor===l.constructor)f.copy(l);else if(f!==null&&typeof f=="object"&&typeof f.set=="function"&&Array.isArray(l))typeof f.fromArray=="function"?f.fromArray(l):f.set(...l);else if(f!==null&&typeof f=="object"&&typeof f.set=="function"&&typeof l=="number")typeof f.setScalar=="function"?f.setScalar(l):f.set(l);else{var s;u[d]=l,r&&!r.linear&&P$.includes(d)&&(s=u[d])!=null&&s.isTexture&&u[d].format===ai&&u[d].type===Ni&&(u[d].colorSpace=mn)}}if(i!=null&&i.parent&&r!=null&&r.internal&&(t=i.object)!=null&&t.isObject3D&&a!==i.eventCount){const o=i.object,l=r.internal.interaction.indexOf(o);l>-1&&r.internal.interaction.splice(l,1),i.eventCount&&o.raycast!==null&&r.internal.interaction.push(o)}return i&&i.props.attach===void 0&&(i.object.isBufferGeometry?i.props.attach="geometry":i.object.isMaterial&&(i.props.attach="material")),i&&$p(i),n}function $p(n){var e;if(!n.parent)return;n.props.onUpdate==null||n.props.onUpdate(n.object);const t=(e=n.root)==null||e.getState==null?void 0:e.getState();t&&t.internal.frames===0&&t.invalidate()}function B$(n,e){n.manual||(Z7(n)?(n.left=e.width/-2,n.right=e.width/2,n.top=e.height/2,n.bottom=e.height/-2):n.aspect=e.width/e.height,n.updateProjectionMatrix())}const kr=n=>n==null?void 0:n.isObject3D;function ox(n){return(n.eventObject||n.object).uuid+"/"+n.index+n.instanceId}function $7(n,e,t,i){const r=t.get(e);r&&(t.delete(e),t.size===0&&(n.delete(i),r.target.releasePointerCapture(i)))}function F$(n,e){const{internal:t}=n.getState();t.interaction=t.interaction.filter(i=>i!==e),t.initialHits=t.initialHits.filter(i=>i!==e),t.hovered.forEach((i,r)=>{(i.eventObject===e||i.object===e)&&t.hovered.delete(r)}),t.capturedMap.forEach((i,r)=>{$7(t.capturedMap,e,i,r)})}function H$(n){function e(l){const{internal:u}=n.getState(),d=l.offsetX-u.initialClick[0],f=l.offsetY-u.initialClick[1];return Math.round(Math.sqrt(d*d+f*f))}function t(l){return l.filter(u=>["Move","Over","Enter","Out","Leave"].some(d=>{var f;return(f=u.__r3f)==null?void 0:f.handlers["onPointer"+d]}))}function i(l,u){const d=n.getState(),f=new Set,p=[],m=u?u(d.internal.interaction):d.internal.interaction;for(let _=0;_{const E=rf(_.object),b=rf(T.object);return!E||!b?_.distance-T.distance:b.events.priority-E.events.priority||_.distance-T.distance}).filter(_=>{const T=ox(_);return f.has(T)?!1:(f.add(T),!0)});d.events.filter&&(x=d.events.filter(x,d));for(const _ of x){let T=_.object;for(;T;){var S;(S=T.__r3f)!=null&&S.eventCount&&p.push({..._,eventObject:T}),T=T.parent}}if("pointerId"in l&&d.internal.capturedMap.has(l.pointerId))for(let _ of d.internal.capturedMap.get(l.pointerId).values())f.has(ox(_.intersection))||p.push(_.intersection);return p}function r(l,u,d,f){if(l.length){const p={stopped:!1};for(const m of l){let v=rf(m.object);if(v||m.object.traverseAncestors(x=>{const S=rf(x);if(S)return v=S,!1}),v){const{raycaster:x,pointer:S,camera:_,internal:T}=v,E=new D(S.x,S.y,0).unproject(_),b=N=>{var C,z;return(C=(z=T.capturedMap.get(N))==null?void 0:z.has(m.eventObject))!=null?C:!1},R=N=>{const C={intersection:m,target:u.target};T.capturedMap.has(N)?T.capturedMap.get(N).set(m.eventObject,C):T.capturedMap.set(N,new Map([[m.eventObject,C]])),u.target.setPointerCapture(N)},w=N=>{const C=T.capturedMap.get(N);C&&$7(T.capturedMap,m.eventObject,C,N)};let L={};for(let N in u){let C=u[N];typeof C!="function"&&(L[N]=C)}let U={...m,...L,pointer:S,intersections:l,stopped:p.stopped,delta:d,unprojectedPoint:E,ray:x.ray,camera:_,stopPropagation(){const N="pointerId"in u&&T.capturedMap.get(u.pointerId);if((!N||N.has(m.eventObject))&&(U.stopped=p.stopped=!0,T.hovered.size&&Array.from(T.hovered.values()).find(C=>C.eventObject===m.eventObject))){const C=l.slice(0,l.indexOf(m));a([...C,m])}},target:{hasPointerCapture:b,setPointerCapture:R,releasePointerCapture:w},currentTarget:{hasPointerCapture:b,setPointerCapture:R,releasePointerCapture:w},nativeEvent:u};if(f(U),p.stopped===!0)break}}}return l}function a(l){const{internal:u}=n.getState();for(const d of u.hovered.values())if(!l.length||!l.find(f=>f.object===d.object&&f.index===d.index&&f.instanceId===d.instanceId)){const p=d.eventObject.__r3f;if(u.hovered.delete(ox(d)),p!=null&&p.eventCount){const m=p.handlers,v={...d,intersections:l};m.onPointerOut==null||m.onPointerOut(v),m.onPointerLeave==null||m.onPointerLeave(v)}}}function s(l,u){for(let d=0;da([]);case"onLostPointerCapture":return u=>{const{internal:d}=n.getState();"pointerId"in u&&d.capturedMap.has(u.pointerId)&&requestAnimationFrame(()=>{d.capturedMap.has(u.pointerId)&&(d.capturedMap.delete(u.pointerId),a([]))})}}return function(d){const{onPointerMissed:f,internal:p}=n.getState();p.lastEvent.current=d;const m=l==="onPointerMove",v=l==="onClick"||l==="onContextMenu"||l==="onDoubleClick",S=i(d,m?t:void 0),_=v?e(d):0;l==="onPointerDown"&&(p.initialClick=[d.offsetX,d.offsetY],p.initialHits=S.map(E=>E.eventObject)),v&&!S.length&&_<=2&&(s(d,p.interaction),f&&f(d)),m&&a(S);function T(E){const b=E.eventObject,R=b.__r3f;if(!(R!=null&&R.eventCount))return;const w=R.handlers;if(m){if(w.onPointerOver||w.onPointerEnter||w.onPointerOut||w.onPointerLeave){const L=ox(E),U=p.hovered.get(L);U?U.stopped&&E.stopPropagation():(p.hovered.set(L,E),w.onPointerOver==null||w.onPointerOver(E),w.onPointerEnter==null||w.onPointerEnter(E))}w.onPointerMove==null||w.onPointerMove(E)}else{const L=w[l];L?(!v||p.initialHits.includes(b))&&(s(d,p.interaction.filter(U=>!p.initialHits.includes(U))),L(E)):v&&p.initialHits.includes(b)&&s(d,p.interaction.filter(U=>!p.initialHits.includes(U)))}}r(S,d,_,T)}}return{handlePointer:o}}const CL=n=>!!(n!=null&&n.render),ez=ie.createContext(null),V$=(n,e)=>{const t=p$((o,l)=>{const u=new D,d=new D,f=new D;function p(_=l().camera,T=d,E=l().size){const{width:b,height:R,top:w,left:L}=E,U=b/R;T.isVector3?f.copy(T):f.set(...T);const N=_.getWorldPosition(u).distanceTo(f);if(Z7(_))return{width:b/_.zoom,height:R/_.zoom,top:w,left:L,factor:1,distance:N,aspect:U};{const C=_.fov*Math.PI/180,z=2*Math.tan(C/2)*N,W=z*(b/R);return{width:W,height:z,top:w,left:L,factor:b/W,distance:N,aspect:U}}}let m;const v=_=>o(T=>({performance:{...T.performance,current:_}})),x=new re;return{set:o,get:l,gl:null,camera:null,raycaster:null,events:{priority:1,enabled:!0,connected:!1},scene:null,xr:null,invalidate:(_=1)=>n(l(),_),advance:(_,T)=>e(_,T,l()),legacy:!1,linear:!1,flat:!1,controls:null,clock:new cv,pointer:x,mouse:x,frameloop:"always",onPointerMissed:void 0,performance:{current:1,min:.5,max:1,debounce:200,regress:()=>{const _=l();m&&clearTimeout(m),_.performance.current!==_.performance.min&&v(_.performance.min),m=setTimeout(()=>v(l().performance.max),_.performance.debounce)}},size:{width:0,height:0,top:0,left:0},viewport:{initialDpr:0,dpr:0,width:0,height:0,top:0,left:0,aspect:0,distance:0,factor:0,getCurrentViewport:p},setEvents:_=>o(T=>({...T,events:{...T.events,..._}})),setSize:(_,T,E=0,b=0)=>{const R=l().camera,w={width:_,height:T,top:E,left:b};o(L=>({size:w,viewport:{...L.viewport,...p(R,d,w)}}))},setDpr:_=>o(T=>{const E=K7(_);return{viewport:{...T.viewport,dpr:E,initialDpr:T.viewport.initialDpr||E}}}),setFrameloop:(_="always")=>{const T=l().clock;T.stop(),T.elapsedTime=0,_!=="never"&&(T.start(),T.elapsedTime=0),o(()=>({frameloop:_}))},previousRoot:void 0,internal:{interaction:[],hovered:new Map,subscribers:[],initialClick:[0,0],initialHits:[],capturedMap:new Map,lastEvent:ie.createRef(),active:!1,frames:0,priority:0,subscribe:(_,T,E)=>{const b=l().internal;return b.priority=b.priority+(T>0?1:0),b.subscribers.push({ref:_,priority:T,store:E}),b.subscribers=b.subscribers.sort((R,w)=>R.priority-w.priority),()=>{const R=l().internal;R!=null&&R.subscribers&&(R.priority=R.priority-(T>0?1:0),R.subscribers=R.subscribers.filter(w=>w.ref!==_))}}}}}),i=t.getState();let r=i.size,a=i.viewport.dpr,s=i.camera;return t.subscribe(()=>{const{camera:o,size:l,viewport:u,gl:d,set:f}=t.getState();if(l.width!==r.width||l.height!==r.height||u.dpr!==a){r=l,a=u.dpr,B$(o,l),u.dpr>0&&d.setPixelRatio(u.dpr);const p=typeof HTMLCanvasElement<"u"&&d.domElement instanceof HTMLCanvasElement;d.setSize(l.width,l.height,p)}o!==s&&(s=o,f(p=>({viewport:{...p.viewport,...p.viewport.getCurrentViewport(o)}})))}),t.subscribe(o=>n(o)),t};function tz(){const n=ie.useContext(ez);if(!n)throw new Error("R3F: Hooks can only be used within the Canvas component!");return n}function pn(n=t=>t,e){return tz()(n,e)}function _a(n,e=0){const t=tz(),i=t.getState().internal.subscribe,r=Q7(n);return uv(()=>i(r,e,t),[e,i,t]),null}const DL=new WeakMap,G$=n=>{var e;return typeof n=="function"&&(n==null||(e=n.prototype)==null?void 0:e.constructor)===n};function nz(n,e){return function(t,...i){let r;return G$(t)?(r=DL.get(t),r||(r=new t,DL.set(t,r))):r=t,n&&n(r),Promise.all(i.map(a=>new Promise((s,o)=>r.load(a,l=>{kr(l==null?void 0:l.scene)&&Object.assign(l,N$(l.scene)),s(l)},e,l=>o(new Error(`Could not load ${a}: ${l==null?void 0:l.message}`))))))}}function By(n,e,t,i){const r=Array.isArray(e)?e:[e],a=g$(nz(t,i),[n,...r],{equal:di.equ});return Array.isArray(e)?a:a[0]}By.preload=function(n,e,t){const i=Array.isArray(e)?e:[e];return v$(nz(t),[n,...i])};By.clear=function(n,e){const t=Array.isArray(e)?e:[e];return _$([n,...t])};function k$(n){const e=S$(n);return e.injectIntoDevTools({bundleType:0,rendererPackageName:"@react-three/fiber",version:ie.version}),e}const iz=0,Op={},W$=/^three(?=[A-Z])/,dT=n=>`${n[0].toUpperCase()}${n.slice(1)}`;let X$=0;const q$=n=>typeof n=="function";function rz(n){if(q$(n)){const e=`${X$++}`;return Op[e]=n,e}else Object.assign(Op,n)}function az(n,e){const t=dT(n),i=Op[t];if(n!=="primitive"&&!i)throw new Error(`R3F: ${t} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`);if(n==="primitive"&&!e.object)throw new Error("R3F: Primitives without 'object' are invalid!");if(e.args!==void 0&&!Array.isArray(e.args))throw new Error("R3F: The args prop must be an array!")}function Y$(n,e,t){var i;return n=dT(n)in Op?n:n.replace(W$,""),az(n,e),n==="primitive"&&(i=e.object)!=null&&i.__r3f&&delete e.object.__r3f,Uy(e.object,t,n,e)}function j$(n){if(!n.isHidden){var e;n.props.attach&&(e=n.parent)!=null&&e.object?zy(n.parent,n):kr(n.object)&&(n.object.visible=!1),n.isHidden=!0,$p(n)}}function sz(n){if(n.isHidden){var e;n.props.attach&&(e=n.parent)!=null&&e.object?Py(n.parent,n):kr(n.object)&&n.props.visible!==!1&&(n.object.visible=!0),n.isHidden=!1,$p(n)}}function IR(n,e,t){const i=e.root.getState();if(!(!n.parent&&n.object!==i.scene)){if(!e.object){var r,a;const s=Op[dT(e.type)];e.object=(r=e.props.object)!=null?r:new s(...(a=e.props.args)!=null?a:[]),e.object.__r3f=e}if(wc(e.object,e.props),e.props.attach)Py(n,e);else if(kr(e.object)&&kr(n.object)){const s=n.object.children.indexOf(t==null?void 0:t.object);if(t&&s!==-1){const o=n.object.children.indexOf(e.object);if(o!==-1){n.object.children.splice(o,1);const l=o{try{n.dispose()}catch{}};typeof IS_REACT_ACT_ENVIRONMENT<"u"?e():Q3.unstable_scheduleCallback(Q3.unstable_IdlePriority,e)}}function J3(n,e,t){if(!e)return;e.parent=null;const i=n.children.indexOf(e);i!==-1&&n.children.splice(i,1),e.props.attach?zy(n,e):kr(e.object)&&kr(n.object)&&(n.object.remove(e.object),F$(j7(e),e.object));const r=e.props.dispose!==null&&t!==!1;for(let a=e.children.length-1;a>=0;a--){const s=e.children[a];J3(e,s,r)}e.children.length=0,delete e.object.__r3f,r&&e.type!=="primitive"&&e.object.type!=="Scene"&&oz(e.object),t===void 0&&$p(e)}function Z$(n,e){for(const t of[n,n.alternate])if(t!==null)if(typeof t.ref=="function"){t.refCleanup==null||t.refCleanup();const i=t.ref(e);typeof i=="function"&&(t.refCleanup=i)}else t.ref&&(t.ref.current=e)}const h1=[];function Q$(){for(const[t]of h1){const i=t.parent;if(i){t.props.attach?zy(i,t):kr(t.object)&&kr(i.object)&&i.object.remove(t.object);for(const r of t.children)r.props.attach?zy(t,r):kr(r.object)&&kr(t.object)&&t.object.remove(r.object)}t.isHidden&&sz(t),t.object.__r3f&&delete t.object.__r3f,t.type!=="primitive"&&oz(t.object)}for(const[t,i,r]of h1){t.props=i;const a=t.parent;if(a){var n,e;const s=Op[dT(t.type)];t.object=(n=t.props.object)!=null?n:new s(...(e=t.props.args)!=null?e:[]),t.object.__r3f=t,Z$(r,t.object),wc(t.object,t.props),t.props.attach?Py(a,t):kr(t.object)&&kr(a.object)&&a.object.add(t.object);for(const o of t.children)o.props.attach?Py(t,o):kr(o.object)&&kr(t.object)&&t.object.add(o.object);$p(t)}}h1.length=0}const bb=()=>{},OL={};let lx=iz;const K$=0,J$=4,$3=k$({isPrimaryRenderer:!1,warnsIfNotActing:!1,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,createInstance:Y$,removeChild:J3,appendChild:Eb,appendInitialChild:Eb,insertBefore:NL,appendChildToContainer(n,e){const t=n.getState().scene.__r3f;!e||!t||Eb(t,e)},removeChildFromContainer(n,e){const t=n.getState().scene.__r3f;!e||!t||J3(t,e)},insertInContainerBefore(n,e,t){const i=n.getState().scene.__r3f;!e||!t||!i||NL(i,e,t)},getRootHostContext:()=>OL,getChildHostContext:()=>OL,commitUpdate(n,e,t,i,r){var a,s,o;az(e,i);let l=!1;if((n.type==="primitive"&&t.object!==i.object||((a=i.args)==null?void 0:a.length)!==((s=t.args)==null?void 0:s.length)||(o=i.args)!=null&&o.some((d,f)=>{var p;return d!==((p=t.args)==null?void 0:p[f])}))&&(l=!0),l)h1.push([n,{...i},r]);else{const d=U$(n,i);Object.keys(d).length&&(Object.assign(n.props,d),wc(n.object,d))}(r.sibling===null||(r.flags&J$)===K$)&&Q$()},finalizeInitialChildren:()=>!1,commitMount(){},getPublicInstance:n=>n==null?void 0:n.object,prepareForCommit:()=>null,preparePortalMount:n=>Uy(n.getState().scene,n,"",{}),resetAfterCommit:()=>{},shouldSetTextContent:()=>!1,clearContainer:()=>!1,hideInstance:j$,unhideInstance:sz,createTextInstance:bb,hideTextInstance:bb,unhideTextInstance:bb,scheduleTimeout:typeof setTimeout=="function"?setTimeout:void 0,cancelTimeout:typeof clearTimeout=="function"?clearTimeout:void 0,noTimeout:-1,getInstanceFromNode:()=>null,beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},detachDeletedInstance(){},prepareScopeUpdate(){},getInstanceFromScope:()=>null,shouldAttemptEagerTransition:()=>!1,trackSchedulerEvent:()=>{},resolveEventType:()=>null,resolveEventTimeStamp:()=>-1.1,requestPostPaintCallback(){},maySuspendCommit:()=>!1,preloadInstance:()=>!0,startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady:()=>null,NotPendingTransition:null,HostTransitionContext:ie.createContext(null),setCurrentUpdatePriority(n){lx=n},getCurrentUpdatePriority(){return lx},resolveUpdatePriority(){var n;if(lx!==iz)return lx;switch(typeof window<"u"&&((n=window.event)==null?void 0:n.type)){case"click":case"contextmenu":case"dblclick":case"pointercancel":case"pointerdown":case"pointerup":return o1.DiscreteEventPriority;case"pointermove":case"pointerout":case"pointerover":case"pointerenter":case"pointerleave":case"wheel":return o1.ContinuousEventPriority;default:return o1.DefaultEventPriority}},resetFormInstance(){}}),Gh=new Map,af={objects:"shallow",strict:!1};function $$(n,e){if(!e&&typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement&&n.parentElement){const{width:t,height:i,top:r,left:a}=n.parentElement.getBoundingClientRect();return{width:t,height:i,top:r,left:a}}else if(!e&&typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas)return{width:n.width,height:n.height,top:0,left:0};return{width:0,height:0,top:0,left:0,...e}}function eee(n){const e=Gh.get(n),t=e==null?void 0:e.fiber,i=e==null?void 0:e.store;e&&console.warn("R3F.createRoot should only be called once!");const r=typeof reportError=="function"?reportError:console.error,a=i||V$(nA,IL),s=t||$3.createContainer(a,o1.ConcurrentRoot,null,!1,null,"",r,r,r,null);e||Gh.set(n,{fiber:s,store:a});let o,l,u=!1,d=null;return{async configure(f={}){let p;d=new Promise(De=>p=De);let{gl:m,size:v,scene:x,events:S,onCreated:_,shadows:T=!1,linear:E=!1,flat:b=!1,legacy:R=!1,orthographic:w=!1,frameloop:L="always",dpr:U=[1,2],performance:N,raycaster:C,camera:z,onPointerMissed:W}=f,K=a.getState(),oe=K.gl;if(!K.gl){const De={canvas:n,powerPreference:"high-performance",antialias:!0,alpha:!0},Xe=typeof m=="function"?await m(De):m;CL(Xe)?oe=Xe:oe=new uT({...De,...m}),K.set({gl:oe})}let ae=K.raycaster;ae||K.set({raycaster:ae=new sT});const{params:X,...te}=C||{};if(di.equ(te,ae,af)||wc(ae,{...te}),di.equ(X,ae.params,af)||wc(ae,{params:{...ae.params,...X}}),!K.camera||K.camera===l&&!di.equ(l,z,af)){l=z;const De=z==null?void 0:z.isCamera,Xe=De?z:w?new Za(0,0,0,0,.1,1e3):new si(75,0,.1,1e3);De||(Xe.position.z=5,z&&(wc(Xe,z),Xe.manual||("aspect"in z||"left"in z||"right"in z||"bottom"in z||"top"in z)&&(Xe.manual=!0,Xe.updateProjectionMatrix())),!K.camera&&!(z!=null&&z.rotation)&&Xe.lookAt(0,0,0)),K.set({camera:Xe}),ae.camera=Xe}if(!K.scene){let De;x!=null&&x.isScene?(De=x,Uy(De,a,"",{})):(De=new Rp,Uy(De,a,"",{}),x&&wc(De,x)),K.set({scene:De})}S&&!K.events.handlers&&K.set({events:S(a)});const Q=$$(n,v);if(di.equ(Q,K.size,af)||K.setSize(Q.width,Q.height,Q.top,Q.left),U&&K.viewport.dpr!==K7(U)&&K.setDpr(U),K.frameloop!==L&&K.setFrameloop(L),K.onPointerMissed||K.set({onPointerMissed:W}),N&&!di.equ(N,K.performance,af)&&K.set(De=>({performance:{...De.performance,...N}})),!K.xr){var ce;const De=(tt,xt)=>{const ve=a.getState();ve.frameloop!=="never"&&IL(tt,!0,ve,xt)},Xe=()=>{const tt=a.getState();tt.gl.xr.enabled=tt.gl.xr.isPresenting,tt.gl.xr.setAnimationLoop(tt.gl.xr.isPresenting?De:null),tt.gl.xr.isPresenting||nA(tt)},nt={connect(){const tt=a.getState().gl;tt.xr.addEventListener("sessionstart",Xe),tt.xr.addEventListener("sessionend",Xe)},disconnect(){const tt=a.getState().gl;tt.xr.removeEventListener("sessionstart",Xe),tt.xr.removeEventListener("sessionend",Xe)}};typeof((ce=oe.xr)==null?void 0:ce.addEventListener)=="function"&&nt.connect(),K.set({xr:nt})}if(oe.shadowMap){const De=oe.shadowMap.enabled,Xe=oe.shadowMap.type;if(oe.shadowMap.enabled=!!T,di.boo(T))oe.shadowMap.type=Z0;else if(di.str(T)){var se;const nt={basic:W8,percentage:MS,soft:Z0,variance:Xs};oe.shadowMap.type=(se=nt[T])!=null?se:Z0}else di.obj(T)&&Object.assign(oe.shadowMap,T);(De!==oe.shadowMap.enabled||Xe!==oe.shadowMap.type)&&(oe.shadowMap.needsUpdate=!0)}return tn.enabled=!R,u||(oe.outputColorSpace=E?Xn:mn,oe.toneMapping=b?As:jw),K.legacy!==R&&K.set(()=>({legacy:R})),K.linear!==E&&K.set(()=>({linear:E})),K.flat!==b&&K.set(()=>({flat:b})),m&&!di.fun(m)&&!CL(m)&&!di.equ(m,oe,af)&&wc(oe,m),o=_,u=!0,p(),this},render(f){return!u&&!d&&this.configure(),d.then(()=>{$3.updateContainer(ot.jsx(tee,{store:a,children:f,onCreated:o,rootElement:n}),s,null,()=>{})}),a},unmount(){lz(n)}}}function tee({store:n,children:e,onCreated:t,rootElement:i}){return uv(()=>{const r=n.getState();r.set(a=>({internal:{...a.internal,active:!0}})),t&&t(r),n.getState().events.connected||r.events.connect==null||r.events.connect(i)},[]),ot.jsx(ez.Provider,{value:n,children:e})}function lz(n,e){const t=Gh.get(n),i=t==null?void 0:t.fiber;if(i){const r=t==null?void 0:t.store.getState();r&&(r.internal.active=!1),$3.updateContainer(null,i,null,()=>{r&&setTimeout(()=>{try{var a,s,o,l;r.events.disconnect==null||r.events.disconnect(),(a=r.gl)==null||(s=a.renderLists)==null||s.dispose==null||s.dispose(),(o=r.gl)==null||o.forceContextLoss==null||o.forceContextLoss(),(l=r.gl)!=null&&l.xr&&r.xr.disconnect(),O$(r.scene),Gh.delete(n)}catch{}},500)})}}const nee=new Set,iee=new Set,ree=new Set;function Mb(n,e){if(n.size)for(const{callback:t}of n.values())t(e)}function ig(n,e){switch(n){case"before":return Mb(nee,e);case"after":return Mb(iee,e);case"tail":return Mb(ree,e)}}let Ab,wb;function eA(n,e,t){let i=e.clock.getDelta();e.frameloop==="never"&&typeof n=="number"&&(i=n-e.clock.elapsedTime,e.clock.oldTime=e.clock.elapsedTime,e.clock.elapsedTime=n),Ab=e.internal.subscribers;for(let r=0;r0)&&!((e=sf.gl.xr)!=null&&e.isPresenting)&&(Rb+=eA(n,sf))}if(tA=!1,ig("after",n),Rb===0)return ig("tail",n),Fy=!1,cancelAnimationFrame(LL)}function nA(n,e=1){var t;if(!n)return Gh.forEach(i=>nA(i.store.getState(),e));(t=n.gl.xr)!=null&&t.isPresenting||!n.internal.active||n.frameloop==="never"||(e>1?n.internal.frames=Math.min(60,n.internal.frames+e):tA?n.internal.frames=2:n.internal.frames=1,Fy||(Fy=!0,requestAnimationFrame(cz)))}function IL(n,e=!0,t,i){if(e&&ig("before",n),t)eA(n,t,i);else for(const r of Gh.values())eA(n,r.store.getState());e&&ig("after",n)}const Cb={onClick:["click",!1],onContextMenu:["contextmenu",!1],onDoubleClick:["dblclick",!1],onWheel:["wheel",!0],onPointerDown:["pointerdown",!0],onPointerUp:["pointerup",!0],onPointerLeave:["pointerleave",!0],onPointerMove:["pointermove",!0],onPointerCancel:["pointercancel",!0],onLostPointerCapture:["lostpointercapture",!0]};function aee(n){const{handlePointer:e}=H$(n);return{priority:1,enabled:!0,compute(t,i,r){i.pointer.set(t.offsetX/i.size.width*2-1,-(t.offsetY/i.size.height)*2+1),i.raycaster.setFromCamera(i.pointer,i.camera)},connected:void 0,handlers:Object.keys(Cb).reduce((t,i)=>({...t,[i]:e(i)}),{}),update:()=>{var t;const{events:i,internal:r}=n.getState();(t=r.lastEvent)!=null&&t.current&&i.handlers&&i.handlers.onPointerMove(r.lastEvent.current)},connect:t=>{const{set:i,events:r}=n.getState();if(r.disconnect==null||r.disconnect(),i(a=>({events:{...a.events,connected:t}})),r.handlers)for(const a in r.handlers){const s=r.handlers[a],[o,l]=Cb[a];t.addEventListener(o,s,{passive:l})}},disconnect:()=>{const{set:t,events:i}=n.getState();if(i.connected){if(i.handlers)for(const r in i.handlers){const a=i.handlers[r],[s]=Cb[r];i.connected.removeEventListener(s,a)}t(r=>({events:{...r.events,connected:void 0}}))}}}}function UL(n,e){let t;return(...i)=>{window.clearTimeout(t),t=window.setTimeout(()=>n(...i),e)}}function see({debounce:n,scroll:e,polyfill:t,offsetSize:i}={debounce:0,scroll:!1,offsetSize:!1}){const r=t||(typeof window>"u"?class{}:window.ResizeObserver);if(!r)throw new Error("This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills");const[a,s]=ie.useState({left:0,top:0,width:0,height:0,bottom:0,right:0,x:0,y:0}),o=ie.useRef({element:null,scrollContainers:null,resizeObserver:null,lastBounds:a,orientationHandler:null}),l=n?typeof n=="number"?n:n.scroll:null,u=n?typeof n=="number"?n:n.resize:null,d=ie.useRef(!1);ie.useEffect(()=>(d.current=!0,()=>void(d.current=!1)));const[f,p,m]=ie.useMemo(()=>{const _=()=>{if(!o.current.element)return;const{left:T,top:E,width:b,height:R,bottom:w,right:L,x:U,y:N}=o.current.element.getBoundingClientRect(),C={left:T,top:E,width:b,height:R,bottom:w,right:L,x:U,y:N};o.current.element instanceof HTMLElement&&i&&(C.height=o.current.element.offsetHeight,C.width=o.current.element.offsetWidth),Object.freeze(C),d.current&&!uee(o.current.lastBounds,C)&&s(o.current.lastBounds=C)};return[_,u?UL(_,u):_,l?UL(_,l):_]},[s,i,l,u]);function v(){o.current.scrollContainers&&(o.current.scrollContainers.forEach(_=>_.removeEventListener("scroll",m,!0)),o.current.scrollContainers=null),o.current.resizeObserver&&(o.current.resizeObserver.disconnect(),o.current.resizeObserver=null),o.current.orientationHandler&&("orientation"in screen&&"removeEventListener"in screen.orientation?screen.orientation.removeEventListener("change",o.current.orientationHandler):"onorientationchange"in window&&window.removeEventListener("orientationchange",o.current.orientationHandler))}function x(){o.current.element&&(o.current.resizeObserver=new r(m),o.current.resizeObserver.observe(o.current.element),e&&o.current.scrollContainers&&o.current.scrollContainers.forEach(_=>_.addEventListener("scroll",m,{capture:!0,passive:!0})),o.current.orientationHandler=()=>{m()},"orientation"in screen&&"addEventListener"in screen.orientation?screen.orientation.addEventListener("change",o.current.orientationHandler):"onorientationchange"in window&&window.addEventListener("orientationchange",o.current.orientationHandler))}const S=_=>{!_||_===o.current.element||(v(),o.current.element=_,o.current.scrollContainers=uz(_),x())};return lee(m,!!e),oee(p),ie.useEffect(()=>{v(),x()},[e,m,p]),ie.useEffect(()=>v,[]),[S,a,f]}function oee(n){ie.useEffect(()=>{const e=n;return window.addEventListener("resize",e),()=>void window.removeEventListener("resize",e)},[n])}function lee(n,e){ie.useEffect(()=>{if(e){const t=n;return window.addEventListener("scroll",t,{capture:!0,passive:!0}),()=>void window.removeEventListener("scroll",t,!0)}},[n,e])}function uz(n){const e=[];if(!n||n===document.body)return e;const{overflow:t,overflowX:i,overflowY:r}=window.getComputedStyle(n);return[t,i,r].some(a=>a==="auto"||a==="scroll")&&e.push(n),[...e,...uz(n.parentElement)]}const cee=["x","y","top","bottom","left","right","width","height"],uee=(n,e)=>cee.every(t=>n[t]===e[t]);function hee({ref:n,children:e,fallback:t,resize:i,style:r,gl:a,events:s=aee,eventSource:o,eventPrefix:l,shadows:u,linear:d,flat:f,legacy:p,orthographic:m,frameloop:v,dpr:x,performance:S,raycaster:_,camera:T,scene:E,onPointerMissed:b,onCreated:R,...w}){ie.useMemo(()=>rz(kJ),[]);const L=R$(),[U,N]=see({scroll:!0,debounce:{scroll:50,resize:0},...i}),C=ie.useRef(null),z=ie.useRef(null);ie.useImperativeHandle(n,()=>C.current);const W=Q7(b),[K,oe]=ie.useState(!1),[ae,X]=ie.useState(!1);if(K)throw K;if(ae)throw ae;const te=ie.useRef(null);uv(()=>{const ce=C.current;if(N.width>0&&N.height>0&&ce){te.current||(te.current=eee(ce));async function se(){await te.current.configure({gl:a,scene:E,events:s,shadows:u,linear:d,flat:f,legacy:p,orthographic:m,frameloop:v,dpr:x,performance:S,raycaster:_,camera:T,size:N,onPointerMissed:(...De)=>W.current==null?void 0:W.current(...De),onCreated:De=>{De.events.connect==null||De.events.connect(o?A$(o)?o.current:o:z.current),l&&De.setEvents({compute:(Xe,nt)=>{const tt=Xe[l+"X"],xt=Xe[l+"Y"];nt.pointer.set(tt/nt.size.width*2-1,-(xt/nt.size.height)*2+1),nt.raycaster.setFromCamera(nt.pointer,nt.camera)}}),R==null||R(De)}}),te.current.render(ot.jsx(L,{children:ot.jsx(D$,{set:X,children:ot.jsx(ie.Suspense,{fallback:ot.jsx(C$,{set:oe}),children:e??null})})}))}se()}}),ie.useEffect(()=>{const ce=C.current;if(ce)return()=>lz(ce)},[]);const Q=o?"none":"auto";return ot.jsx("div",{ref:z,style:{position:"relative",width:"100%",height:"100%",overflow:"hidden",pointerEvents:Q,...r},...w,children:ot.jsx("div",{ref:U,style:{width:"100%",height:"100%"},children:ot.jsx("canvas",{ref:C,style:{display:"block"},children:t})})})}function hz(n){return ot.jsx(q7,{children:ot.jsx(hee,{...n})})}function dee(n){let e=0;for(const i in n.attributes){const r=n.getAttribute(i);e+=r.count*r.itemSize*r.array.BYTES_PER_ELEMENT}const t=n.getIndex();return e+=t?t.count*t.itemSize*t.array.BYTES_PER_ELEMENT:0,e}function PL(n,e){if(e===_9)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===Cy||e===tR){let t=n.getIndex();if(t===null){const s=[],o=n.getAttribute("position");if(o!==void 0){for(let l=0;l=2.0 are supported."));return}const u=new Xee(a,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});u.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d=0&&o[f]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+f+'".')}}u.setExtensions(s),u.setPlugins(o),u.parse(i,r)}parseAsync(e,t){const i=this;return new Promise(function(r,a){i.parse(e,t,r,a)})}}function fee(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const ln={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class pee{constructor(e){this.parser=e,this.name=ln.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,r=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,a.source,s)}}class Ree{constructor(e){this.parser=e,this.name=ln.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,r=i.json,a=r.textures[e];if(!a.extensions||!a.extensions[t])return null;const s=a.extensions[t],o=r.images[s.source];let l=i.textureLoader;if(o.uri){const u=i.options.manager.getHandler(o.uri);u!==null&&(l=u)}return i.loadTextureImage(e,s.source,l)}}class Cee{constructor(e){this.parser=e,this.name=ln.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,r=i.json,a=r.textures[e];if(!a.extensions||!a.extensions[t])return null;const s=a.extensions[t],o=r.images[s.source];let l=i.textureLoader;if(o.uri){const u=i.options.manager.getHandler(o.uri);u!==null&&(l=u)}return i.loadTextureImage(e,s.source,l)}}class Dee{constructor(e){this.name=ln.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const r=i.extensions[this.name],a=this.parser.getDependency("buffer",r.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return a.then(function(o){const l=r.byteOffset||0,u=r.byteLength||0,d=r.count,f=r.byteStride,p=new Uint8Array(o,l,u);return s.decodeGltfBufferAsync?s.decodeGltfBufferAsync(d,f,p,r.mode,r.filter).then(function(m){return m.buffer}):s.ready.then(function(){const m=new ArrayBuffer(d*f);return s.decodeGltfBuffer(new Uint8Array(m),d,f,p,r.mode,r.filter),m})})}else return null}}class Nee{constructor(e){this.name=ln.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const r=t.meshes[i.mesh];for(const u of r.primitives)if(u.mode!==fs.TRIANGLES&&u.mode!==fs.TRIANGLE_STRIP&&u.mode!==fs.TRIANGLE_FAN&&u.mode!==void 0)return null;const s=i.extensions[this.name].attributes,o=[],l={};for(const u in s)o.push(this.parser.getDependency("accessor",s[u]).then(d=>(l[u]=d,l[u])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(u=>{const d=u.pop(),f=d.isGroup?d.children:[d],p=u[0].count,m=[];for(const v of f){const x=new Me,S=new D,_=new ft,T=new D(1,1,1),E=new VS(v.geometry,v.material,p);for(let b=0;b0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Wee=new Me;class Xee{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new fee,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,r=-1,a=!1,s=-1;if(typeof navigator<"u"){const o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);r=i&&l?parseInt(l[1],10):-1,a=o.indexOf("Firefox")>-1,s=a?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&r<17||a&&s<98?this.textureLoader=new ER(this.options.manager):this.textureLoader=new x7(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new jr(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,r=this.json,a=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(s){return s._markDefs&&s._markDefs()}),Promise.all(this._invokeAll(function(s){return s.beforeRoot&&s.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(s){const o={scene:s[0][r.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:r.asset,parser:i,userData:{}};return Xu(a,o,r),yo(o,r),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let r=0,a=t.length;r{const l=this.associations.get(s);l!=null&&this.associations.set(o,l);for(const[u,d]of s.children.entries())a(d,o.children[u])};return a(i,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&S.setY(N,w[L*l+1]),l>=3&&S.setZ(N,w[L*l+2]),l>=4&&S.setW(N,w[L*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}S.normalized=v}return S})}loadTexture(e){const t=this.json,i=this.options,a=t.textures[e].source,s=t.images[a];let o=this.textureLoader;if(s.uri){const l=i.manager.getHandler(s.uri);l!==null&&(o=l)}return this.loadTextureImage(e,a,o)}loadTextureImage(e,t,i){const r=this,a=this.json,s=a.textures[e],o=a.images[t],l=(o.uri||o.bufferView)+":"+s.sampler;if(this.textureCache[l])return this.textureCache[l];const u=this.loadImageSource(t,i).then(function(d){d.flipY=!1,d.name=s.name||o.name||"",d.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(d.name=o.uri);const p=(a.samplers||{})[s.sampler]||{};return d.magFilter=BL[p.magFilter]||Bt,d.minFilter=BL[p.minFilter]||Ga,d.wrapS=FL[p.wrapS]||Ir,d.wrapT=FL[p.wrapT]||Ir,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==Yn&&d.minFilter!==Bt,r.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[l]=u,u}loadImageSource(e,t){const i=this,r=this.json,a=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(f=>f.clone());const s=r.images[e],o=self.URL||self.webkitURL;let l=s.uri||"",u=!1;if(s.bufferView!==void 0)l=i.getDependency("bufferView",s.bufferView).then(function(f){u=!0;const p=new Blob([f],{type:s.mimeType});return l=o.createObjectURL(p),l});else if(s.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(l).then(function(f){return new Promise(function(p,m){let v=p;t.isImageBitmapLoader===!0&&(v=function(x){const S=new In(x);S.needsUpdate=!0,p(S)}),t.load(qc.resolveURL(f,a.path),v,void 0,m)})}).then(function(f){return u===!0&&o.revokeObjectURL(l),yo(f,s),f.userData.mimeType=s.mimeType||kee(s.uri),f}).catch(function(f){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),f});return this.sourceCache[e]=d,d}assignTexture(e,t,i,r){const a=this;return this.getDependency("texture",i.index).then(function(s){if(!s)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(s=s.clone(),s.channel=i.texCoord),a.extensions[ln.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[ln.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=a.associations.get(s);s=a.extensions[ln.KHR_TEXTURE_TRANSFORM].extendTexture(s,o),a.associations.set(s,l)}}return r!==void 0&&(s.colorSpace=r),e[t]=s,s})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const r=t.attributes.tangent===void 0,a=t.attributes.color!==void 0,s=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new nv,ei.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(o,l)),i=l}else if(e.isLine){const o="LineBasicMaterial:"+i.uuid;let l=this.cache.get(o);l||(l=new Yi,ei.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(r||a||s){let o="ClonedMaterial:"+i.uuid+":";r&&(o+="derivative-tangents:"),a&&(o+="vertex-colors:"),s&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),a&&(l.vertexColors=!0),s&&(l.flatShading=!0),r&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return lv}loadMaterial(e){const t=this,i=this.json,r=this.extensions,a=i.materials[e];let s;const o={},l=a.extensions||{},u=[];if(l[ln.KHR_MATERIALS_UNLIT]){const f=r[ln.KHR_MATERIALS_UNLIT];s=f.getMaterialType(),u.push(f.extendParams(o,a,t))}else{const f=a.pbrMetallicRoughness||{};if(o.color=new Ye(1,1,1),o.opacity=1,Array.isArray(f.baseColorFactor)){const p=f.baseColorFactor;o.color.setRGB(p[0],p[1],p[2],Xn),o.opacity=p[3]}f.baseColorTexture!==void 0&&u.push(t.assignTexture(o,"map",f.baseColorTexture,mn)),o.metalness=f.metallicFactor!==void 0?f.metallicFactor:1,o.roughness=f.roughnessFactor!==void 0?f.roughnessFactor:1,f.metallicRoughnessTexture!==void 0&&(u.push(t.assignTexture(o,"metalnessMap",f.metallicRoughnessTexture)),u.push(t.assignTexture(o,"roughnessMap",f.metallicRoughnessTexture))),s=this._invokeOne(function(p){return p.getMaterialType&&p.getMaterialType(e)}),u.push(Promise.all(this._invokeAll(function(p){return p.extendMaterialParams&&p.extendMaterialParams(e,o)})))}a.doubleSided===!0&&(o.side=xr);const d=a.alphaMode||Nb.OPAQUE;if(d===Nb.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,d===Nb.MASK&&(o.alphaTest=a.alphaCutoff!==void 0?a.alphaCutoff:.5)),a.normalTexture!==void 0&&s!==Sr&&(u.push(t.assignTexture(o,"normalMap",a.normalTexture)),o.normalScale=new re(1,1),a.normalTexture.scale!==void 0)){const f=a.normalTexture.scale;o.normalScale.set(f,f)}if(a.occlusionTexture!==void 0&&s!==Sr&&(u.push(t.assignTexture(o,"aoMap",a.occlusionTexture)),a.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=a.occlusionTexture.strength)),a.emissiveFactor!==void 0&&s!==Sr){const f=a.emissiveFactor;o.emissive=new Ye().setRGB(f[0],f[1],f[2],Xn)}return a.emissiveTexture!==void 0&&s!==Sr&&u.push(t.assignTexture(o,"emissiveMap",a.emissiveTexture,mn)),Promise.all(u).then(function(){const f=new s(o);return a.name&&(f.name=a.name),yo(f,a),t.associations.set(f,{materials:e}),a.extensions&&Xu(r,f,a),f})}createUniqueName(e){const t=fn.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,r=this.primitiveCache;function a(o){return i[ln.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return HL(l,o,t)})}const s=[];for(let o=0,l=e.length;o0&&Vee(_,a),_.name=t.createUniqueName(a.name||"mesh_"+e),yo(_,a),S.extensions&&Xu(r,_,S),t.assignFinalMaterial(_),f.push(_)}for(let m=0,v=f.length;m1?d=new Xi:u.length===1?d=u[0]:d=new Xt,d!==u[0])for(let f=0,p=u.length;f1){const f=r.associations.get(d);r.associations.set(d,{...f})}return r.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],r=this,a=new Xi;i.name&&(a.name=r.createUniqueName(i.name)),yo(a,i),i.extensions&&Xu(t,a,i);const s=i.nodes||[],o=[];for(let l=0,u=s.length;l{const f=new Map;for(const[p,m]of r.associations)(p instanceof ei||p instanceof In)&&f.set(p,m);return d.traverse(p=>{const m=r.associations.get(p);m!=null&&f.set(p,m)}),f};return r.associations=u(a),a})}_createAnimationTracks(e,t,i,r,a){const s=[],o=e.name?e.name:e.uuid,l=[];hc[a.path]===hc.weights?e.traverse(function(p){p.morphTargetInfluences&&l.push(p.name?p.name:p.uuid)}):l.push(o);let u;switch(hc[a.path]){case hc.weights:u=tu;break;case hc.rotation:u=nu;break;case hc.translation:case hc.scale:u=Hh;break;default:switch(i.itemSize){case 1:u=tu;break;case 2:case 3:default:u=Hh;break}break}const d=r.interpolation!==void 0?Bee[r.interpolation]:Tp,f=this._getArrayFromAccessor(i);for(let p=0,m=l.length;pnew Promise((i,r)=>{var a=l=>{try{o(t.next(l))}catch(u){r(u)}},s=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);o((t=t.apply(n,e)).next())}),yn=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{o(t.next(l))}catch(u){r(u)}},s=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);o((t=t.apply(n,e)).next())}),VL=class extends Xt{constructor(n){super(),this.weight=0,this.isBinary=!1,this.overrideBlink="none",this.overrideLookAt="none",this.overrideMouth="none",this._binds=[],this.name=`VRMExpression_${n}`,this.expressionName=n,this.type="VRMExpression",this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink==="block"?0.5?1:0:this.weight}addBind(n){this._binds.push(n)}deleteBind(n){const e=this._binds.indexOf(n);e>=0&&this._binds.splice(e,1)}applyWeight(n){var e;let t=this.outputWeight;t*=(e=n==null?void 0:n.multiplier)!=null?e:1,this.isBinary&&t<1&&(t=0),this._binds.forEach(i=>i.applyWeight(t))}clearAppliedWeight(){this._binds.forEach(n=>n.clearAppliedWeight())}};function pz(n,e,t){var i,r;const a=n.parser.json,s=(i=a.nodes)==null?void 0:i[e];if(s==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${e}] of glTF but the node doesn't exist`),null;const o=s.mesh;if(o==null)return null;const l=(r=a.meshes)==null?void 0:r[o];if(l==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${o}] of glTF but the mesh doesn't exist`),null;const u=l.primitives.length,d=[];return t.traverse(f=>{d.length{const a=pz(n,r,i);a!=null&&t.set(r,a)}),t})}var aA={Aa:"aa",Ih:"ih",Ou:"ou",Ee:"ee",Oh:"oh",Blink:"blink",Happy:"happy",Angry:"angry",Sad:"sad",Relaxed:"relaxed",LookUp:"lookUp",Surprised:"surprised",LookDown:"lookDown",LookLeft:"lookLeft",LookRight:"lookRight",BlinkLeft:"blinkLeft",BlinkRight:"blinkRight",Neutral:"neutral"};function mz(n){return Math.max(Math.min(n,1),0)}var WL=class gz{constructor(){this.blinkExpressionNames=["blink","blinkLeft","blinkRight"],this.lookAtExpressionNames=["lookLeft","lookRight","lookUp","lookDown"],this.mouthExpressionNames=["aa","ee","ih","oh","ou"],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){const e={},t=new Set(Object.values(aA));return Object.entries(this._expressionMap).forEach(([i,r])=>{t.has(i)&&(e[i]=r)}),e}get customExpressionMap(){const e={},t=new Set(Object.values(aA));return Object.entries(this._expressionMap).forEach(([i,r])=>{t.has(i)||(e[i]=r)}),e}copy(e){return this._expressions.concat().forEach(i=>{this.unregisterExpression(i)}),e._expressions.forEach(i=>{this.registerExpression(i)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new gz().copy(this)}getExpression(e){var t;return(t=this._expressionMap[e])!=null?t:null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){const t=this._expressions.indexOf(e);t===-1&&console.warn("VRMExpressionManager: The specified expressions is not registered"),this._expressions.splice(t,1),delete this._expressionMap[e.expressionName]}getValue(e){var t;const i=this.getExpression(e);return(t=i==null?void 0:i.weight)!=null?t:null}setValue(e,t){const i=this.getExpression(e);i&&(i.weight=mz(t))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){const t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){const e=this._calculateWeightMultipliers();this._expressions.forEach(t=>{t.clearAppliedWeight()}),this._expressions.forEach(t=>{let i=1;const r=t.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(i*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(i*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(i*=e.mouth),t.applyWeight({multiplier:i})})}_calculateWeightMultipliers(){let e=1,t=1,i=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,t-=r.overrideLookAtAmount,i-=r.overrideMouthAmount}),e=Math.max(0,e),t=Math.max(0,t),i=Math.max(0,i),{blink:e,lookAt:t,mouth:i}}},Km={Color:"color",EmissionColor:"emissionColor",ShadeColor:"shadeColor",RimColor:"rimColor",OutlineColor:"outlineColor"},Yee={_Color:Km.Color,_EmissionColor:Km.EmissionColor,_ShadeColor:Km.ShadeColor,_RimColor:Km.RimColor,_OutlineColor:Km.OutlineColor},jee=new Ye,vz=class _z{constructor({material:e,type:t,targetValue:i,targetAlpha:r}){this.material=e,this.type=t,this.targetValue=i,this.targetAlpha=r??1;const a=this._initColorBindState(),s=this._initAlphaBindState();this._state={color:a,alpha:s}}applyWeight(e){const{color:t,alpha:i}=this._state;if(t!=null){const{propertyName:r,deltaValue:a}=t,s=this.material[r];s!=null&&s.add(jee.copy(a).multiplyScalar(e))}if(i!=null){const{propertyName:r,deltaValue:a}=i;this.material[r]!=null&&(this.material[r]+=a*e)}}clearAppliedWeight(){const{color:e,alpha:t}=this._state;if(e!=null){const{propertyName:i,initialValue:r}=e,a=this.material[i];a!=null&&a.copy(r)}if(t!=null){const{propertyName:i,initialValue:r}=t;this.material[i]!=null&&(this.material[i]=r)}}_initColorBindState(){var e,t,i;const{material:r,type:a,targetValue:s}=this,o=this._getPropertyNameMap(),l=(t=(e=o==null?void 0:o[a])==null?void 0:e[0])!=null?t:null;if(l==null)return console.warn(`Tried to add a material color bind to the material ${(i=r.name)!=null?i:"(no name)"}, the type ${a} but the material or the type is not supported.`),null;const d=r[l].clone(),f=new Ye(s.r-d.r,s.g-d.g,s.b-d.b);return{propertyName:l,initialValue:d,deltaValue:f}}_initAlphaBindState(){var e,t,i;const{material:r,type:a,targetAlpha:s}=this,o=this._getPropertyNameMap(),l=(t=(e=o==null?void 0:o[a])==null?void 0:e[1])!=null?t:null;if(l==null&&s!==1)return console.warn(`Tried to add a material alpha bind to the material ${(i=r.name)!=null?i:"(no name)"}, the type ${a} but the material or the type does not support alpha.`),null;if(l==null)return null;const u=r[l],d=s-u;return{propertyName:l,initialValue:u,deltaValue:d}}_getPropertyNameMap(){var e,t;return(t=(e=Object.entries(_z._propertyNameMapMap).find(([i])=>this.material[i]===!0))==null?void 0:e[1])!=null?t:null}};vz._propertyNameMapMap={isMeshStandardMaterial:{color:["color","opacity"],emissionColor:["emissive",null]},isMeshBasicMaterial:{color:["color","opacity"]},isMToonMaterial:{color:["color","opacity"],emissionColor:["emissive",null],outlineColor:["outlineColorFactor",null],matcapColor:["matcapFactor",null],rimColor:["parametricRimColorFactor",null],shadeColor:["shadeColorFactor",null]}};var XL=vz,Hy=class{constructor({primitives:n,index:e,weight:t}){this.primitives=n,this.index=e,this.weight=t}applyWeight(n){this.primitives.forEach(e=>{var t;((t=e.morphTargetInfluences)==null?void 0:t[this.index])!=null&&(e.morphTargetInfluences[this.index]+=this.weight*n)})}clearAppliedWeight(){this.primitives.forEach(n=>{var e;((e=n.morphTargetInfluences)==null?void 0:e[this.index])!=null&&(n.morphTargetInfluences[this.index]=0)})}},qL=new re,xz=class yz{constructor({material:e,scale:t,offset:i}){var r,a;this.material=e,this.scale=t,this.offset=i;const s=(r=Object.entries(yz._propertyNamesMap).find(([o])=>e[o]===!0))==null?void 0:r[1];s==null?(console.warn(`Tried to add a texture transform bind to the material ${(a=e.name)!=null?a:"(no name)"} but the material is not supported.`),this._properties=[]):(this._properties=[],s.forEach(o=>{var l;const u=(l=e[o])==null?void 0:l.clone();if(!u)return null;e[o]=u;const d=u.offset.clone(),f=u.repeat.clone(),p=i.clone().sub(d),m=t.clone().sub(f);this._properties.push({name:o,initialOffset:d,deltaOffset:p,initialScale:f,deltaScale:m})}))}applyWeight(e){this._properties.forEach(t=>{const i=this.material[t.name];i!==void 0&&(i.offset.add(qL.copy(t.deltaOffset).multiplyScalar(e)),i.repeat.add(qL.copy(t.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{const t=this.material[e.name];t!==void 0&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))})}};xz._propertyNamesMap={isMeshStandardMaterial:["map","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap"],isMeshBasicMaterial:["map","specularMap","alphaMap"],isMToonMaterial:["map","normalMap","emissiveMap","shadeMultiplyTexture","rimMultiplyTexture","outlineWidthMultiplyTexture","uvAnimationMaskTexture"]};var YL=xz,Zee=new Set(["1.0","1.0-beta"]),Sz=class Tz{get name(){return"VRMExpressionLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return yn(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return yn(this,null,function*(){const t=yield this._v1Import(e);if(t)return t;const i=yield this._v0Import(e);return i||null})}_v1Import(e){return yn(this,null,function*(){var t,i;const r=this.parser.json;if(!(((t=r.extensionsUsed)==null?void 0:t.indexOf("VRMC_vrm"))!==-1))return null;const s=(i=r.extensions)==null?void 0:i.VRMC_vrm;if(!s)return null;const o=s.specVersion;if(!Zee.has(o))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${o}"`),null;const l=s.expressions;if(!l)return null;const u=new Set(Object.values(aA)),d=new Map;l.preset!=null&&Object.entries(l.preset).forEach(([p,m])=>{if(m!=null){if(!u.has(p)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${p}" detected. Ignoring the expression`);return}d.set(p,m)}}),l.custom!=null&&Object.entries(l.custom).forEach(([p,m])=>{if(u.has(p)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${p}". Ignoring the expression`);return}d.set(p,m)});const f=new WL;return yield Promise.all(Array.from(d.entries()).map(p=>yn(this,[p],function*([m,v]){var x,S,_,T,E,b,R;const w=new VL(m);if(e.scene.add(w),w.isBinary=(x=v.isBinary)!=null?x:!1,w.overrideBlink=(S=v.overrideBlink)!=null?S:"none",w.overrideLookAt=(_=v.overrideLookAt)!=null?_:"none",w.overrideMouth=(T=v.overrideMouth)!=null?T:"none",(E=v.morphTargetBinds)==null||E.forEach(L=>yn(this,null,function*(){var U;if(L.node===void 0||L.index===void 0)return;const N=yield GL(e,L.node),C=L.index;if(!N.every(z=>Array.isArray(z.morphTargetInfluences)&&C{const N=U.material;N&&(Array.isArray(N)?L.push(...N):L.push(N))}),(b=v.materialColorBinds)==null||b.forEach(U=>yn(this,null,function*(){L.filter(C=>{var z;const W=(z=this.parser.associations.get(C))==null?void 0:z.materials;return U.material===W}).forEach(C=>{w.addBind(new XL({material:C,type:U.type,targetValue:new Ye().fromArray(U.targetValue),targetAlpha:U.targetValue[3]}))})})),(R=v.textureTransformBinds)==null||R.forEach(U=>yn(this,null,function*(){L.filter(C=>{var z;const W=(z=this.parser.associations.get(C))==null?void 0:z.materials;return U.material===W}).forEach(C=>{var z,W;w.addBind(new YL({material:C,offset:new re().fromArray((z=U.offset)!=null?z:[0,0]),scale:new re().fromArray((W=U.scale)!=null?W:[1,1])}))})}))}f.registerExpression(w)}))),f})}_v0Import(e){return yn(this,null,function*(){var t;const i=this.parser.json,r=(t=i.extensions)==null?void 0:t.VRM;if(!r)return null;const a=r.blendShapeMaster;if(!a)return null;const s=new WL,o=a.blendShapeGroups;if(!o)return s;const l=new Set;return yield Promise.all(o.map(u=>yn(this,null,function*(){var d;const f=u.presetName,p=f!=null&&Tz.v0v1PresetNameMap[f]||null,m=p??u.name;if(m==null){console.warn("VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression");return}if(l.has(m)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${f} has duplicated entries. Ignoring the expression`);return}l.add(m);const v=new VL(m);e.scene.add(v),v.isBinary=(d=u.isBinary)!=null?d:!1,u.binds&&u.binds.forEach(S=>yn(this,null,function*(){var _;if(S.mesh===void 0||S.index===void 0)return;const T=[];(_=i.nodes)==null||_.forEach((b,R)=>{b.mesh===S.mesh&&T.push(R)});const E=S.index;yield Promise.all(T.map(b=>yn(this,null,function*(){var R;const w=yield GL(e,b);if(!w.every(L=>Array.isArray(L.morphTargetInfluences)&&E{if(S.materialName===void 0||S.propertyName===void 0||S.targetValue===void 0)return;const _=[];e.scene.traverse(E=>{if(E.material){const b=E.material;Array.isArray(b)?_.push(...b.filter(R=>(R.name===S.materialName||R.name===S.materialName+" (Outline)")&&_.indexOf(R)===-1)):b.name===S.materialName&&_.indexOf(b)===-1&&_.push(b)}});const T=S.propertyName;_.forEach(E=>{if(T==="_MainTex_ST"){const R=new re(S.targetValue[0],S.targetValue[1]),w=new re(S.targetValue[2],S.targetValue[3]);w.y=1-w.y-R.y,v.addBind(new YL({material:E,scale:R,offset:w}));return}const b=Yee[T];if(b){v.addBind(new XL({material:E,type:b,targetValue:new Ye().fromArray(S.targetValue),targetAlpha:S.targetValue[3]}));return}console.warn(T+" is not supported")})}),s.registerExpression(v)}))),s})}};Sz.v0v1PresetNameMap={a:"aa",e:"ee",i:"ih",o:"oh",u:"ou",blink:"blink",joy:"happy",angry:"angry",sorrow:"sad",fun:"relaxed",lookup:"lookUp",lookdown:"lookDown",lookleft:"lookLeft",lookright:"lookRight",blink_l:"blinkLeft",blink_r:"blinkRight",neutral:"neutral"};var Qee=Sz,UR=class Mf{constructor(e,t){this._firstPersonOnlyLayer=Mf.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=Mf.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=e,this.meshAnnotations=t}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMFirstPerson: humanoid must be same in order to copy");return this.meshAnnotations=e.meshAnnotations.map(t=>({meshes:t.meshes.concat(),type:t.type})),this}clone(){return new Mf(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:e=Mf.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=Mf.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||(this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=t,this.meshAnnotations.forEach(i=>{i.meshes.forEach(r=>{i.type==="firstPersonOnly"?(r.layers.set(this._firstPersonOnlyLayer),r.traverse(a=>a.layers.set(this._firstPersonOnlyLayer))):i.type==="thirdPersonOnly"?(r.layers.set(this._thirdPersonOnlyLayer),r.traverse(a=>a.layers.set(this._thirdPersonOnlyLayer))):i.type==="auto"&&this._createHeadlessModel(r)})}),this._initializedLayers=!0)}_excludeTriangles(e,t,i,r){let a=0;if(t!=null&&t.length>0)for(let s=0;s0&&r.includes(f[0])||d[1]>0&&r.includes(f[1])||d[2]>0&&r.includes(f[2])||d[3]>0&&r.includes(f[3]))continue;const p=t[l],m=i[l];if(p[0]>0&&r.includes(m[0])||p[1]>0&&r.includes(m[1])||p[2]>0&&r.includes(m[2])||p[3]>0&&r.includes(m[3]))continue;const v=t[u],x=i[u];v[0]>0&&r.includes(x[0])||v[1]>0&&r.includes(x[1])||v[2]>0&&r.includes(x[2])||v[3]>0&&r.includes(x[3])||(e[a++]=o,e[a++]=l,e[a++]=u)}return a}_createErasedMesh(e,t){const i=new FS(e.geometry.clone(),e.material);i.name=`${e.name}(erase)`,i.frustumCulled=e.frustumCulled,i.layers.set(this._firstPersonOnlyLayer);const r=i.geometry,a=r.getAttribute("skinIndex"),s=a instanceof X3?[]:a.array,o=[];for(let x=0;x{this._isEraseTarget(a)&&i.push(s)}),!i.length){t.layers.enable(this._thirdPersonOnlyLayer),t.layers.enable(this._firstPersonOnlyLayer);return}t.layers.set(this._thirdPersonOnlyLayer);const r=this._createErasedMesh(t,i);e.add(r)}_createHeadlessModel(e){if(e.type==="Group")if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(t=>t.layers.set(this._thirdPersonOnlyLayer));else{const t=new Xi;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter(i=>i.type==="SkinnedMesh").forEach(i=>{const r=i;this._createHeadlessModelForSkinnedMesh(t,r)})}else if(e.type==="SkinnedMesh"){const t=e;this._createHeadlessModelForSkinnedMesh(e.parent,t)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(t=>t.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode("head")?!0:e.parent?this._isEraseTarget(e.parent):!1}};UR.DEFAULT_FIRSTPERSON_ONLY_LAYER=9;UR.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var jL=UR,Kee=new Set(["1.0","1.0-beta"]),Jee=class{get name(){return"VRMFirstPersonLoaderPlugin"}constructor(n){this.parser=n}afterRoot(n){return yn(this,null,function*(){const e=n.userData.vrmHumanoid;if(e!==null){if(e===void 0)throw new Error("VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");n.userData.vrmFirstPerson=yield this._import(n,e)}})}_import(n,e){return yn(this,null,function*(){if(e==null)return null;const t=yield this._v1Import(n,e);if(t)return t;const i=yield this._v0Import(n,e);return i||null})}_v1Import(n,e){return yn(this,null,function*(){var t,i;const r=this.parser.json;if(!(((t=r.extensionsUsed)==null?void 0:t.indexOf("VRMC_vrm"))!==-1))return null;const s=(i=r.extensions)==null?void 0:i.VRMC_vrm;if(!s)return null;const o=s.specVersion;if(!Kee.has(o))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${o}"`),null;const l=s.firstPerson,u=[],d=yield kL(n);return Array.from(d.entries()).forEach(([f,p])=>{var m,v;const x=(m=l==null?void 0:l.meshAnnotations)==null?void 0:m.find(S=>S.node===f);u.push({meshes:p,type:(v=x==null?void 0:x.type)!=null?v:"auto"})}),new jL(e,u)})}_v0Import(n,e){return yn(this,null,function*(){var t;const i=this.parser.json,r=(t=i.extensions)==null?void 0:t.VRM;if(!r)return null;const a=r.firstPerson;if(!a)return null;const s=[],o=yield kL(n);return Array.from(o.entries()).forEach(([l,u])=>{const d=i.nodes[l],f=a.meshAnnotations?a.meshAnnotations.find(p=>p.mesh===d.mesh):void 0;s.push({meshes:u,type:this._convertV0FlagToV1Type(f==null?void 0:f.firstPersonFlag)})}),new jL(e,s)})}_convertV0FlagToV1Type(n){return n==="FirstPersonOnly"?"firstPersonOnly":n==="ThirdPersonOnly"?"thirdPersonOnly":n==="Both"?"both":"auto"}},ZL=new D,QL=new D,$ee=new ft,KL=class extends Xi{constructor(n){super(),this.vrmHumanoid=n,this._boneAxesMap=new Map,Object.values(n.humanBones).forEach(e=>{const t=new w7(1);t.matrixAutoUpdate=!1,t.material.depthTest=!1,t.material.depthWrite=!1,this.add(t),this._boneAxesMap.set(e,t)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(n=>{n.geometry.dispose(),n.material.dispose()})}updateMatrixWorld(n){Array.from(this._boneAxesMap.entries()).forEach(([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(ZL,$ee,QL);const i=ZL.set(.1,.1,.1).divide(QL);t.matrix.copy(e.node.matrixWorld).scale(i)}),super.updateMatrixWorld(n)}},Lb=["hips","spine","chest","upperChest","neck","head","leftEye","rightEye","jaw","leftUpperLeg","leftLowerLeg","leftFoot","leftToes","rightUpperLeg","rightLowerLeg","rightFoot","rightToes","leftShoulder","leftUpperArm","leftLowerArm","leftHand","rightShoulder","rightUpperArm","rightLowerArm","rightHand","leftThumbMetacarpal","leftThumbProximal","leftThumbDistal","leftIndexProximal","leftIndexIntermediate","leftIndexDistal","leftMiddleProximal","leftMiddleIntermediate","leftMiddleDistal","leftRingProximal","leftRingIntermediate","leftRingDistal","leftLittleProximal","leftLittleIntermediate","leftLittleDistal","rightThumbMetacarpal","rightThumbProximal","rightThumbDistal","rightIndexProximal","rightIndexIntermediate","rightIndexDistal","rightMiddleProximal","rightMiddleIntermediate","rightMiddleDistal","rightRingProximal","rightRingIntermediate","rightRingDistal","rightLittleProximal","rightLittleIntermediate","rightLittleDistal"],ete={hips:null,spine:"hips",chest:"spine",upperChest:"chest",neck:"upperChest",head:"neck",leftEye:"head",rightEye:"head",jaw:"head",leftUpperLeg:"hips",leftLowerLeg:"leftUpperLeg",leftFoot:"leftLowerLeg",leftToes:"leftFoot",rightUpperLeg:"hips",rightLowerLeg:"rightUpperLeg",rightFoot:"rightLowerLeg",rightToes:"rightFoot",leftShoulder:"upperChest",leftUpperArm:"leftShoulder",leftLowerArm:"leftUpperArm",leftHand:"leftLowerArm",rightShoulder:"upperChest",rightUpperArm:"rightShoulder",rightLowerArm:"rightUpperArm",rightHand:"rightLowerArm",leftThumbMetacarpal:"leftHand",leftThumbProximal:"leftThumbMetacarpal",leftThumbDistal:"leftThumbProximal",leftIndexProximal:"leftHand",leftIndexIntermediate:"leftIndexProximal",leftIndexDistal:"leftIndexIntermediate",leftMiddleProximal:"leftHand",leftMiddleIntermediate:"leftMiddleProximal",leftMiddleDistal:"leftMiddleIntermediate",leftRingProximal:"leftHand",leftRingIntermediate:"leftRingProximal",leftRingDistal:"leftRingIntermediate",leftLittleProximal:"leftHand",leftLittleIntermediate:"leftLittleProximal",leftLittleDistal:"leftLittleIntermediate",rightThumbMetacarpal:"rightHand",rightThumbProximal:"rightThumbMetacarpal",rightThumbDistal:"rightThumbProximal",rightIndexProximal:"rightHand",rightIndexIntermediate:"rightIndexProximal",rightIndexDistal:"rightIndexIntermediate",rightMiddleProximal:"rightHand",rightMiddleIntermediate:"rightMiddleProximal",rightMiddleDistal:"rightMiddleIntermediate",rightRingProximal:"rightHand",rightRingIntermediate:"rightRingProximal",rightRingDistal:"rightRingIntermediate",rightLittleProximal:"rightHand",rightLittleIntermediate:"rightLittleProximal",rightLittleDistal:"rightLittleIntermediate"};function Ez(n){return n.invert?n.invert():n.inverse(),n}var qu=new D,Yu=new ft,sA=class{constructor(n){this.humanBones=n,this.restPose=this.getAbsolutePose()}getAbsolutePose(){const n={};return Object.keys(this.humanBones).forEach(e=>{const t=e,i=this.getBoneNode(t);i&&(qu.copy(i.position),Yu.copy(i.quaternion),n[t]={position:qu.toArray(),rotation:Yu.toArray()})}),n}getPose(){const n={};return Object.keys(this.humanBones).forEach(e=>{const t=e,i=this.getBoneNode(t);if(!i)return;qu.set(0,0,0),Yu.identity();const r=this.restPose[t];r!=null&&r.position&&qu.fromArray(r.position).negate(),r!=null&&r.rotation&&Ez(Yu.fromArray(r.rotation)),qu.add(i.position),Yu.premultiply(i.quaternion),n[t]={position:qu.toArray(),rotation:Yu.toArray()}}),n}setPose(n){Object.entries(n).forEach(([e,t])=>{const i=e,r=this.getBoneNode(i);if(!r)return;const a=this.restPose[i];a&&(t!=null&&t.position&&(r.position.fromArray(t.position),a.position&&r.position.add(qu.fromArray(a.position))),t!=null&&t.rotation&&(r.quaternion.fromArray(t.rotation),a.rotation&&r.quaternion.multiply(Yu.fromArray(a.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([n,e])=>{const t=this.getBoneNode(n);t&&(e!=null&&e.position&&t.position.fromArray(e.position),e!=null&&e.rotation&&t.quaternion.fromArray(e.rotation))})}getBone(n){var e;return(e=this.humanBones[n])!=null?e:void 0}getBoneNode(n){var e,t;return(t=(e=this.humanBones[n])==null?void 0:e.node)!=null?t:null}},Ib=new D,tte=new ft,nte=new D,JL=class bz extends sA{static _setupTransforms(e){const t=new Xt;t.name="VRMHumanoidRig";const i={},r={},a={};Lb.forEach(o=>{var l;const u=e.getBoneNode(o);if(u){const d=new D,f=new ft;u.updateWorldMatrix(!0,!1),u.matrixWorld.decompose(d,f,Ib),i[o]=d,r[o]=u.quaternion.clone();const p=new ft;(l=u.parent)==null||l.matrixWorld.decompose(Ib,p,Ib),a[o]=p}});const s={};return Lb.forEach(o=>{var l;const u=e.getBoneNode(o);if(u){const d=i[o];let f=o,p;for(;p==null&&(f=ete[f],f!=null);)p=i[f];const m=new Xt;m.name="Normalized_"+u.name,(f?(l=s[f])==null?void 0:l.node:t).add(m),m.position.copy(d),p&&m.position.sub(p),s[o]={node:m}}}),{rigBones:s,root:t,parentWorldRotations:a,boneRotations:r}}constructor(e){const{rigBones:t,root:i,parentWorldRotations:r,boneRotations:a}=bz._setupTransforms(e);super(t),this.original=e,this.root=i,this._parentWorldRotations=r,this._boneRotations=a}update(){Lb.forEach(e=>{const t=this.original.getBoneNode(e);if(t!=null){const i=this.getBoneNode(e),r=this._parentWorldRotations[e],a=tte.copy(r).invert(),s=this._boneRotations[e];if(t.quaternion.copy(i.quaternion).multiply(r).premultiply(a).multiply(s),e==="hips"){const o=i.getWorldPosition(nte);t.parent.updateWorldMatrix(!0,!1);const l=t.parent.matrixWorld,u=o.applyMatrix4(l.invert());t.position.copy(u)}}})}},$L=class Mz{get restPose(){return console.warn("VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead."),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,t){var i;this.autoUpdateHumanBones=(i=t==null?void 0:t.autoUpdateHumanBones)!=null?i:!0,this._rawHumanBones=new sA(e),this._normalizedHumanBones=new JL(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new sA(e.humanBones),this._normalizedHumanBones=new JL(this._rawHumanBones),this}clone(){return new Mz(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn("VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead."),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn("VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead."),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn("VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead."),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn("VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead."),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn("VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead."),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn("VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead."),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},ite={Hips:"hips",Spine:"spine",Head:"head",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand"},rte=new Set(["1.0","1.0-beta"]),eI={leftThumbProximal:"leftThumbMetacarpal",leftThumbIntermediate:"leftThumbProximal",rightThumbProximal:"rightThumbMetacarpal",rightThumbIntermediate:"rightThumbProximal"},ate=class{get name(){return"VRMHumanoidLoaderPlugin"}constructor(n,e){this.parser=n,this.helperRoot=e==null?void 0:e.helperRoot,this.autoUpdateHumanBones=e==null?void 0:e.autoUpdateHumanBones}afterRoot(n){return yn(this,null,function*(){n.userData.vrmHumanoid=yield this._import(n)})}_import(n){return yn(this,null,function*(){const e=yield this._v1Import(n);if(e)return e;const t=yield this._v0Import(n);return t||null})}_v1Import(n){return yn(this,null,function*(){var e,t;const i=this.parser.json;if(!(((e=i.extensionsUsed)==null?void 0:e.indexOf("VRMC_vrm"))!==-1))return null;const a=(t=i.extensions)==null?void 0:t.VRMC_vrm;if(!a)return null;const s=a.specVersion;if(!rte.has(s))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${s}"`),null;const o=a.humanoid;if(!o)return null;const l=o.humanBones.leftThumbIntermediate!=null||o.humanBones.rightThumbIntermediate!=null,u={};o.humanBones!=null&&(yield Promise.all(Object.entries(o.humanBones).map(f=>yn(this,[f],function*([p,m]){let v=p;const x=m.node;if(l){const _=eI[v];_!=null&&(v=_)}const S=yield this.parser.getDependency("node",x);if(S==null){console.warn(`A glTF node bound to the humanoid bone ${v} (index = ${x}) does not exist`);return}u[v]={node:S}}))));const d=new $L(this._ensureRequiredBonesExist(u),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(n.scene.add(d.normalizedHumanBonesRoot),this.helperRoot){const f=new KL(d);this.helperRoot.add(f),f.renderOrder=this.helperRoot.renderOrder}return d})}_v0Import(n){return yn(this,null,function*(){var e;const i=(e=this.parser.json.extensions)==null?void 0:e.VRM;if(!i)return null;const r=i.humanoid;if(!r)return null;const a={};r.humanBones!=null&&(yield Promise.all(r.humanBones.map(o=>yn(this,null,function*(){const l=o.bone,u=o.node;if(l==null||u==null)return;const d=yield this.parser.getDependency("node",u);if(d==null){console.warn(`A glTF node bound to the humanoid bone ${l} (index = ${u}) does not exist`);return}const f=eI[l],p=f??l;if(a[p]!=null){console.warn(`Multiple bone entries for ${p} detected (index = ${u}), ignoring duplicated entries.`);return}a[p]={node:d}}))));const s=new $L(this._ensureRequiredBonesExist(a),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(n.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){const o=new KL(s);this.helperRoot.add(o),o.renderOrder=this.helperRoot.renderOrder}return s})}_ensureRequiredBonesExist(n){const e=Object.values(ite).filter(t=>n[t]==null);if(e.length>0)throw new Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${e.join(", ")}`);return n}},tI=class extends Ct{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new bt(new Float32Array(65*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new bt(new Uint16Array(3*63),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,n=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,n=!0),n&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let n=0;n<64;n++){const e=n/63*this._currentTheta;this._attrPos.setXYZ(n+1,this._currentRadius*Math.sin(e),0,this._currentRadius*Math.cos(e))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<63;n++)this._attrIndex.setXYZ(n*3,0,n+1,n+2);this._attrIndex.needsUpdate=!0}},ste=class extends Ct{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new D,this._currentTail=new D,this._attrPos=new bt(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new bt(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,n=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),n=!0),n&&this._buildPosition()}_buildPosition(){for(let n=0;n<32;n++){const e=n/16*Math.PI;this._attrPos.setXYZ(n,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+n,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+n,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(64+n*2,32+n,32+e),this._attrIndex.setXY(128+n*2,64+n,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},ux=new ft,nI=new ft,Jm=new D,iI=new D,rI=Math.sqrt(2)/2,ote=new ft(0,0,-rI,rI),lte=new D(0,1,0),cte=class extends Xi{constructor(n){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=n;{const e=new tI;e.radius=.5;const t=new Sr({color:65280,transparent:!0,opacity:.5,side:xr,depthTest:!1,depthWrite:!1});this._meshPitch=new jn(e,t),this.add(this._meshPitch)}{const e=new tI;e.radius=.5;const t=new Sr({color:16711680,transparent:!0,opacity:.5,side:xr,depthTest:!1,depthWrite:!1});this._meshYaw=new jn(e,t),this.add(this._meshYaw)}{const e=new ste;e.radius=.1;const t=new Yi({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new va(e,t),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(n){const e=lt.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=e,this._meshYaw.geometry.update();const t=lt.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=t,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(Jm),this.vrmLookAt.getLookAtWorldQuaternion(ux),ux.multiply(this.vrmLookAt.getFaceFrontQuaternion(nI)),this._meshYaw.position.copy(Jm),this._meshYaw.quaternion.copy(ux),this._meshPitch.position.copy(Jm),this._meshPitch.quaternion.copy(ux),this._meshPitch.quaternion.multiply(nI.setFromAxisAngle(lte,e)),this._meshPitch.quaternion.multiply(ote);const{target:i,autoUpdate:r}=this.vrmLookAt;i!=null&&r&&(i.getWorldPosition(iI).sub(Jm),this._lineTarget.geometry.tail.copy(iI),this._lineTarget.geometry.update(),this._lineTarget.position.copy(Jm)),super.updateMatrixWorld(n)}},ute=new D,hte=new D;function oA(n,e){return n.matrixWorld.decompose(ute,e,hte),e}function d1(n){return[Math.atan2(-n.z,n.x),Math.atan2(n.y,Math.sqrt(n.x*n.x+n.z*n.z))]}function aI(n){const e=Math.round(n/2/Math.PI);return n-2*Math.PI*e}var sI=new D(0,0,1),dte=new D,fte=new D,pte=new D,mte=new ft,Ub=new ft,oI=new ft,gte=new ft,Pb=new Ai,Az=class wz{constructor(e,t){this.offsetFromHeadBone=new D,this.autoUpdate=!0,this.faceFront=new D(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new ft)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn("VRMLookAt: euler is deprecated. use getEuler() instead."),this.getEuler(new Ai)}getEuler(e){return e.set(lt.DEG2RAD*this._pitch,lt.DEG2RAD*this._yaw,0,"YXZ")}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMLookAt: humanoid must be same in order to copy");return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new wz(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){const t=this.humanoid.getRawBoneNode("head");return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){const t=this.humanoid.getRawBoneNode("head");return oA(t,e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(sI)<.01)return e.copy(this._restHeadWorldQuaternion).invert();const[t,i]=d1(this.faceFront);return Pb.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(Pb).premultiply(gte.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(Ub),this.getFaceFrontQuaternion(oI),e.copy(sI).applyQuaternion(Ub).applyQuaternion(oI).applyEuler(this.getEuler(Pb))}lookAt(e){const t=mte.copy(this._restHeadWorldQuaternion).multiply(Ez(this.getLookAtWorldQuaternion(Ub))),i=this.getLookAtWorldPosition(fte),r=pte.copy(e).sub(i).applyQuaternion(t).normalize(),[a,s]=d1(this.faceFront),[o,l]=d1(r),u=aI(o-a),d=aI(s-l);this._yaw=lt.RAD2DEG*u,this._pitch=lt.RAD2DEG*d,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(dte)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};Az.EULER_ORDER="YXZ";var vte=Az,_te=new D(0,0,1),go=new ft,of=new ft,cs=new Ai(0,0,0,"YXZ"),f1=class{constructor(n,e,t,i,r){this.humanoid=n,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=t,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=r,this.faceFront=new D(0,0,1),this._restQuatLeftEye=new ft,this._restQuatRightEye=new ft,this._restLeftEyeParentWorldQuat=new ft,this._restRightEyeParentWorldQuat=new ft;const a=this.humanoid.getRawBoneNode("leftEye"),s=this.humanoid.getRawBoneNode("rightEye");a&&(this._restQuatLeftEye.copy(a.quaternion),oA(a.parent,this._restLeftEyeParentWorldQuat)),s&&(this._restQuatRightEye.copy(s.quaternion),oA(s.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(n,e){const t=this.humanoid.getRawBoneNode("leftEye"),i=this.humanoid.getRawBoneNode("rightEye"),r=this.humanoid.getNormalizedBoneNode("leftEye"),a=this.humanoid.getNormalizedBoneNode("rightEye");t&&(e<0?cs.x=-lt.DEG2RAD*this.rangeMapVerticalDown.map(-e):cs.x=lt.DEG2RAD*this.rangeMapVerticalUp.map(e),n<0?cs.y=-lt.DEG2RAD*this.rangeMapHorizontalInner.map(-n):cs.y=lt.DEG2RAD*this.rangeMapHorizontalOuter.map(n),go.setFromEuler(cs),this._getWorldFaceFrontQuat(of),r.quaternion.copy(of).multiply(go).multiply(of.invert()),go.copy(this._restLeftEyeParentWorldQuat),t.quaternion.copy(r.quaternion).multiply(go).premultiply(go.invert()).multiply(this._restQuatLeftEye)),i&&(e<0?cs.x=-lt.DEG2RAD*this.rangeMapVerticalDown.map(-e):cs.x=lt.DEG2RAD*this.rangeMapVerticalUp.map(e),n<0?cs.y=-lt.DEG2RAD*this.rangeMapHorizontalOuter.map(-n):cs.y=lt.DEG2RAD*this.rangeMapHorizontalInner.map(n),go.setFromEuler(cs),this._getWorldFaceFrontQuat(of),a.quaternion.copy(of).multiply(go).multiply(of.invert()),go.copy(this._restRightEyeParentWorldQuat),i.quaternion.copy(a.quaternion).multiply(go).premultiply(go.invert()).multiply(this._restQuatRightEye))}lookAt(n){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const e=lt.RAD2DEG*n.y,t=lt.RAD2DEG*n.x;this.applyYawPitch(e,t)}_getWorldFaceFrontQuat(n){if(this.faceFront.distanceToSquared(_te)<.01)return n.identity();const[e,t]=d1(this.faceFront);return cs.set(0,.5*Math.PI+e,t,"YZX"),n.setFromEuler(cs)}};f1.type="bone";var lA=class{constructor(n,e,t,i,r){this.expressions=n,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=t,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=r}applyYawPitch(n,e){e<0?(this.expressions.setValue("lookDown",0),this.expressions.setValue("lookUp",this.rangeMapVerticalUp.map(-e))):(this.expressions.setValue("lookUp",0),this.expressions.setValue("lookDown",this.rangeMapVerticalDown.map(e))),n<0?(this.expressions.setValue("lookLeft",0),this.expressions.setValue("lookRight",this.rangeMapHorizontalOuter.map(-n))):(this.expressions.setValue("lookRight",0),this.expressions.setValue("lookLeft",this.rangeMapHorizontalOuter.map(n)))}lookAt(n){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const e=lt.RAD2DEG*n.y,t=lt.RAD2DEG*n.x;this.applyYawPitch(e,t)}};lA.type="expression";var lI=class{constructor(n,e){this.inputMaxValue=n,this.outputScale=e}map(n){return this.outputScale*mz(n/this.inputMaxValue)}},xte=new Set(["1.0","1.0-beta"]),hx=.01,yte=class{get name(){return"VRMLookAtLoaderPlugin"}constructor(n,e){this.parser=n,this.helperRoot=e==null?void 0:e.helperRoot}afterRoot(n){return yn(this,null,function*(){const e=n.userData.vrmHumanoid;if(e===null)return;if(e===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");const t=n.userData.vrmExpressionManager;if(t!==null){if(t===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first");n.userData.vrmLookAt=yield this._import(n,e,t)}})}_import(n,e,t){return yn(this,null,function*(){if(e==null||t==null)return null;const i=yield this._v1Import(n,e,t);if(i)return i;const r=yield this._v0Import(n,e,t);return r||null})}_v1Import(n,e,t){return yn(this,null,function*(){var i,r,a;const s=this.parser.json;if(!(((i=s.extensionsUsed)==null?void 0:i.indexOf("VRMC_vrm"))!==-1))return null;const l=(r=s.extensions)==null?void 0:r.VRMC_vrm;if(!l)return null;const u=l.specVersion;if(!xte.has(u))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${u}"`),null;const d=l.lookAt;if(!d)return null;const f=d.type==="expression"?1:10,p=this._v1ImportRangeMap(d.rangeMapHorizontalInner,f),m=this._v1ImportRangeMap(d.rangeMapHorizontalOuter,f),v=this._v1ImportRangeMap(d.rangeMapVerticalDown,f),x=this._v1ImportRangeMap(d.rangeMapVerticalUp,f);let S;d.type==="expression"?S=new lA(t,p,m,v,x):S=new f1(e,p,m,v,x);const _=this._importLookAt(e,S);return _.offsetFromHeadBone.fromArray((a=d.offsetFromHeadBone)!=null?a:[0,.06,0]),_})}_v1ImportRangeMap(n,e){var t,i;let r=(t=n==null?void 0:n.inputMaxValue)!=null?t:90;const a=(i=n==null?void 0:n.outputScale)!=null?i:e;return r(console.error(s),console.warn("VRMMetaLoaderPlugin: Failed to load a thumbnail image"),null))})}},bte=class{constructor(n){this.scene=n.scene,this.meta=n.meta,this.humanoid=n.humanoid,this.expressionManager=n.expressionManager,this.firstPerson=n.firstPerson,this.lookAt=n.lookAt}update(n){this.humanoid.update(),this.lookAt&&this.lookAt.update(n),this.expressionManager&&this.expressionManager.update()}},Mte=class extends bte{constructor(n){super(n),this.materials=n.materials,this.springBoneManager=n.springBoneManager,this.nodeConstraintManager=n.nodeConstraintManager}update(n){super.update(n),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(n),this.materials&&this.materials.forEach(e=>{e.update&&e.update(n)})}},Ate=Object.defineProperty,cI=Object.getOwnPropertySymbols,wte=Object.prototype.hasOwnProperty,Rte=Object.prototype.propertyIsEnumerable,uI=(n,e,t)=>e in n?Ate(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,hI=(n,e)=>{for(var t in e||(e={}))wte.call(e,t)&&uI(n,t,e[t]);if(cI)for(var t of cI(e))Rte.call(e,t)&&uI(n,t,e[t]);return n},gh=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{o(t.next(l))}catch(u){r(u)}},s=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);o((t=t.apply(n,e)).next())}),Cte={"":3e3,srgb:3001};function Dte(n,e){parseInt($s,10)>=152?n.colorSpace=e:n.encoding=Cte[e]}var Nte=class{get pending(){return Promise.all(this._pendings)}constructor(n,e){this._parser=n,this._materialParams=e,this._pendings=[]}assignPrimitive(n,e){e!=null&&(this._materialParams[n]=e)}assignColor(n,e,t){if(e!=null){const i=new Ye().fromArray(e);t&&i.convertSRGBToLinear(),this._materialParams[n]=i}}assignTexture(n,e,t){return gh(this,null,function*(){const i=gh(this,null,function*(){e!=null&&(yield this._parser.assignTexture(this._materialParams,n,e),t&&Dte(this._materialParams[n],"srgb"))});return this._pendings.push(i),i})}assignTextureByIndex(n,e,t){return gh(this,null,function*(){return this.assignTexture(n,e!=null?{index:e}:void 0,t)})}},Ote=`// #define PHONG + +varying vec3 vViewPosition; + +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif + +#include + +// #include +#ifdef MTOON_USE_UV + varying vec2 vUv; + + // COMPAT: pre-r151 uses a common uvTransform + #if THREE_VRM_THREE_REVISION < 151 + uniform mat3 uvTransform; + #endif +#endif + +// #include +// COMAPT: pre-r151 uses uv2 for lightMap and aoMap +#if THREE_VRM_THREE_REVISION < 151 + #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + attribute vec2 uv2; + varying vec2 vUv2; + uniform mat3 uv2Transform; + #endif +#endif + +// #include +// #include +#include +#include +#include +#include +#include +#include +#include + +#ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE + uniform sampler2D outlineWidthMultiplyTexture; + uniform mat3 outlineWidthMultiplyTextureUvTransform; +#endif + +uniform float outlineWidthFactor; + +void main() { + + // #include + #ifdef MTOON_USE_UV + // COMPAT: pre-r151 uses a common uvTransform + #if THREE_VRM_THREE_REVISION >= 151 + vUv = uv; + #else + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #endif + + // #include + // COMAPT: pre-r151 uses uv2 for lightMap and aoMap + #if THREE_VRM_THREE_REVISION < 151 + #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy; + #endif + #endif + + #include + + #include + #include + #include + #include + + // we need this to compute the outline properly + objectNormal = normalize( objectNormal ); + + #include + + #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED + vNormal = normalize( transformedNormal ); + #endif + + #include + + #include + #include + // #include + #include + #include + #include + + vViewPosition = - mvPosition.xyz; + + #ifdef OUTLINE + float worldNormalLength = length( transformedNormal ); + vec3 outlineOffset = outlineWidthFactor * worldNormalLength * objectNormal; + + #ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE + vec2 outlineWidthMultiplyTextureUv = ( outlineWidthMultiplyTextureUvTransform * vec3( vUv, 1 ) ).xy; + float outlineTex = texture2D( outlineWidthMultiplyTexture, outlineWidthMultiplyTextureUv ).g; + outlineOffset *= outlineTex; + #endif + + #ifdef OUTLINE_WIDTH_SCREEN + outlineOffset *= vViewPosition.z / projectionMatrix[ 1 ].y; + #endif + + gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 ); + + gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic + #endif + + #include + // #include + #include + #include + +}`,Lte=`// #define PHONG + +uniform vec3 litFactor; + +uniform float opacity; + +uniform vec3 shadeColorFactor; +#ifdef USE_SHADEMULTIPLYTEXTURE + uniform sampler2D shadeMultiplyTexture; + uniform mat3 shadeMultiplyTextureUvTransform; +#endif + +uniform float shadingShiftFactor; +uniform float shadingToonyFactor; + +#ifdef USE_SHADINGSHIFTTEXTURE + uniform sampler2D shadingShiftTexture; + uniform mat3 shadingShiftTextureUvTransform; + uniform float shadingShiftTextureScale; +#endif + +uniform float giEqualizationFactor; + +uniform vec3 parametricRimColorFactor; +#ifdef USE_RIMMULTIPLYTEXTURE + uniform sampler2D rimMultiplyTexture; + uniform mat3 rimMultiplyTextureUvTransform; +#endif +uniform float rimLightingMixFactor; +uniform float parametricRimFresnelPowerFactor; +uniform float parametricRimLiftFactor; + +#ifdef USE_MATCAPTEXTURE + uniform vec3 matcapFactor; + uniform sampler2D matcapTexture; + uniform mat3 matcapTextureUvTransform; +#endif + +uniform vec3 emissive; +uniform float emissiveIntensity; + +uniform vec3 outlineColorFactor; +uniform float outlineLightingMixFactor; + +#ifdef USE_UVANIMATIONMASKTEXTURE + uniform sampler2D uvAnimationMaskTexture; + uniform mat3 uvAnimationMaskTextureUvTransform; +#endif + +uniform float uvAnimationScrollXOffset; +uniform float uvAnimationScrollYOffset; +uniform float uvAnimationRotationPhase; + +#include +#include +#include +#include + +// #include +#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) ) + varying vec2 vUv; +#endif + +// #include +// COMAPT: pre-r151 uses uv2 for lightMap and aoMap +#if THREE_VRM_THREE_REVISION < 151 + #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + varying vec2 vUv2; + #endif +#endif + +#include + +#ifdef USE_MAP + uniform mat3 mapUvTransform; +#endif + +// #include + +#include + +#include +// #include +#include + +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapUvTransform; +#endif + +// #include +// #include +// #include +#include + +// #include +// COMPAT: pre-r151 doesn't have BRDF_Lambert in +#if THREE_VRM_THREE_REVISION < 151 + vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; + } +#endif + +#include + +#include + +// #include +varying vec3 vViewPosition; + +struct MToonMaterial { + vec3 diffuseColor; + vec3 shadeColor; + float shadingShift; +}; + +float linearstep( float a, float b, float t ) { + return clamp( ( t - a ) / ( b - a ), 0.0, 1.0 ); +} + +/** + * Convert NdotL into toon shading factor using shadingShift and shadingToony + */ +float getShading( + const in float dotNL, + const in float shadow, + const in float shadingShift +) { + float shading = dotNL; + shading = shading + shadingShift; + shading = linearstep( -1.0 + shadingToonyFactor, 1.0 - shadingToonyFactor, shading ); + shading *= shadow; + return shading; +} + +/** + * Mix diffuseColor and shadeColor using shading factor and light color + */ +vec3 getDiffuse( + const in MToonMaterial material, + const in float shading, + in vec3 lightColor +) { + #ifdef DEBUG_LITSHADERATE + return vec3( BRDF_Lambert( shading * lightColor ) ); + #endif + + vec3 col = lightColor * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, shading ) ); + + // The "comment out if you want to PBR absolutely" line + #ifdef V0_COMPAT_SHADE + col = min( col, material.diffuseColor ); + #endif + + return col; +} + +// COMPAT: pre-r156 uses a struct GeometricContext +#if THREE_VRM_THREE_REVISION >= 157 + void RE_Direct_MToon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) { + float dotNL = clamp( dot( geometryNormal, directLight.direction ), -1.0, 1.0 ); + vec3 irradiance = directLight.color; + + // directSpecular will be used for rim lighting, not an actual specular + reflectedLight.directSpecular += irradiance; + + irradiance *= dotNL; + + float shading = getShading( dotNL, shadow, material.shadingShift ); + + // toon shaded diffuse + reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color ); + } + + void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, inout ReflectedLight reflectedLight ) { + // indirect diffuse will use diffuseColor, no shadeColor involved + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + + // directSpecular will be used for rim lighting, not an actual specular + reflectedLight.directSpecular += irradiance; + } +#else + void RE_Direct_MToon( const in IncidentLight directLight, const in GeometricContext geometry, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) { + float dotNL = clamp( dot( geometry.normal, directLight.direction ), -1.0, 1.0 ); + vec3 irradiance = directLight.color; + + // directSpecular will be used for rim lighting, not an actual specular + reflectedLight.directSpecular += irradiance; + + irradiance *= dotNL; + + float shading = getShading( dotNL, shadow, material.shadingShift ); + + // toon shaded diffuse + reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color ); + } + + void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in GeometricContext geometry, const in MToonMaterial material, inout ReflectedLight reflectedLight ) { + // indirect diffuse will use diffuseColor, no shadeColor involved + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + + // directSpecular will be used for rim lighting, not an actual specular + reflectedLight.directSpecular += irradiance; + } +#endif + +#define RE_Direct RE_Direct_MToon +#define RE_IndirectDiffuse RE_IndirectDiffuse_MToon +#define Material_LightProbeLOD( material ) (0) + +#include +// #include + +// #include +#ifdef USE_NORMALMAP + + uniform sampler2D normalMap; + uniform mat3 normalMapUvTransform; + uniform vec2 normalScale; + +#endif + +// COMPAT: pre-r151 +// USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151 +#if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP ) + + uniform mat3 normalMatrix; + +#endif + +// COMPAT: pre-r151 +// USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151 +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( TANGENTSPACE_NORMALMAP ) ) + + // Per-Pixel Tangent Space Normal Mapping + // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html + + // three-vrm specific change: it requires \`uv\` as an input in order to support uv scrolls + + // Temporary compat against shader change @ Three.js r126, r151 + #if THREE_VRM_THREE_REVISION >= 151 + + 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 ); + + } + + #else + + vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) { + + vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) ); + vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + + vec3 N = normalize( 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; + + // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0 + // TODO: Is this still required? Or shall I make a PR about it? + if ( length( T ) == 0.0 || length( B ) == 0.0 ) { + return surf_norm; + } + + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det ); + + return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z ); + + } + + #endif + +#endif + +// #include +#include +#include + +// == post correction ========================================================== +void postCorrection() { + #include + #include + #include + #include + #include +} + +// == main procedure =========================================================== +void main() { + #include + + vec2 uv = vec2(0.5, 0.5); + + #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) ) + uv = vUv; + + float uvAnimMask = 1.0; + #ifdef USE_UVANIMATIONMASKTEXTURE + vec2 uvAnimationMaskTextureUv = ( uvAnimationMaskTextureUvTransform * vec3( uv, 1 ) ).xy; + uvAnimMask = texture2D( uvAnimationMaskTexture, uvAnimationMaskTextureUv ).b; + #endif + + float uvRotCos = cos( uvAnimationRotationPhase * uvAnimMask ); + float uvRotSin = sin( uvAnimationRotationPhase * uvAnimMask ); + uv = mat2( uvRotCos, -uvRotSin, uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5; + uv = uv + vec2( uvAnimationScrollXOffset, uvAnimationScrollYOffset ) * uvAnimMask; + #endif + + #ifdef DEBUG_UV + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) ) + gl_FragColor = vec4( uv, 0.0, 1.0 ); + #endif + return; + #endif + + vec4 diffuseColor = vec4( litFactor, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive * emissiveIntensity; + + #include + + // #include + #ifdef USE_MAP + vec2 mapUv = ( mapUvTransform * vec3( uv, 1 ) ).xy; + vec4 sampledDiffuseColor = texture2D( map, mapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w ); + #endif + diffuseColor *= sampledDiffuseColor; + #endif + + // #include + #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) ) + diffuseColor.rgb *= vColor; + #endif + + // #include + + #include + + // #include + + // #include + 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 + + #ifdef USE_NORMALMAP + + vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy; + + #endif + + #ifdef USE_NORMALMAP_TANGENTSPACE + + #ifdef USE_TANGENT + + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + + #else + + mat3 tbn = getTangentFrame( - vViewPosition, normal, normalMapUv ); + + #endif + + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + + #endif + + #endif + + #ifdef USE_CLEARCOAT_NORMALMAP + + #ifdef USE_TANGENT + + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + + #else + + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + + #endif + + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + + #endif + + #endif + + // non perturbed normal for clearcoat among others + + vec3 nonPerturbedNormal = normal; + + #ifdef OUTLINE + normal *= -1.0; + #endif + + // #include + + // COMPAT: pre-r151 + // USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151 + #if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP ) + + normal = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals + + #ifdef FLIP_SIDED + + normal = - normal; + + #endif + + #ifdef DOUBLE_SIDED + + normal = normal * faceDirection; + + #endif + + normal = normalize( normalMatrix * normal ); + + // COMPAT: pre-r151 + // USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151 + #elif defined( USE_NORMALMAP_TANGENTSPACE ) || defined( TANGENTSPACE_NORMALMAP ) + + vec3 mapN = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + + // COMPAT: pre-r151 + #if THREE_VRM_THREE_REVISION >= 151 || defined( USE_TANGENT ) + + normal = normalize( tbn * mapN ); + + #else + + normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection ); + + #endif + + #endif + + // #include + #ifdef USE_EMISSIVEMAP + vec2 emissiveMapUv = ( emissiveMapUvTransform * vec3( uv, 1 ) ).xy; + totalEmissiveRadiance *= texture2D( emissiveMap, emissiveMapUv ).rgb; + #endif + + #ifdef DEBUG_NORMAL + gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 ); + return; + #endif + + // -- MToon: lighting -------------------------------------------------------- + // accumulation + // #include + MToonMaterial material; + + material.diffuseColor = diffuseColor.rgb; + + material.shadeColor = shadeColorFactor; + #ifdef USE_SHADEMULTIPLYTEXTURE + vec2 shadeMultiplyTextureUv = ( shadeMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy; + material.shadeColor *= texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv ).rgb; + #endif + + #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) ) + material.shadeColor.rgb *= vColor; + #endif + + material.shadingShift = shadingShiftFactor; + #ifdef USE_SHADINGSHIFTTEXTURE + vec2 shadingShiftTextureUv = ( shadingShiftTextureUvTransform * vec3( uv, 1 ) ).xy; + material.shadingShift += texture2D( shadingShiftTexture, shadingShiftTextureUv ).r * shadingShiftTextureScale; + #endif + + // #include + + // MToon Specific changes: + // Since we want to take shadows into account of shading instead of irradiance, + // we had to modify the codes that multiplies the results of shadowmap into color of direct lights. + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + vec3 geometryPosition = - vViewPosition; + vec3 geometryNormal = normal; + vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); + + vec3 geometryClearcoatNormal; + + #ifdef USE_CLEARCOAT + + geometryClearcoatNormal = clearcoatNormal; + + #endif + #else + GeometricContext geometry; + + geometry.position = - vViewPosition; + geometry.normal = normal; + geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); + + #ifdef USE_CLEARCOAT + + geometry.clearcoatNormal = clearcoatNormal; + + #endif + #endif + + IncidentLight directLight; + + // since these variables will be used in unrolled loop, we have to define in prior + float shadow; + + #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 ]; + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + getPointLightInfo( pointLight, geometryPosition, directLight ); + #else + getPointLightInfo( pointLight, geometry, directLight ); + #endif + + shadow = 1.0; + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + // COMPAT: pre-r166 + // r166 introduced shadowIntensity + #if THREE_VRM_THREE_REVISION >= 166 + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #else + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + #endif + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight ); + #else + RE_Direct( directLight, geometry, material, shadow, reflectedLight ); + #endif + + } + #pragma unroll_loop_end + + #endif + + #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + + SpotLight spotLight; + #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 ]; + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #else + getSpotLightInfo( spotLight, geometry, directLight ); + #endif + + shadow = 1.0; + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + // COMPAT: pre-r166 + // r166 introduced shadowIntensity + #if THREE_VRM_THREE_REVISION >= 166 + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; + #else + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; + #endif + #endif + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight ); + #else + RE_Direct( directLight, geometry, material, shadow, reflectedLight ); + #endif + + } + #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 ]; + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + getDirectionalLightInfo( directionalLight, directLight ); + #else + getDirectionalLightInfo( directionalLight, geometry, directLight ); + #endif + + shadow = 1.0; + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + // COMPAT: pre-r166 + // r166 introduced shadowIntensity + #if THREE_VRM_THREE_REVISION >= 166 + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #else + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + #endif + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight ); + #else + RE_Direct( directLight, geometry, material, shadow, reflectedLight ); + #endif + + } + #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, geometry, material, reflectedLight ); + + // } + // #pragma unroll_loop_end + + // #endif + + #if defined( RE_IndirectDiffuse ) + + vec3 iblIrradiance = vec3( 0.0 ); + + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + + // COMPAT: pre-r156 uses a struct GeometricContext + // COMPAT: pre-r156 doesn't have a define USE_LIGHT_PROBES + #if THREE_VRM_THREE_REVISION >= 157 + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #else + irradiance += getLightProbeIrradiance( lightProbe, geometry.normal ); + #endif + + #if ( NUM_HEMI_LIGHTS > 0 ) + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + #else + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal ); + #endif + + } + #pragma unroll_loop_end + + #endif + + #endif + + // #if defined( RE_IndirectSpecular ) + + // vec3 radiance = vec3( 0.0 ); + // vec3 clearcoatRadiance = vec3( 0.0 ); + + // #endif + + #include + #include + + // modulation + #include + + vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + + #ifdef DEBUG_LITSHADERATE + gl_FragColor = vec4( col, diffuseColor.a ); + postCorrection(); + return; + #endif + + // -- MToon: rim lighting ----------------------------------------- + vec3 viewDir = normalize( vViewPosition ); + + #ifndef PHYSICALLY_CORRECT_LIGHTS + reflectedLight.directSpecular /= PI; + #endif + vec3 rimMix = mix( vec3( 1.0 ), reflectedLight.directSpecular, 1.0 ); + + vec3 rim = parametricRimColorFactor * pow( saturate( 1.0 - dot( viewDir, normal ) + parametricRimLiftFactor ), parametricRimFresnelPowerFactor ); + + #ifdef USE_MATCAPTEXTURE + { + vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) ); + vec3 y = cross( viewDir, x ); // guaranteed to be normalized + vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) ); + sphereUv = ( matcapTextureUvTransform * vec3( sphereUv, 1 ) ).xy; + vec3 matcap = texture2D( matcapTexture, sphereUv ).rgb; + rim += matcapFactor * matcap; + } + #endif + + #ifdef USE_RIMMULTIPLYTEXTURE + vec2 rimMultiplyTextureUv = ( rimMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy; + rim *= texture2D( rimMultiplyTexture, rimMultiplyTextureUv ).rgb; + #endif + + col += rimMix * rim; + + // -- MToon: Emission -------------------------------------------------------- + col += totalEmissiveRadiance; + + // #include + + // -- Almost done! ----------------------------------------------------------- + #if defined( OUTLINE ) + col = outlineColorFactor.rgb * mix( vec3( 1.0 ), col, outlineLightingMixFactor ); + #endif + + #ifdef OPAQUE + diffuseColor.a = 1.0; + #endif + + gl_FragColor = vec4( col, diffuseColor.a ); + postCorrection(); +} +`,Ite={None:"none"},dI={None:"none",ScreenCoordinates:"screenCoordinates"},Ute={3e3:"",3001:"srgb"};function zb(n){return parseInt($s,10)>=152?n.colorSpace:Ute[n.encoding]}var Pte=class extends Oi{constructor(n={}){var e;super({vertexShader:Ote,fragmentShader:Lte}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=Hl,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=Ite.None,this._outlineWidthMode=dI.None,this._isOutline=!1,n.transparentWithZWrite&&(n.depthWrite=!0),delete n.transparentWithZWrite,n.fog=!0,n.lights=!0,n.clipping=!0,this.uniforms=oR.merge([rt.common,rt.normalmap,rt.emissivemap,rt.fog,rt.lights,{litFactor:{value:new Ye(1,1,1)},mapUvTransform:{value:new Mt},colorAlpha:{value:1},normalMapUvTransform:{value:new Mt},shadeColorFactor:{value:new Ye(0,0,0)},shadeMultiplyTexture:{value:null},shadeMultiplyTextureUvTransform:{value:new Mt},shadingShiftFactor:{value:0},shadingShiftTexture:{value:null},shadingShiftTextureUvTransform:{value:new Mt},shadingShiftTextureScale:{value:1},shadingToonyFactor:{value:.9},giEqualizationFactor:{value:.9},matcapFactor:{value:new Ye(1,1,1)},matcapTexture:{value:null},matcapTextureUvTransform:{value:new Mt},parametricRimColorFactor:{value:new Ye(0,0,0)},rimMultiplyTexture:{value:null},rimMultiplyTextureUvTransform:{value:new Mt},rimLightingMixFactor:{value:1},parametricRimFresnelPowerFactor:{value:5},parametricRimLiftFactor:{value:0},emissive:{value:new Ye(0,0,0)},emissiveIntensity:{value:1},emissiveMapUvTransform:{value:new Mt},outlineWidthMultiplyTexture:{value:null},outlineWidthMultiplyTextureUvTransform:{value:new Mt},outlineWidthFactor:{value:0},outlineColorFactor:{value:new Ye(0,0,0)},outlineLightingMixFactor:{value:1},uvAnimationMaskTexture:{value:null},uvAnimationMaskTextureUvTransform:{value:new Mt},uvAnimationScrollXOffset:{value:0},uvAnimationScrollYOffset:{value:0},uvAnimationRotationPhase:{value:0}},(e=n.uniforms)!=null?e:{}]),this.setValues(n),this._uploadUniformsWorkaround(),this.customProgramCacheKey=()=>[...Object.entries(this._generateDefines()).map(([t,i])=>`${t}:${i}`),this.matcapTexture?`matcapTextureColorSpace:${zb(this.matcapTexture)}`:"",this.shadeMultiplyTexture?`shadeMultiplyTextureColorSpace:${zb(this.shadeMultiplyTexture)}`:"",this.rimMultiplyTexture?`rimMultiplyTextureColorSpace:${zb(this.rimMultiplyTexture)}`:""].join(","),this.onBeforeCompile=t=>{const i=parseInt($s,10),r=Object.entries(hI(hI({},this._generateDefines()),this.defines)).filter(([a,s])=>!!s).map(([a,s])=>`#define ${a} ${s}`).join(` +`)+` +`;t.vertexShader=r+t.vertexShader,t.fragmentShader=r+t.fragmentShader,i<154&&(t.fragmentShader=t.fragmentShader.replace("#include ","#include "))}}get color(){return this.uniforms.litFactor.value}set color(n){this.uniforms.litFactor.value=n}get map(){return this.uniforms.map.value}set map(n){this.uniforms.map.value=n}get normalMap(){return this.uniforms.normalMap.value}set normalMap(n){this.uniforms.normalMap.value=n}get normalScale(){return this.uniforms.normalScale.value}set normalScale(n){this.uniforms.normalScale.value=n}get emissive(){return this.uniforms.emissive.value}set emissive(n){this.uniforms.emissive.value=n}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(n){this.uniforms.emissiveIntensity.value=n}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(n){this.uniforms.emissiveMap.value=n}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(n){this.uniforms.shadeColorFactor.value=n}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(n){this.uniforms.shadeMultiplyTexture.value=n}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(n){this.uniforms.shadingShiftFactor.value=n}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(n){this.uniforms.shadingShiftTexture.value=n}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(n){this.uniforms.shadingShiftTextureScale.value=n}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(n){this.uniforms.shadingToonyFactor.value=n}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(n){this.uniforms.giEqualizationFactor.value=n}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(n){this.uniforms.matcapFactor.value=n}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(n){this.uniforms.matcapTexture.value=n}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(n){this.uniforms.parametricRimColorFactor.value=n}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(n){this.uniforms.rimMultiplyTexture.value=n}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(n){this.uniforms.rimLightingMixFactor.value=n}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(n){this.uniforms.parametricRimFresnelPowerFactor.value=n}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(n){this.uniforms.parametricRimLiftFactor.value=n}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(n){this.uniforms.outlineWidthMultiplyTexture.value=n}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(n){this.uniforms.outlineWidthFactor.value=n}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(n){this.uniforms.outlineColorFactor.value=n}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(n){this.uniforms.outlineLightingMixFactor.value=n}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(n){this.uniforms.uvAnimationMaskTexture.value=n}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(n){this.uniforms.uvAnimationScrollXOffset.value=n}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(n){this.uniforms.uvAnimationScrollYOffset.value=n}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(n){this.uniforms.uvAnimationRotationPhase.value=n}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(n){this._ignoreVertexColor=n,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(n){this._v0CompatShade=n,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(n){this._debugMode=n,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(n){this._outlineWidthMode=n,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(n){this._isOutline=n,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(n){this._uploadUniformsWorkaround(),this._updateUVAnimation(n)}copy(n){return super.copy(n),this.map=n.map,this.normalMap=n.normalMap,this.emissiveMap=n.emissiveMap,this.shadeMultiplyTexture=n.shadeMultiplyTexture,this.shadingShiftTexture=n.shadingShiftTexture,this.matcapTexture=n.matcapTexture,this.rimMultiplyTexture=n.rimMultiplyTexture,this.outlineWidthMultiplyTexture=n.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=n.uvAnimationMaskTexture,this.normalMapType=n.normalMapType,this.uvAnimationScrollXSpeedFactor=n.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=n.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=n.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=n.ignoreVertexColor,this.v0CompatShade=n.v0CompatShade,this.debugMode=n.debugMode,this.outlineWidthMode=n.outlineWidthMode,this.isOutline=n.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(n){this.uniforms.uvAnimationScrollXOffset.value+=n*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=n*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=n*this.uvAnimationRotationSpeedFactor,this.uniforms.alphaTest.value=this.alphaTest,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform),this.uniformsNeedUpdate=!0}_generateDefines(){const n=parseInt($s,10),e=this.outlineWidthMultiplyTexture!==null,t=this.map!==null||this.normalMap!==null||this.emissiveMap!==null||this.shadeMultiplyTexture!==null||this.shadingShiftTexture!==null||this.rimMultiplyTexture!==null||this.uvAnimationMaskTexture!==null;return{THREE_VRM_THREE_REVISION:n,OUTLINE:this._isOutline,MTOON_USE_UV:e||t,MTOON_UVS_VERTEX_ONLY:e&&!t,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:this.shadeMultiplyTexture!==null,USE_SHADINGSHIFTTEXTURE:this.shadingShiftTexture!==null,USE_MATCAPTEXTURE:this.matcapTexture!==null,USE_RIMMULTIPLYTEXTURE:this.rimMultiplyTexture!==null,USE_OUTLINEWIDTHMULTIPLYTEXTURE:this._isOutline&&this.outlineWidthMultiplyTexture!==null,USE_UVANIMATIONMASKTEXTURE:this.uvAnimationMaskTexture!==null,IGNORE_VERTEX_COLOR:this._ignoreVertexColor===!0,DEBUG_NORMAL:this._debugMode==="normal",DEBUG_LITSHADERATE:this._debugMode==="litShadeRate",DEBUG_UV:this._debugMode==="uv",OUTLINE_WIDTH_SCREEN:this._isOutline&&this._outlineWidthMode===dI.ScreenCoordinates}}_updateTextureMatrix(n,e){n.value&&(n.value.matrixAutoUpdate&&n.value.updateMatrix(),e.value.copy(n.value.matrix))}},zte=new Set(["1.0","1.0-beta"]),Rz=class p1{get name(){return p1.EXTENSION_NAME}constructor(e,t={}){var i,r,a,s;this.parser=e,this.materialType=(i=t.materialType)!=null?i:Pte,this.renderOrderOffset=(r=t.renderOrderOffset)!=null?r:0,this.v0CompatShade=(a=t.v0CompatShade)!=null?a:!1,this.debugMode=(s=t.debugMode)!=null?s:"none",this._mToonMaterialSet=new Set}beforeRoot(){return gh(this,null,function*(){this._removeUnlitExtensionIfMToonExists()})}afterRoot(e){return gh(this,null,function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)})}getMaterialType(e){return this._getMToonExtension(e)?this.materialType:null}extendMaterialParams(e,t){const i=this._getMToonExtension(e);return i?this._extendMaterialParams(i,t):null}loadMesh(e){return gh(this,null,function*(){var t;const i=this.parser,a=(t=i.json.meshes)==null?void 0:t[e];if(a==null)throw new Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);const s=a.primitives,o=yield i.loadMesh(e);if(s.length===1){const l=o,u=s[0].material;u!=null&&this._setupPrimitive(l,u)}else{const l=o;for(let u=0;u{var s;this._getMToonExtension(a)&&((s=r.extensions)!=null&&s.KHR_materials_unlit)&&delete r.extensions.KHR_materials_unlit})}_getMToonExtension(e){var t,i;const s=(t=this.parser.json.materials)==null?void 0:t[e];if(s==null){console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);return}const o=(i=s.extensions)==null?void 0:i[p1.EXTENSION_NAME];if(o==null)return;const l=o.specVersion;if(!zte.has(l)){console.warn(`MToonMaterialLoaderPlugin: Unknown ${p1.EXTENSION_NAME} specVersion "${l}"`);return}return o}_extendMaterialParams(e,t){return gh(this,null,function*(){var i;delete t.metalness,delete t.roughness;const r=new Nte(this.parser,t);r.assignPrimitive("transparentWithZWrite",e.transparentWithZWrite),r.assignColor("shadeColorFactor",e.shadeColorFactor),r.assignTexture("shadeMultiplyTexture",e.shadeMultiplyTexture,!0),r.assignPrimitive("shadingShiftFactor",e.shadingShiftFactor),r.assignTexture("shadingShiftTexture",e.shadingShiftTexture,!0),r.assignPrimitive("shadingShiftTextureScale",(i=e.shadingShiftTexture)==null?void 0:i.scale),r.assignPrimitive("shadingToonyFactor",e.shadingToonyFactor),r.assignPrimitive("giEqualizationFactor",e.giEqualizationFactor),r.assignColor("matcapFactor",e.matcapFactor),r.assignTexture("matcapTexture",e.matcapTexture,!0),r.assignColor("parametricRimColorFactor",e.parametricRimColorFactor),r.assignTexture("rimMultiplyTexture",e.rimMultiplyTexture,!0),r.assignPrimitive("rimLightingMixFactor",e.rimLightingMixFactor),r.assignPrimitive("parametricRimFresnelPowerFactor",e.parametricRimFresnelPowerFactor),r.assignPrimitive("parametricRimLiftFactor",e.parametricRimLiftFactor),r.assignPrimitive("outlineWidthMode",e.outlineWidthMode),r.assignPrimitive("outlineWidthFactor",e.outlineWidthFactor),r.assignTexture("outlineWidthMultiplyTexture",e.outlineWidthMultiplyTexture,!1),r.assignColor("outlineColorFactor",e.outlineColorFactor),r.assignPrimitive("outlineLightingMixFactor",e.outlineLightingMixFactor),r.assignTexture("uvAnimationMaskTexture",e.uvAnimationMaskTexture,!1),r.assignPrimitive("uvAnimationScrollXSpeedFactor",e.uvAnimationScrollXSpeedFactor),r.assignPrimitive("uvAnimationScrollYSpeedFactor",e.uvAnimationScrollYSpeedFactor),r.assignPrimitive("uvAnimationRotationSpeedFactor",e.uvAnimationRotationSpeedFactor),r.assignPrimitive("v0CompatShade",this.v0CompatShade),r.assignPrimitive("debugMode",this.debugMode),yield r.pending})}_setupPrimitive(e,t){const i=this._getMToonExtension(t);if(i){const r=this._parseRenderOrder(i);e.renderOrder=r+this.renderOrderOffset,this._generateOutline(e),this._addToMaterialSet(e);return}}_shouldGenerateOutline(e){return typeof e.outlineWidthMode=="string"&&e.outlineWidthMode!=="none"&&typeof e.outlineWidthFactor=="number"&&e.outlineWidthFactor>0}_generateOutline(e){const t=e.material;if(!(t instanceof ei)||!this._shouldGenerateOutline(t))return;e.material=[t];const i=t.clone();i.name+=" (Outline)",i.isOutline=!0,i.side=ki,e.material.push(i);const r=e.geometry,a=r.index?r.index.count:r.attributes.position.count/3;r.addGroup(0,a,0),r.addGroup(0,a,1)}_addToMaterialSet(e){const t=e.material,i=new Set;Array.isArray(t)?t.forEach(r=>i.add(r)):i.add(t);for(const r of i)this._mToonMaterialSet.add(r)}_parseRenderOrder(e){var t;return(e.transparentWithZWrite?0:19)+((t=e.renderQueueOffsetNumber)!=null?t:0)}};Rz.EXTENSION_NAME="VRMC_materials_mtoon";var Bte=Rz,Fte=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{o(t.next(l))}catch(u){r(u)}},s=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);o((t=t.apply(n,e)).next())}),Cz=class cA{get name(){return cA.EXTENSION_NAME}constructor(e){this.parser=e}extendMaterialParams(e,t){return Fte(this,null,function*(){const i=this._getHDREmissiveMultiplierExtension(e);if(i==null)return;console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead.");const r=i.emissiveMultiplier;t.emissiveIntensity=r})}_getHDREmissiveMultiplierExtension(e){var t,i;const s=(t=this.parser.json.materials)==null?void 0:t[e];if(s==null){console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);return}const o=(i=s.extensions)==null?void 0:i[cA.EXTENSION_NAME];if(o!=null)return o}};Cz.EXTENSION_NAME="VRMC_materials_hdr_emissiveMultiplier";var Hte=Cz,Vte=Object.defineProperty,Gte=Object.defineProperties,kte=Object.getOwnPropertyDescriptors,fI=Object.getOwnPropertySymbols,Wte=Object.prototype.hasOwnProperty,Xte=Object.prototype.propertyIsEnumerable,pI=(n,e,t)=>e in n?Vte(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,vo=(n,e)=>{for(var t in e||(e={}))Wte.call(e,t)&&pI(n,t,e[t]);if(fI)for(var t of fI(e))Xte.call(e,t)&&pI(n,t,e[t]);return n},mI=(n,e)=>Gte(n,kte(e)),qte=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{o(t.next(l))}catch(u){r(u)}},s=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);o((t=t.apply(n,e)).next())});function lf(n){return Math.pow(n,2.2)}var Yte=class{get name(){return"VRMMaterialsV0CompatPlugin"}constructor(n){var e;this.parser=n,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;const t=this.parser.json;t.extensionsUsed=(e=t.extensionsUsed)!=null?e:[],t.extensionsUsed.indexOf("KHR_texture_transform")===-1&&t.extensionsUsed.push("KHR_texture_transform")}beforeRoot(){return qte(this,null,function*(){var n;const e=this.parser.json,t=(n=e.extensions)==null?void 0:n.VRM,i=t==null?void 0:t.materialProperties;i&&(this._populateRenderQueueMap(i),i.forEach((r,a)=>{var s,o;const l=(s=e.materials)==null?void 0:s[a];if(l==null){console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${a}] of glTF but the material doesn't exist`);return}if(r.shader==="VRM/MToon"){const u=this._parseV0MToonProperties(r,l);e.materials[a]=u}else if((o=r.shader)!=null&&o.startsWith("VRM/Unlit")){const u=this._parseV0UnlitProperties(r,l);e.materials[a]=u}else r.shader==="VRM_USE_GLTFSHADER"||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${r.shader}`)}))})}_parseV0MToonProperties(n,e){var t,i,r,a,s,o,l,u,d,f,p,m,v,x,S,_,T,E,b,R,w,L,U,N,C,z,W,K,oe,ae,X,te,Q,ce,se,De,Xe,nt,tt,xt,ve,we,Ze,de,it,wt,ct,Qe,Ee,V,Ae,Oe,Ve,Fe,$e;const Je=(i=(t=n.keywordMap)==null?void 0:t._ALPHABLEND_ON)!=null?i:!1,k=((r=n.floatProperties)==null?void 0:r._ZWrite)===1&&Je,P=this._v0ParseRenderQueue(n),he=(s=(a=n.keywordMap)==null?void 0:a._ALPHATEST_ON)!=null?s:!1,be=Je?"BLEND":he?"MASK":"OPAQUE",Ie=he?(l=(o=n.floatProperties)==null?void 0:o._Cutoff)!=null?l:.5:void 0,yt=((d=(u=n.floatProperties)==null?void 0:u._CullMode)!=null?d:2)===0,je=this._portTextureTransform(n),Tt=((p=(f=n.vectorProperties)==null?void 0:f._Color)!=null?p:[1,1,1,1]).map((I,G)=>G===3?I:lf(I)),vt=(m=n.textureProperties)==null?void 0:m._MainTex,Ue=vt!=null?{index:vt,extensions:vo({},je)}:void 0,He=(x=(v=n.floatProperties)==null?void 0:v._BumpScale)!=null?x:1,pt=(S=n.textureProperties)==null?void 0:S._BumpMap,J=pt!=null?{index:pt,scale:He,extensions:vo({},je)}:void 0,me=((T=(_=n.vectorProperties)==null?void 0:_._EmissionColor)!=null?T:[0,0,0,1]).map(lf),Le=(E=n.textureProperties)==null?void 0:E._EmissionMap,j=Le!=null?{index:Le,extensions:vo({},je)}:void 0,ke=((R=(b=n.vectorProperties)==null?void 0:b._ShadeColor)!=null?R:[.97,.81,.86,1]).map(lf),ge=(w=n.textureProperties)==null?void 0:w._ShadeTexture,We=ge!=null?{index:ge,extensions:vo({},je)}:void 0;let Ge=(U=(L=n.floatProperties)==null?void 0:L._ShadeShift)!=null?U:0,Re=(C=(N=n.floatProperties)==null?void 0:N._ShadeToony)!=null?C:.9;Re=lt.lerp(Re,1,.5+.5*Ge),Ge=-Ge-(1-Re);const at=(W=(z=n.floatProperties)==null?void 0:z._IndirectLightIntensity)!=null?W:.1,Et=at?1-at:void 0,Gt=(K=n.textureProperties)==null?void 0:K._SphereAdd,kt=Gt!=null?[1,1,1]:void 0,mi=Gt!=null?{index:Gt}:void 0,gi=(ae=(oe=n.floatProperties)==null?void 0:oe._RimLightingMix)!=null?ae:0,Po=(X=n.textureProperties)==null?void 0:X._RimTexture,ro=Po!=null?{index:Po,extensions:vo({},je)}:void 0,ao=((Q=(te=n.vectorProperties)==null?void 0:te._RimColor)!=null?Q:[0,0,0,1]).map(lf),Li=(se=(ce=n.floatProperties)==null?void 0:ce._RimFresnelPower)!=null?se:1,so=(Xe=(De=n.floatProperties)==null?void 0:De._RimLift)!=null?Xe:0,Er=["none","worldCoordinates","screenCoordinates"][(tt=(nt=n.floatProperties)==null?void 0:nt._OutlineWidthMode)!=null?tt:0];let er=(ve=(xt=n.floatProperties)==null?void 0:xt._OutlineWidth)!=null?ve:0;er=.01*er;const $r=(we=n.textureProperties)==null?void 0:we._OutlineWidthTexture,Un=$r!=null?{index:$r,extensions:vo({},je)}:void 0,Ja=((de=(Ze=n.vectorProperties)==null?void 0:Ze._OutlineColor)!=null?de:[0,0,0]).map(lf),lo=((wt=(it=n.floatProperties)==null?void 0:it._OutlineColorMode)!=null?wt:0)===1?(Qe=(ct=n.floatProperties)==null?void 0:ct._OutlineLightingMix)!=null?Qe:1:0,zo=(Ee=n.textureProperties)==null?void 0:Ee._UvAnimMaskTexture,Sa=zo!=null?{index:zo,extensions:vo({},je)}:void 0,br=(Ae=(V=n.floatProperties)==null?void 0:V._UvAnimScrollX)!=null?Ae:0;let O=(Ve=(Oe=n.floatProperties)==null?void 0:Oe._UvAnimScrollY)!=null?Ve:0;O!=null&&(O=-O);const B=($e=(Fe=n.floatProperties)==null?void 0:Fe._UvAnimRotation)!=null?$e:0,Y={specVersion:"1.0",transparentWithZWrite:k,renderQueueOffsetNumber:P,shadeColorFactor:ke,shadeMultiplyTexture:We,shadingShiftFactor:Ge,shadingToonyFactor:Re,giEqualizationFactor:Et,matcapFactor:kt,matcapTexture:mi,rimLightingMixFactor:gi,rimMultiplyTexture:ro,parametricRimColorFactor:ao,parametricRimFresnelPowerFactor:Li,parametricRimLiftFactor:so,outlineWidthMode:Er,outlineWidthFactor:er,outlineWidthMultiplyTexture:Un,outlineColorFactor:Ja,outlineLightingMixFactor:lo,uvAnimationMaskTexture:Sa,uvAnimationScrollXSpeedFactor:br,uvAnimationScrollYSpeedFactor:O,uvAnimationRotationSpeedFactor:B};return mI(vo({},e),{pbrMetallicRoughness:{baseColorFactor:Tt,baseColorTexture:Ue},normalTexture:J,emissiveTexture:j,emissiveFactor:me,alphaMode:be,alphaCutoff:Ie,doubleSided:yt,extensions:{VRMC_materials_mtoon:Y}})}_parseV0UnlitProperties(n,e){var t,i,r,a,s;const o=n.shader==="VRM/UnlitTransparentZWrite",l=n.shader==="VRM/UnlitTransparent"||o,u=this._v0ParseRenderQueue(n),d=n.shader==="VRM/UnlitCutout",f=l?"BLEND":d?"MASK":"OPAQUE",p=d?(i=(t=n.floatProperties)==null?void 0:t._Cutoff)!=null?i:.5:void 0,m=this._portTextureTransform(n),v=((a=(r=n.vectorProperties)==null?void 0:r._Color)!=null?a:[1,1,1,1]).map(lf),x=(s=n.textureProperties)==null?void 0:s._MainTex,S=x!=null?{index:x,extensions:vo({},m)}:void 0,_={specVersion:"1.0",transparentWithZWrite:o,renderQueueOffsetNumber:u,shadeColorFactor:v,shadeMultiplyTexture:S};return mI(vo({},e),{pbrMetallicRoughness:{baseColorFactor:v,baseColorTexture:S},alphaMode:f,alphaCutoff:p,extensions:{VRMC_materials_mtoon:_}})}_portTextureTransform(n){var e,t,i,r,a;const s=(e=n.vectorProperties)==null?void 0:e._MainTex;if(s==null)return{};const o=[(t=s==null?void 0:s[0])!=null?t:0,(i=s==null?void 0:s[1])!=null?i:0],l=[(r=s==null?void 0:s[2])!=null?r:1,(a=s==null?void 0:s[3])!=null?a:1];return o[1]=1-l[1]-o[1],{KHR_texture_transform:{offset:o,scale:l}}}_v0ParseRenderQueue(n){var e,t;const i=n.shader==="VRM/UnlitTransparentZWrite",r=((e=n.keywordMap)==null?void 0:e._ALPHABLEND_ON)!=null||n.shader==="VRM/UnlitTransparent"||i,a=((t=n.floatProperties)==null?void 0:t._ZWrite)===1||i;let s=0;if(r){const o=n.renderQueue;o!=null&&(a?s=this._renderQueueMapTransparentZWrite.get(o):s=this._renderQueueMapTransparent.get(o))}return s}_populateRenderQueueMap(n){const e=new Set,t=new Set;n.forEach(i=>{var r,a;const s=i.shader==="VRM/UnlitTransparentZWrite",o=((r=i.keywordMap)==null?void 0:r._ALPHABLEND_ON)!=null||i.shader==="VRM/UnlitTransparent"||s,l=((a=i.floatProperties)==null?void 0:a._ZWrite)===1||s;if(o){const u=i.renderQueue;u!=null&&(l?t.add(u):e.add(u))}}),e.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${e.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),t.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${t.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(e).sort().forEach((i,r)=>{const a=Math.min(Math.max(r-e.size+1,-9),0);this._renderQueueMapTransparent.set(i,a)}),Array.from(t).sort().forEach((i,r)=>{const a=Math.min(Math.max(r,0),9);this._renderQueueMapTransparentZWrite.set(i,a)})}},gI=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{o(t.next(l))}catch(u){r(u)}},s=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);o((t=t.apply(n,e)).next())}),dc=new D,Bb=class extends Xi{constructor(n){super(),this._attrPosition=new bt(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(R9);const e=new Ct;e.setAttribute("position",this._attrPosition);const t=new Yi({color:16711935,depthTest:!1,depthWrite:!1});this._line=new Oo(e,t),this.add(this._line),this.constraint=n}updateMatrixWorld(n){dc.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,dc.x,dc.y,dc.z),this.constraint.source&&dc.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,dc.x,dc.y,dc.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(n)}};function vI(n,e){return e.set(n.elements[12],n.elements[13],n.elements[14])}var jte=new D,Zte=new D;function Qte(n,e){return n.decompose(jte,e,Zte),e}function Vy(n){return n.invert?n.invert():n.inverse(),n}var PR=class{constructor(n,e){this.destination=n,this.source=e,this.weight=1}},Kte=new D,Jte=new D,$te=new D,ene=new ft,tne=new ft,nne=new ft,ine=class extends PR{get aimAxis(){return this._aimAxis}set aimAxis(n){this._aimAxis=n,this._v3AimAxis.set(n==="PositiveX"?1:n==="NegativeX"?-1:0,n==="PositiveY"?1:n==="NegativeY"?-1:0,n==="PositiveZ"?1:n==="NegativeZ"?-1:0)}get dependencies(){const n=new Set([this.source]);return this.destination.parent&&n.add(this.destination.parent),n}constructor(n,e){super(n,e),this._aimAxis="PositiveX",this._v3AimAxis=new D(1,0,0),this._dstRestQuat=new ft}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);const n=ene.identity(),e=tne.identity();this.destination.parent&&(Qte(this.destination.parent.matrixWorld,n),Vy(e.copy(n)));const t=Kte.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(n),i=vI(this.source.matrixWorld,Jte).sub(vI(this.destination.matrixWorld,$te)).normalize(),r=nne.setFromUnitVectors(t,i).premultiply(e).multiply(n).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(r,this.weight)}};function rne(n,e){const t=[n];let i=n.parent;for(;i!==null;)t.unshift(i),i=i.parent;t.forEach(r=>{e(r)})}var ane=class{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(n){this._constraints.add(n);let e=this._objectConstraintsMap.get(n.destination);e==null&&(e=new Set,this._objectConstraintsMap.set(n.destination,e)),e.add(n)}deleteConstraint(n){this._constraints.delete(n),this._objectConstraintsMap.get(n.destination).delete(n)}setInitState(){const n=new Set,e=new Set;for(const t of this._constraints)this._processConstraint(t,n,e,i=>i.setInitState())}update(){const n=new Set,e=new Set;for(const t of this._constraints)this._processConstraint(t,n,e,i=>i.update())}_processConstraint(n,e,t,i){if(t.has(n))return;if(e.has(n))throw new Error("VRMNodeConstraintManager: Circular dependency detected while updating constraints");e.add(n);const r=n.dependencies;for(const a of r)rne(a,s=>{const o=this._objectConstraintsMap.get(s);if(o)for(const l of o)this._processConstraint(l,e,t,i)});i(n),t.add(n)}},sne=new ft,one=new ft,lne=class extends PR{get dependencies(){return new Set([this.source])}constructor(n,e){super(n,e),this._dstRestQuat=new ft,this._invSrcRestQuat=new ft}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Vy(this._invSrcRestQuat.copy(this.source.quaternion))}update(){const n=sne.copy(this._invSrcRestQuat).multiply(this.source.quaternion),e=one.copy(this._dstRestQuat).multiply(n);this.destination.quaternion.copy(this._dstRestQuat).slerp(e,this.weight)}},cne=new D,une=new ft,hne=new ft,dne=class extends PR{get rollAxis(){return this._rollAxis}set rollAxis(n){this._rollAxis=n,this._v3RollAxis.set(n==="X"?1:0,n==="Y"?1:0,n==="Z"?1:0)}get dependencies(){return new Set([this.source])}constructor(n,e){super(n,e),this._rollAxis="X",this._v3RollAxis=new D(1,0,0),this._dstRestQuat=new ft,this._invDstRestQuat=new ft,this._invSrcRestQuatMulDstRestQuat=new ft}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Vy(this._invDstRestQuat.copy(this._dstRestQuat)),Vy(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){const n=une.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),e=cne.copy(this._v3RollAxis).applyQuaternion(n),i=hne.setFromUnitVectors(e,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(n);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}},fne=new Set(["1.0","1.0-beta"]),Dz=class C0{get name(){return C0.EXTENSION_NAME}constructor(e,t){this.parser=e,this.helperRoot=t==null?void 0:t.helperRoot}afterRoot(e){return gI(this,null,function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)})}_import(e){return gI(this,null,function*(){var t;const i=this.parser.json;if(!(((t=i.extensionsUsed)==null?void 0:t.indexOf(C0.EXTENSION_NAME))!==-1))return null;const a=new ane,s=yield this.parser.getDependencies("node");return s.forEach((o,l)=>{var u;const d=i.nodes[l],f=(u=d==null?void 0:d.extensions)==null?void 0:u[C0.EXTENSION_NAME];if(f==null)return;const p=f.specVersion;if(!fne.has(p)){console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${C0.EXTENSION_NAME} specVersion "${p}"`);return}const m=f.constraint;if(m.roll!=null){const v=this._importRollConstraint(o,s,m.roll);a.addConstraint(v)}else if(m.aim!=null){const v=this._importAimConstraint(o,s,m.aim);a.addConstraint(v)}else if(m.rotation!=null){const v=this._importRotationConstraint(o,s,m.rotation);a.addConstraint(v)}}),e.scene.updateMatrixWorld(),a.setInitState(),a})}_importRollConstraint(e,t,i){const{source:r,rollAxis:a,weight:s}=i,o=t[r],l=new dne(e,o);if(a!=null&&(l.rollAxis=a),s!=null&&(l.weight=s),this.helperRoot){const u=new Bb(l);this.helperRoot.add(u)}return l}_importAimConstraint(e,t,i){const{source:r,aimAxis:a,weight:s}=i,o=t[r],l=new ine(e,o);if(a!=null&&(l.aimAxis=a),s!=null&&(l.weight=s),this.helperRoot){const u=new Bb(l);this.helperRoot.add(u)}return l}_importRotationConstraint(e,t,i){const{source:r,weight:a}=i,s=t[r],o=new lne(e,s);if(a!=null&&(o.weight=a),this.helperRoot){const l=new Bb(o);this.helperRoot.add(l)}return o}};Dz.EXTENSION_NAME="VRMC_node_constraint";var pne=Dz,dx=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{o(t.next(l))}catch(u){r(u)}},s=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);o((t=t.apply(n,e)).next())}),zR=class{},Fb=new D,ju=new D,Nz=class extends zR{get type(){return"capsule"}constructor(n){var e,t,i,r;super(),this.offset=(e=n==null?void 0:n.offset)!=null?e:new D(0,0,0),this.tail=(t=n==null?void 0:n.tail)!=null?t:new D(0,0,0),this.radius=(i=n==null?void 0:n.radius)!=null?i:0,this.inside=(r=n==null?void 0:n.inside)!=null?r:!1}calculateCollision(n,e,t,i){Fb.setFromMatrixPosition(n),ju.subVectors(this.tail,this.offset).applyMatrix4(n),ju.sub(Fb);const r=ju.lengthSq();i.copy(e).sub(Fb);const a=ju.dot(i);a<=0||(r<=a||ju.multiplyScalar(a/r),i.sub(ju));const s=i.length(),o=this.inside?this.radius-t-s:s-t-this.radius;return o<0&&(i.multiplyScalar(1/s),this.inside&&i.negate()),o}},Hb=new D,_I=new Mt,Oz=class extends zR{get type(){return"plane"}constructor(n){var e,t;super(),this.offset=(e=n==null?void 0:n.offset)!=null?e:new D(0,0,0),this.normal=(t=n==null?void 0:n.normal)!=null?t:new D(0,0,1)}calculateCollision(n,e,t,i){i.setFromMatrixPosition(n),i.negate().add(e),_I.getNormalMatrix(n),Hb.copy(this.normal).applyNormalMatrix(_I).normalize();const r=i.dot(Hb)-t;return i.copy(Hb),r}},mne=new D,Lz=class extends zR{get type(){return"sphere"}constructor(n){var e,t,i;super(),this.offset=(e=n==null?void 0:n.offset)!=null?e:new D(0,0,0),this.radius=(t=n==null?void 0:n.radius)!=null?t:0,this.inside=(i=n==null?void 0:n.inside)!=null?i:!1}calculateCollision(n,e,t,i){i.subVectors(e,mne.setFromMatrixPosition(n));const r=i.length(),a=this.inside?this.radius-t-r:r-t-this.radius;return a<0&&(i.multiplyScalar(1/r),this.inside&&i.negate()),a}},_o=new D,gne=class extends Ct{constructor(n){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new D,this._currentTail=new D,this._shape=n,this._attrPos=new bt(new Float32Array(396),3),this.setAttribute("position",this._attrPos),this._attrIndex=new bt(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;const e=this._shape.radius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,n=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),n=!0);const t=_o.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(t)>1e-10&&(this._currentTail.copy(t),n=!0),n&&this._buildPosition()}_buildPosition(){_o.copy(this._currentTail).sub(this._currentOffset);const n=_o.length()/this._currentRadius;for(let i=0;i<=16;i++){const r=i/16*Math.PI;this._attrPos.setXYZ(i,-Math.sin(r),-Math.cos(r),0),this._attrPos.setXYZ(17+i,n+Math.sin(r),Math.cos(r),0),this._attrPos.setXYZ(34+i,-Math.sin(r),0,-Math.cos(r)),this._attrPos.setXYZ(51+i,n+Math.sin(r),0,Math.cos(r))}for(let i=0;i<32;i++){const r=i/16*Math.PI;this._attrPos.setXYZ(68+i,0,Math.sin(r),Math.cos(r)),this._attrPos.setXYZ(100+i,n,Math.sin(r),Math.cos(r))}const e=Math.atan2(_o.y,Math.sqrt(_o.x*_o.x+_o.z*_o.z)),t=-Math.atan2(_o.z,_o.x);this.rotateZ(e),this.rotateY(t),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<34;n++){const e=(n+1)%34;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(68+n*2,34+n,34+e)}for(let n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(136+n*2,68+n,68+e),this._attrIndex.setXY(200+n*2,100+n,100+e)}this._attrIndex.needsUpdate=!0}},vne=class extends Ct{constructor(n){super(),this.worldScale=1,this._currentOffset=new D,this._currentNormal=new D,this._shape=n,this._attrPos=new bt(new Float32Array(6*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new bt(new Uint16Array(10),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),n=!0),this._currentNormal.equals(this._shape.normal)||(this._currentNormal.copy(this._shape.normal),n=!0),n&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,-.5,-.5,0),this._attrPos.setXYZ(1,.5,-.5,0),this._attrPos.setXYZ(2,.5,.5,0),this._attrPos.setXYZ(3,-.5,.5,0),this._attrPos.setXYZ(4,0,0,0),this._attrPos.setXYZ(5,0,0,.25),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this.lookAt(this._currentNormal),this._attrPos.needsUpdate=!0}_buildIndex(){this._attrIndex.setXY(0,0,1),this._attrIndex.setXY(2,1,2),this._attrIndex.setXY(4,2,3),this._attrIndex.setXY(6,3,0),this._attrIndex.setXY(8,4,5),this._attrIndex.needsUpdate=!0}},_ne=class extends Ct{constructor(n){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new D,this._shape=n,this._attrPos=new bt(new Float32Array(32*3*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new bt(new Uint16Array(64*3),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;const e=this._shape.radius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,n=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),n=!0),n&&this._buildPosition()}_buildPosition(){for(let n=0;n<32;n++){const e=n/16*Math.PI;this._attrPos.setXYZ(n,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+n,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+n,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(64+n*2,32+n,32+e),this._attrIndex.setXY(128+n*2,64+n,64+e)}this._attrIndex.needsUpdate=!0}},xne=new D,Vb=class extends Xi{constructor(n){if(super(),this.matrixAutoUpdate=!1,this.collider=n,this.collider.shape instanceof Lz)this._geometry=new _ne(this.collider.shape);else if(this.collider.shape instanceof Nz)this._geometry=new gne(this.collider.shape);else if(this.collider.shape instanceof Oz)this._geometry=new vne(this.collider.shape);else throw new Error("VRMSpringBoneColliderHelper: Unknown collider shape type detected");const e=new Yi({color:16711935,depthTest:!1,depthWrite:!1});this._line=new va(this._geometry,e),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(n){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);const e=this.matrix.elements;this._geometry.worldScale=xne.set(e[0],e[1],e[2]).length(),this._geometry.update(),super.updateMatrixWorld(n)}},yne=class extends Ct{constructor(n){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new D,this._springBone=n,this._attrPos=new bt(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new bt(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;const e=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,n=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),n=!0),n&&this._buildPosition()}_buildPosition(){for(let n=0;n<32;n++){const e=n/16*Math.PI;this._attrPos.setXYZ(n,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+n,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+n,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(64+n*2,32+n,32+e),this._attrIndex.setXY(128+n*2,64+n,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},Sne=new D,Tne=class extends Xi{constructor(n){super(),this.matrixAutoUpdate=!1,this.springBone=n,this._geometry=new yne(this.springBone);const e=new Yi({color:16776960,depthTest:!1,depthWrite:!1});this._line=new va(this._geometry,e),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(n){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);const e=this.matrix.elements;this._geometry.worldScale=Sne.set(e[0],e[1],e[2]).length(),this._geometry.update(),super.updateMatrixWorld(n)}},Gb=class extends Xt{constructor(n){super(),this.colliderMatrix=new Me,this.shape=n}updateWorldMatrix(n,e){super.updateWorldMatrix(n,e),Ene(this.colliderMatrix,this.matrixWorld,this.shape.offset)}};function Ene(n,e,t){const i=e.elements;n.copy(e),t&&(n.elements[12]=i[0]*t.x+i[4]*t.y+i[8]*t.z+i[12],n.elements[13]=i[1]*t.x+i[5]*t.y+i[9]*t.z+i[13],n.elements[14]=i[2]*t.x+i[6]*t.y+i[10]*t.z+i[14])}var bne=new Me;function Mne(n){return n.invert?n.invert():n.getInverse(bne.copy(n)),n}var Ane=class{constructor(n){this._inverseCache=new Me,this._shouldUpdateInverse=!0,this.matrix=n;const e={set:(t,i,r)=>(this._shouldUpdateInverse=!0,t[i]=r,!0)};this._originalElements=n.elements,n.elements=new Proxy(n.elements,e)}get inverse(){return this._shouldUpdateInverse&&(Mne(this._inverseCache.copy(this.matrix)),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}},kb=new Me,cf=new D,$m=new D,e0=new D,t0=new D,wne=new Me,Rne=class{constructor(n,e,t={},i=[]){this._currentTail=new D,this._prevTail=new D,this._boneAxis=new D,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new Me,this._initialLocalRotation=new ft,this._initialLocalChildPosition=new D;var r,a,s,o,l,u;this.bone=n,this.bone.matrixAutoUpdate=!1,this.child=e,this.settings={hitRadius:(r=t.hitRadius)!=null?r:0,stiffness:(a=t.stiffness)!=null?a:1,gravityPower:(s=t.gravityPower)!=null?s:0,gravityDir:(l=(o=t.gravityDir)==null?void 0:o.clone())!=null?l:new D(0,-1,0),dragForce:(u=t.dragForce)!=null?u:.4},this.colliderGroups=i}get dependencies(){const n=new Set,e=this.bone.parent;e&&n.add(e);for(let t=0;t{e(r)})}function uA(n,e){n.children.forEach(t=>{e(t)||uA(t,e)})}function Dne(n){var e;const t=new Map;for(const i of n){let r=i;do{const a=((e=t.get(r))!=null?e:0)+1;if(a===n.size)return r;t.set(r,a),r=r.parent}while(r!==null)}return null}var xI=class{constructor(){this._joints=new Set,this._sortedJoints=[],this._hasWarnedCircularDependency=!1,this._ancestors=[],this._objectSpringBonesMap=new Map,this._isSortedJointsDirty=!1,this._relevantChildrenUpdated=this._relevantChildrenUpdated.bind(this)}get joints(){return this._joints}get springBones(){return console.warn("VRMSpringBoneManager: springBones is deprecated. use joints instead."),this._joints}get colliderGroups(){const n=new Set;return this._joints.forEach(e=>{e.colliderGroups.forEach(t=>{n.add(t)})}),Array.from(n)}get colliders(){const n=new Set;return this.colliderGroups.forEach(e=>{e.colliders.forEach(t=>{n.add(t)})}),Array.from(n)}addJoint(n){this._joints.add(n);let e=this._objectSpringBonesMap.get(n.bone);e==null&&(e=new Set,this._objectSpringBonesMap.set(n.bone,e)),e.add(n),this._isSortedJointsDirty=!0}addSpringBone(n){console.warn("VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead."),this.addJoint(n)}deleteJoint(n){this._joints.delete(n),this._objectSpringBonesMap.get(n.bone).delete(n),this._isSortedJointsDirty=!0}deleteSpringBone(n){console.warn("VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead."),this.deleteJoint(n)}setInitState(){this._sortJoints();for(let n=0;n{var s,o;return((o=(s=this._objectSpringBonesMap.get(a))==null?void 0:s.size)!=null?o:0)>0?!0:(this._ancestors.push(a),!1)})),this._isSortedJointsDirty=!1}_insertJointSort(n,e,t,i,r){if(t.has(n))return;if(e.has(n)){this._hasWarnedCircularDependency||(console.warn("VRMSpringBoneManager: Circular dependency detected"),this._hasWarnedCircularDependency=!0);return}e.add(n);const a=n.dependencies;for(const s of a){let o=!1,l=null;Cne(s,u=>{const d=this._objectSpringBonesMap.get(u);if(d)for(const f of d)o=!0,this._insertJointSort(f,e,t,i,r);else o||(l=u)}),l&&r.add(l)}i.push(n),t.add(n)}_relevantChildrenUpdated(n){var e,t;return((t=(e=this._objectSpringBonesMap.get(n))==null?void 0:e.size)!=null?t:0)>0?!0:(n.updateWorldMatrix(!1,!1),!1)}},yI="VRMC_springBone_extended_collider",Nne=new Set(["1.0","1.0-beta"]),One=new Set(["1.0"]),Iz=class Af{get name(){return Af.EXTENSION_NAME}constructor(e,t){var i;this.parser=e,this.jointHelperRoot=t==null?void 0:t.jointHelperRoot,this.colliderHelperRoot=t==null?void 0:t.colliderHelperRoot,this.useExtendedColliders=(i=t==null?void 0:t.useExtendedColliders)!=null?i:!0}afterRoot(e){return dx(this,null,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return dx(this,null,function*(){const t=yield this._v1Import(e);if(t!=null)return t;const i=yield this._v0Import(e);return i??null})}_v1Import(e){return dx(this,null,function*(){var t,i,r,a,s;const o=e.parser.json;if(!(((t=o.extensionsUsed)==null?void 0:t.indexOf(Af.EXTENSION_NAME))!==-1))return null;const u=new xI,d=yield e.parser.getDependencies("node"),f=(i=o.extensions)==null?void 0:i[Af.EXTENSION_NAME];if(!f)return null;const p=f.specVersion;if(!Nne.has(p))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${Af.EXTENSION_NAME} specVersion "${p}"`),null;const m=(r=f.colliders)==null?void 0:r.map((x,S)=>{var _,T,E,b,R,w,L,U,N,C,z,W,K,oe,ae;const X=d[x.node];if(X==null)return console.warn(`VRMSpringBoneLoaderPlugin: The collider #${S} attempted to use the node #${x.node} but not found`),null;const te=x.shape,Q=(_=x.extensions)==null?void 0:_[yI];if(this.useExtendedColliders&&Q!=null){const ce=Q.specVersion;if(!One.has(ce))console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${yI} specVersion "${ce}". Fallbacking to the ${Af.EXTENSION_NAME} definition`);else{const se=Q.shape;if(se.sphere)return this._importSphereCollider(X,{offset:new D().fromArray((T=se.sphere.offset)!=null?T:[0,0,0]),radius:(E=se.sphere.radius)!=null?E:0,inside:(b=se.sphere.inside)!=null?b:!1});if(se.capsule)return this._importCapsuleCollider(X,{offset:new D().fromArray((R=se.capsule.offset)!=null?R:[0,0,0]),radius:(w=se.capsule.radius)!=null?w:0,tail:new D().fromArray((L=se.capsule.tail)!=null?L:[0,0,0]),inside:(U=se.capsule.inside)!=null?U:!1});if(se.plane)return this._importPlaneCollider(X,{offset:new D().fromArray((N=se.plane.offset)!=null?N:[0,0,0]),normal:new D().fromArray((C=se.plane.normal)!=null?C:[0,0,1])})}}if(te.sphere)return this._importSphereCollider(X,{offset:new D().fromArray((z=te.sphere.offset)!=null?z:[0,0,0]),radius:(W=te.sphere.radius)!=null?W:0,inside:!1});if(te.capsule)return this._importCapsuleCollider(X,{offset:new D().fromArray((K=te.capsule.offset)!=null?K:[0,0,0]),radius:(oe=te.capsule.radius)!=null?oe:0,tail:new D().fromArray((ae=te.capsule.tail)!=null?ae:[0,0,0]),inside:!1});throw new Error(`VRMSpringBoneLoaderPlugin: The collider #${S} has no valid shape`)}),v=(a=f.colliderGroups)==null?void 0:a.map((x,S)=>{var _;return{colliders:((_=x.colliders)!=null?_:[]).flatMap(E=>{const b=m==null?void 0:m[E];return b??(console.warn(`VRMSpringBoneLoaderPlugin: The colliderGroup #${S} attempted to use a collider #${E} but not found`),[])}),name:x.name}});return(s=f.springs)==null||s.forEach((x,S)=>{var _;const T=x.joints,E=(_=x.colliderGroups)==null?void 0:_.map(w=>{const L=v==null?void 0:v[w];if(L==null)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${S} attempted to use a colliderGroup ${w} but not found`);return L}),b=x.center!=null?d[x.center]:void 0;let R;T.forEach(w=>{if(R){const L=R.node,U=d[L],N=w.node,C=d[N],z={hitRadius:R.hitRadius,dragForce:R.dragForce,gravityPower:R.gravityPower,stiffness:R.stiffness,gravityDir:R.gravityDir!=null?new D().fromArray(R.gravityDir):void 0},W=this._importJoint(U,C,z,E);b&&(W.center=b),u.addJoint(W)}R=w})}),u.setInitState(),u})}_v0Import(e){return dx(this,null,function*(){var t,i,r;const a=e.parser.json;if(!(((t=a.extensionsUsed)==null?void 0:t.indexOf("VRM"))!==-1))return null;const o=(i=a.extensions)==null?void 0:i.VRM,l=o==null?void 0:o.secondaryAnimation;if(!l)return null;const u=l==null?void 0:l.boneGroups;if(!u)return null;const d=new xI,f=yield e.parser.getDependencies("node"),p=(r=l.colliderGroups)==null?void 0:r.map(m=>{var v;const x=f[m.node];return{colliders:((v=m.colliders)!=null?v:[]).map((_,T)=>{var E,b,R;const w=new D(0,0,0);return _.offset&&w.set((E=_.offset.x)!=null?E:0,(b=_.offset.y)!=null?b:0,_.offset.z?-_.offset.z:0),this._importSphereCollider(x,{offset:w,radius:(R=_.radius)!=null?R:0,inside:!1})})}});return u==null||u.forEach((m,v)=>{const x=m.bones;x&&x.forEach(S=>{var _,T,E,b;const R=f[S],w=new D;m.gravityDir?w.set((_=m.gravityDir.x)!=null?_:0,(T=m.gravityDir.y)!=null?T:0,(E=m.gravityDir.z)!=null?E:0):w.set(0,-1,0);const L=m.center!=null?f[m.center]:void 0,U={hitRadius:m.hitRadius,dragForce:m.dragForce,gravityPower:m.gravityPower,stiffness:m.stiffiness,gravityDir:w},N=(b=m.colliderGroups)==null?void 0:b.map(C=>{const z=p==null?void 0:p[C];if(z==null)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${v} attempted to use a colliderGroup ${C} but not found`);return z});R.traverse(C=>{var z;const W=(z=C.children[0])!=null?z:null,K=this._importJoint(C,W,U,N);L&&(K.center=L),d.addJoint(K)})})}),e.scene.updateMatrixWorld(),d.setInitState(),d})}_importJoint(e,t,i,r){const a=new Rne(e,t,i,r);if(this.jointHelperRoot){const s=new Tne(a);this.jointHelperRoot.add(s),s.renderOrder=this.jointHelperRoot.renderOrder}return a}_importSphereCollider(e,t){const i=new Lz(t),r=new Gb(i);if(e.add(r),this.colliderHelperRoot){const a=new Vb(r);this.colliderHelperRoot.add(a),a.renderOrder=this.colliderHelperRoot.renderOrder}return r}_importCapsuleCollider(e,t){const i=new Nz(t),r=new Gb(i);if(e.add(r),this.colliderHelperRoot){const a=new Vb(r);this.colliderHelperRoot.add(a),a.renderOrder=this.colliderHelperRoot.renderOrder}return r}_importPlaneCollider(e,t){const i=new Oz(t),r=new Gb(i);if(e.add(r),this.colliderHelperRoot){const a=new Vb(r);this.colliderHelperRoot.add(a),a.renderOrder=this.colliderHelperRoot.renderOrder}return r}};Iz.EXTENSION_NAME="VRMC_springBone";var Lne=Iz,Ine=class{get name(){return"VRMLoaderPlugin"}constructor(n,e){var t,i,r,a,s,o,l,u,d,f;this.parser=n;const p=e==null?void 0:e.helperRoot,m=e==null?void 0:e.autoUpdateHumanBones;this.expressionPlugin=(t=e==null?void 0:e.expressionPlugin)!=null?t:new Qee(n),this.firstPersonPlugin=(i=e==null?void 0:e.firstPersonPlugin)!=null?i:new Jee(n),this.humanoidPlugin=(r=e==null?void 0:e.humanoidPlugin)!=null?r:new ate(n,{helperRoot:p,autoUpdateHumanBones:m}),this.lookAtPlugin=(a=e==null?void 0:e.lookAtPlugin)!=null?a:new yte(n,{helperRoot:p}),this.metaPlugin=(s=e==null?void 0:e.metaPlugin)!=null?s:new Ete(n),this.mtoonMaterialPlugin=(o=e==null?void 0:e.mtoonMaterialPlugin)!=null?o:new Bte(n),this.materialsHDREmissiveMultiplierPlugin=(l=e==null?void 0:e.materialsHDREmissiveMultiplierPlugin)!=null?l:new Hte(n),this.materialsV0CompatPlugin=(u=e==null?void 0:e.materialsV0CompatPlugin)!=null?u:new Yte(n),this.springBonePlugin=(d=e==null?void 0:e.springBonePlugin)!=null?d:new Lne(n,{colliderHelperRoot:p,jointHelperRoot:p}),this.nodeConstraintPlugin=(f=e==null?void 0:e.nodeConstraintPlugin)!=null?f:new pne(n,{helperRoot:p})}beforeRoot(){return cx(this,null,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(n){return cx(this,null,function*(){return yield this.mtoonMaterialPlugin.loadMesh(n)})}getMaterialType(n){const e=this.mtoonMaterialPlugin.getMaterialType(n);return e??null}extendMaterialParams(n,e){return cx(this,null,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(n,e),yield this.mtoonMaterialPlugin.extendMaterialParams(n,e)})}afterRoot(n){return cx(this,null,function*(){yield this.metaPlugin.afterRoot(n),yield this.humanoidPlugin.afterRoot(n),yield this.expressionPlugin.afterRoot(n),yield this.lookAtPlugin.afterRoot(n),yield this.firstPersonPlugin.afterRoot(n),yield this.springBonePlugin.afterRoot(n),yield this.nodeConstraintPlugin.afterRoot(n),yield this.mtoonMaterialPlugin.afterRoot(n);const e=n.userData.vrmMeta,t=n.userData.vrmHumanoid;if(e&&t){const i=new Mte({scene:n.scene,expressionManager:n.userData.vrmExpressionManager,firstPerson:n.userData.vrmFirstPerson,humanoid:t,lookAt:n.userData.vrmLookAt,meta:e,materials:n.userData.vrmMToonMaterials,springBoneManager:n.userData.vrmSpringBoneManager,nodeConstraintManager:n.userData.vrmNodeConstraintManager});n.userData.vrm=i}})}};function Une(n){const e=new Set;return n.traverse(t=>{if(!t.isMesh)return;const i=t;e.add(i)}),e}function SI(n,e,t){if(e.size===1){const s=e.values().next().value;if(s.weight===1)return n[s.index]}const i=new Float32Array(n[0].count*3);let r=0;if(t)r=1;else for(const s of e)r+=s.weight;for(const s of e){const o=n[s.index],l=s.weight/r;for(let u=0;ud.getOrCreate(N)).join(","),L=`${b};${_};${w}`;let U=o.get(L);U==null&&(U=E.clone(),Gne(U,R,v),o.set(L,U)),T.geometry.setAttribute("skinIndex",U)}for(const T of m)T.bind(S,new Me)}}function Bne(n){const e=new Set;return n.traverse(t=>{if(!t.isSkinnedMesh)return;const i=t;e.add(i)}),e}function Fne(n,e){const t=new Set;for(let i=0;it)return!1;return!0}var Wb=class{constructor(){this._objectIndexMap=new Map,this._index=0}get(n){return this._objectIndexMap.get(n)}getOrCreate(n){let e=this._objectIndexMap.get(n);return e==null&&(e=this._index,this._objectIndexMap.set(n,e),this._index++),e}};function Wne(n){var e,t,i,r;const a=new Ct;a.name=n.name,a.setIndex(n.index);for(const[s,o]of Object.entries(n.attributes))a.setAttribute(s,o);for(const[s,o]of Object.entries(n.morphAttributes)){const l=s;a.morphAttributes[l]=o.concat()}a.morphTargetsRelative=n.morphTargetsRelative,a.groups=[];for(const s of n.groups)a.addGroup(s.start,s.count,s.materialIndex);return a.boundingSphere=(t=(e=n.boundingSphere)==null?void 0:e.clone())!=null?t:null,a.boundingBox=(r=(i=n.boundingBox)==null?void 0:i.clone())!=null?r:null,a.drawRange.start=n.drawRange.start,a.drawRange.count=n.drawRange.count,a.userData=n.userData,a}function TI(n){if(Object.values(n).forEach(e=>{e!=null&&e.isTexture&&e.dispose()}),n.isShaderMaterial){const e=n.uniforms;e&&Object.values(e).forEach(t=>{const i=t.value;i!=null&&i.isTexture&&i.dispose()})}n.dispose()}function Xne(n){const e=n.geometry;e&&e.dispose();const t=n.skeleton;t&&t.dispose();const i=n.material;i&&(Array.isArray(i)?i.forEach(r=>TI(r)):i&&TI(i))}function qne(n){n.traverse(Xne)}function Yne(n,e){var t,i;console.warn("VRMUtils.removeUnnecessaryJoints: removeUnnecessaryJoints is deprecated. Use combineSkeletons instead. combineSkeletons contributes more to the performance improvement. This function will be removed in the next major version.");const r=(t=e==null?void 0:e.experimentalSameBoneCounts)!=null?t:!1,a=[];n.traverse(l=>{l.type==="SkinnedMesh"&&a.push(l)});const s=new Map;let o=0;for(const l of a){const d=l.geometry.getAttribute("skinIndex");if(s.has(d))continue;const f=new Map,p=new Map;for(let m=0;m{var i,r,a,s;if(!t.isMesh)return;const o=t,l=o.geometry,u=l.index;if(u==null)return;const d=e.get(l);if(d!=null){o.geometry=d;return}const f=Object.values(l.attributes)[0].count,p=new Array(f);let m=0;const v=u.array;for(let b=0;b{T.addGroup(b.start,b.count,b.materialIndex)}),T.boundingBox=(r=(i=l.boundingBox)==null?void 0:i.clone())!=null?r:null,T.boundingSphere=(s=(a=l.boundingSphere)==null?void 0:a.clone())!=null?s:null,T.setDrawRange(l.drawRange.start,l.drawRange.count),T.userData=l.userData,e.set(l,T);{const b=u.array,R=new b.constructor(b.length);for(let w=0;w{const R=l.attributes[b];if(R.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const w=R.array,{itemSize:L,normalized:U}=R,N=new w.constructor(S.length*L);S.forEach((C,z)=>{for(let W=0;W{for(let ae=0;aeK===0),T.morphAttributes[w][L]=new bt(W,C,z)}}E&&(T.morphAttributes={}),o.geometry=T}),Array.from(e.keys()).forEach(t=>{t.dispose()})}function Zne(n){var e;((e=n.meta)==null?void 0:e.metaVersion)==="0"&&(n.scene.rotation.y=Math.PI)}var rd=class{constructor(){}};rd.combineMorphs=Pne;rd.combineSkeletons=zne;rd.deepDispose=qne;rd.removeUnnecessaryJoints=Yne;rd.removeUnnecessaryVertices=jne;rd.rotateVRM0=Zne;/*! + * @pixiv/three-vrm-core v3.4.4 + * The implementation of core features of VRM, for @pixiv/three-vrm + * + * Copyright (c) 2019-2025 pixiv Inc. + * @pixiv/three-vrm-core is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + *//*! + * @pixiv/three-vrm-materials-mtoon v3.4.4 + * MToon (toon material) module for @pixiv/three-vrm + * + * Copyright (c) 2019-2025 pixiv Inc. + * @pixiv/three-vrm-materials-mtoon is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + *//*! + * @pixiv/three-vrm-materials-hdr-emissive-multiplier v3.4.4 + * Support VRMC_hdr_emissiveMultiplier for @pixiv/three-vrm + * + * Copyright (c) 2019-2025 pixiv Inc. + * @pixiv/three-vrm-materials-hdr-emissive-multiplier is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + *//*! + * @pixiv/three-vrm-materials-v0compat v3.4.4 + * VRM0.0 materials compatibility layer plugin for @pixiv/three-vrm + * + * Copyright (c) 2019-2025 pixiv Inc. + * @pixiv/three-vrm-materials-v0compat is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + *//*! + * @pixiv/three-vrm-node-constraint v3.4.4 + * Node constraint module for @pixiv/three-vrm + * + * Copyright (c) 2019-2025 pixiv Inc. + * @pixiv/three-vrm-node-constraint is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + *//*! + * @pixiv/three-vrm-springbone v3.4.4 + * Spring bone module for @pixiv/three-vrm + * + * Copyright (c) 2019-2025 pixiv Inc. + * @pixiv/three-vrm-springbone is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + *//*! + * @pixiv/three-vrm-animation v3.4.4 + * The implementation of VRM Animation + * + * Copyright (c) 2019-2025 pixiv Inc. + * @pixiv/three-vrm-animation is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + */var EI=(n,e,t)=>new Promise((i,r)=>{var a=l=>{try{o(t.next(l))}catch(u){r(u)}},s=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,s);o((t=t.apply(n,e)).next())}),Qne={Aa:"aa",Ih:"ih",Ou:"ou",Ee:"ee",Oh:"oh",Blink:"blink",Happy:"happy",Angry:"angry",Sad:"sad",Relaxed:"relaxed",LookUp:"lookUp",Surprised:"surprised",LookDown:"lookDown",LookLeft:"lookLeft",LookRight:"lookRight",BlinkLeft:"blinkLeft",BlinkRight:"blinkRight",Neutral:"neutral"};new Ye;new re;new D;new D;var bI={hips:null,spine:"hips",chest:"spine",upperChest:"chest",neck:"upperChest",head:"neck",leftEye:"head",rightEye:"head",jaw:"head",leftUpperLeg:"hips",leftLowerLeg:"leftUpperLeg",leftFoot:"leftLowerLeg",leftToes:"leftFoot",rightUpperLeg:"hips",rightLowerLeg:"rightUpperLeg",rightFoot:"rightLowerLeg",rightToes:"rightFoot",leftShoulder:"upperChest",leftUpperArm:"leftShoulder",leftLowerArm:"leftUpperArm",leftHand:"leftLowerArm",rightShoulder:"upperChest",rightUpperArm:"rightShoulder",rightLowerArm:"rightUpperArm",rightHand:"rightLowerArm",leftThumbMetacarpal:"leftHand",leftThumbProximal:"leftThumbMetacarpal",leftThumbDistal:"leftThumbProximal",leftIndexProximal:"leftHand",leftIndexIntermediate:"leftIndexProximal",leftIndexDistal:"leftIndexIntermediate",leftMiddleProximal:"leftHand",leftMiddleIntermediate:"leftMiddleProximal",leftMiddleDistal:"leftMiddleIntermediate",leftRingProximal:"leftHand",leftRingIntermediate:"leftRingProximal",leftRingDistal:"leftRingIntermediate",leftLittleProximal:"leftHand",leftLittleIntermediate:"leftLittleProximal",leftLittleDistal:"leftLittleIntermediate",rightThumbMetacarpal:"rightHand",rightThumbProximal:"rightThumbMetacarpal",rightThumbDistal:"rightThumbProximal",rightIndexProximal:"rightHand",rightIndexIntermediate:"rightIndexProximal",rightIndexDistal:"rightIndexIntermediate",rightMiddleProximal:"rightHand",rightMiddleIntermediate:"rightMiddleProximal",rightMiddleDistal:"rightMiddleIntermediate",rightRingProximal:"rightHand",rightRingIntermediate:"rightRingProximal",rightRingDistal:"rightRingIntermediate",rightLittleProximal:"rightHand",rightLittleIntermediate:"rightLittleProximal",rightLittleDistal:"rightLittleIntermediate"};function Kne(n){return n.invert?n.invert():n.inverse(),n}new D;new D;new D;new D;new D;new D(0,1,0);var Jne=new D,$ne=new D;function eie(n,e){return n.matrixWorld.decompose(Jne,e,$ne),e}function Xb(n){return[Math.atan2(-n.z,n.x),Math.atan2(n.y,Math.sqrt(n.x*n.x+n.z*n.z))]}function MI(n){const e=Math.round(n/2/Math.PI);return n-2*Math.PI*e}var AI=new D(0,0,1),tie=new D,nie=new D,iie=new D,rie=new ft,qb=new ft,wI=new ft,aie=new ft,Yb=new Ai,Pz=class zz{constructor(e,t){this.offsetFromHeadBone=new D,this.autoUpdate=!0,this.faceFront=new D(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new ft)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn("VRMLookAt: euler is deprecated. use getEuler() instead."),this.getEuler(new Ai)}getEuler(e){return e.set(lt.DEG2RAD*this._pitch,lt.DEG2RAD*this._yaw,0,"YXZ")}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMLookAt: humanoid must be same in order to copy");return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new zz(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){const t=this.humanoid.getRawBoneNode("head");return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){const t=this.humanoid.getRawBoneNode("head");return eie(t,e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(AI)<.01)return e.copy(this._restHeadWorldQuaternion).invert();const[t,i]=Xb(this.faceFront);return Yb.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(Yb).premultiply(aie.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(qb),this.getFaceFrontQuaternion(wI),e.copy(AI).applyQuaternion(qb).applyQuaternion(wI).applyEuler(this.getEuler(Yb))}lookAt(e){const t=rie.copy(this._restHeadWorldQuaternion).multiply(Kne(this.getLookAtWorldQuaternion(qb))),i=this.getLookAtWorldPosition(nie),r=iie.copy(e).sub(i).applyQuaternion(t).normalize(),[a,s]=Xb(this.faceFront),[o,l]=Xb(r),u=MI(o-a),d=MI(s-l);this._yaw=lt.RAD2DEG*u,this._pitch=lt.RAD2DEG*d,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(tie)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};Pz.EULER_ORDER="YXZ";var sie=Pz;new D(0,0,1);new Ai(0,0,0,"YXZ");var RI=180/Math.PI,jb=new Ai,CI=class extends Xt{constructor(n){super(),this.vrmLookAt=n,this.type="VRMLookAtQuaternionProxy";const e=this.rotation._onChangeCallback;this.rotation._onChange(()=>{e(),this._applyToLookAt()});const t=this.quaternion._onChangeCallback;this.quaternion._onChange(()=>{t(),this._applyToLookAt()})}_applyToLookAt(){jb.setFromQuaternion(this.quaternion,sie.EULER_ORDER),this.vrmLookAt.yaw=RI*jb.y,this.vrmLookAt.pitch=RI*jb.x}};function oie(n,e,t){var i,r;const a=new Map,s=new Map;for(const[o,l]of n.humanoidTracks.rotation.entries()){const u=(i=e.getNormalizedBoneNode(o))==null?void 0:i.name;if(u!=null){const d=new nu(`${u}.quaternion`,l.times,l.values.map((f,p)=>t==="0"&&p%2===0?-f:f));s.set(o,d)}}for(const[o,l]of n.humanoidTracks.translation.entries()){const u=(r=e.getNormalizedBoneNode(o))==null?void 0:r.name;if(u!=null){const d=n.restHipsPosition.y,p=e.normalizedRestPose.hips.position[1]/d,m=l.clone();m.values=m.values.map((v,x)=>(t==="0"&&x%3!==1?-v:v)*p),m.name=`${u}.position`,a.set(o,m)}}return{translation:a,rotation:s}}function lie(n,e){const t=new Map,i=new Map;for(const[r,a]of n.expressionTracks.preset.entries()){const s=e.getExpressionTrackName(r);if(s!=null){const o=a.clone();o.name=s,t.set(r,o)}}for(const[r,a]of n.expressionTracks.custom.entries()){const s=e.getExpressionTrackName(r);if(s!=null){const o=a.clone();o.name=s,i.set(r,o)}}return{preset:t,custom:i}}function cie(n,e){if(n.lookAtTrack==null)return null;const t=n.lookAtTrack.clone();return t.name=e,t}function uie(n,e){const t=[],i=oie(n,e.humanoid,e.meta.metaVersion);if(t.push(...i.translation.values()),t.push(...i.rotation.values()),e.expressionManager!=null){const r=lie(n,e.expressionManager);t.push(...r.preset.values()),t.push(...r.custom.values())}if(e.lookAt!=null){let r=e.scene.children.find(s=>s instanceof CI);r==null?(console.warn("createVRMAnimationClip: VRMLookAtQuaternionProxy is not found. Creating a new one automatically. To suppress this warning, create a VRMLookAtQuaternionProxy manually"),r=new CI(e.lookAt),r.name="VRMLookAtQuaternionProxy",e.scene.add(r)):r.name===""&&(console.warn("createVRMAnimationClip: VRMLookAtQuaternionProxy is found but its name is not set. Setting the name automatically. To suppress this warning, set the name manually"),r.name="VRMLookAtQuaternionProxy");const a=cie(n,`${r.name}.quaternion`);a!=null&&t.push(a)}return new Vh("Clip",n.duration,t)}var hie=class{constructor(){this.duration=0,this.restHipsPosition=new D,this.humanoidTracks={translation:new Map,rotation:new Map},this.expressionTracks={preset:new Map,custom:new Map},this.lookAtTrack=null}};function DI(n,e){const t=n.length,i=[];let r=[],a=0;for(let s=0;s{const _=r.animations[S],T=this._parseAnimation(x,_,l,u);return T.restHipsPosition=p,T});n.userData.vrmAnimations=v})}_createNodeMap(n){var e,t,i,r,a;const s=new Map,o=new Map,l=(e=n.humanoid)==null?void 0:e.humanBones;l&&Object.entries(l).forEach(([p,m])=>{const v=m==null?void 0:m.node;v!=null&&s.set(v,p)});const u=(t=n.expressions)==null?void 0:t.preset;u&&Object.entries(u).forEach(([p,m])=>{const v=m==null?void 0:m.node;v!=null&&o.set(v,p)});const d=(i=n.expressions)==null?void 0:i.custom;d&&Object.entries(d).forEach(([p,m])=>{const{node:v}=m;o.set(v,p)});const f=(a=(r=n.lookAt)==null?void 0:r.node)!=null?a:null;return{humanoidIndexToName:s,expressionsIndexToName:o,lookAtIndex:f}}_createBoneWorldMatrixMap(n,e){return EI(this,null,function*(){var t,i;n.scene.updateWorldMatrix(!1,!0);const r=yield n.parser.getDependencies("node"),a=new Map;if(e.humanoid==null)return a;for(const[s,o]of Object.entries(e.humanoid.humanBones)){const l=o==null?void 0:o.node;if(l!=null){const u=r[l];a.set(s,u.matrixWorld),s==="hips"&&a.set("hipsParent",(i=(t=u.parent)==null?void 0:t.matrixWorld)!=null?i:die)}}return a})}_parseAnimation(n,e,t,i){const r=n.tracks,a=e.channels,s=new hie;return s.duration=n.duration,a.forEach((o,l)=>{const{node:u,path:d}=o.target,f=r[l];if(u==null)return;const p=t.humanoidIndexToName.get(u);if(p!=null){let v=bI[p];for(;v!=null&&i.get(v)==null;)v=bI[v];if(v==null&&(v="hipsParent"),d==="translation")if(p!=="hips")console.warn(`The loading animation contains a translation track for ${p}, which is not permitted in the VRMC_vrm_animation spec. ignoring the track`);else{const x=i.get("hipsParent"),S=DI(f.values,3).flatMap(T=>n0.fromArray(T).applyMatrix4(x).toArray()),_=f.clone();_.values=new Float32Array(S),s.humanoidTracks.translation.set(p,_)}else if(d==="rotation"){const x=i.get(p),S=i.get(v);x.decompose(n0,Zb,n0),Zb.invert(),S.decompose(n0,NI,n0);const _=DI(f.values,4).flatMap(E=>fie.fromArray(E).premultiply(NI).multiply(Zb).toArray()),T=f.clone();T.values=new Float32Array(_),s.humanoidTracks.rotation.set(p,T)}else throw new Error(`Invalid path "${d}"`);return}const m=t.expressionsIndexToName.get(u);if(m!=null){if(d==="translation"){const v=f.times,x=new Float32Array(f.values.length/3);for(let _=0;_e in n?vie(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,xie=(n,e,t)=>(_ie(n,e+"",t),t);class yie{constructor(){xie(this,"_listeners")}addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;const r=this._listeners[e];if(r!==void 0){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const i=this._listeners[e.type];if(i!==void 0){e.target=this;const r=i.slice(0);for(let a=0,s=r.length;ae in n?Sie(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Lt=(n,e,t)=>(Tie(n,typeof e!="symbol"?e+"":e,t),t);const fx=new Pr,OI=new xs,Eie=Math.cos(70*(Math.PI/180)),LI=(n,e)=>(n%e+e)%e;let bie=class extends yie{constructor(e,t){super(),Lt(this,"object"),Lt(this,"domElement"),Lt(this,"enabled",!0),Lt(this,"target",new D),Lt(this,"minDistance",0),Lt(this,"maxDistance",1/0),Lt(this,"minZoom",0),Lt(this,"maxZoom",1/0),Lt(this,"minPolarAngle",0),Lt(this,"maxPolarAngle",Math.PI),Lt(this,"minAzimuthAngle",-1/0),Lt(this,"maxAzimuthAngle",1/0),Lt(this,"enableDamping",!1),Lt(this,"dampingFactor",.05),Lt(this,"enableZoom",!0),Lt(this,"zoomSpeed",1),Lt(this,"enableRotate",!0),Lt(this,"rotateSpeed",1),Lt(this,"enablePan",!0),Lt(this,"panSpeed",1),Lt(this,"screenSpacePanning",!0),Lt(this,"keyPanSpeed",7),Lt(this,"zoomToCursor",!1),Lt(this,"autoRotate",!1),Lt(this,"autoRotateSpeed",2),Lt(this,"reverseOrbit",!1),Lt(this,"reverseHorizontalOrbit",!1),Lt(this,"reverseVerticalOrbit",!1),Lt(this,"keys",{LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"}),Lt(this,"mouseButtons",{LEFT:rh.ROTATE,MIDDLE:rh.DOLLY,RIGHT:rh.PAN}),Lt(this,"touches",{ONE:ah.ROTATE,TWO:ah.DOLLY_PAN}),Lt(this,"target0"),Lt(this,"position0"),Lt(this,"zoom0"),Lt(this,"_domElementKeyEvents",null),Lt(this,"getPolarAngle"),Lt(this,"getAzimuthalAngle"),Lt(this,"setPolarAngle"),Lt(this,"setAzimuthalAngle"),Lt(this,"getDistance"),Lt(this,"getZoomScale"),Lt(this,"listenToKeyEvents"),Lt(this,"stopListenToKeyEvents"),Lt(this,"saveState"),Lt(this,"reset"),Lt(this,"update"),Lt(this,"connect"),Lt(this,"dispose"),Lt(this,"dollyIn"),Lt(this,"dollyOut"),Lt(this,"getScale"),Lt(this,"setScale"),this.object=e,this.domElement=t,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this.getPolarAngle=()=>d.phi,this.getAzimuthalAngle=()=>d.theta,this.setPolarAngle=J=>{let me=LI(J,2*Math.PI),Le=d.phi;Le<0&&(Le+=2*Math.PI),me<0&&(me+=2*Math.PI);let j=Math.abs(me-Le);2*Math.PI-j{let me=LI(J,2*Math.PI),Le=d.theta;Le<0&&(Le+=2*Math.PI),me<0&&(me+=2*Math.PI);let j=Math.abs(me-Le);2*Math.PI-ji.object.position.distanceTo(i.target),this.listenToKeyEvents=J=>{J.addEventListener("keydown",Se),this._domElementKeyEvents=J},this.stopListenToKeyEvents=()=>{this._domElementKeyEvents.removeEventListener("keydown",Se),this._domElementKeyEvents=null},this.saveState=()=>{i.target0.copy(i.target),i.position0.copy(i.object.position),i.zoom0=i.object.zoom},this.reset=()=>{i.target.copy(i.target0),i.object.position.copy(i.position0),i.object.zoom=i.zoom0,i.object.updateProjectionMatrix(),i.dispatchEvent(r),i.update(),l=o.NONE},this.update=(()=>{const J=new D,me=new D(0,1,0),Le=new ft().setFromUnitVectors(e.up,me),j=Le.clone().invert(),ke=new D,ge=new ft,We=2*Math.PI;return function(){const Re=i.object.position;Le.setFromUnitVectors(e.up,me),j.copy(Le).invert(),J.copy(Re).sub(i.target),J.applyQuaternion(Le),d.setFromVector3(J),i.autoRotate&&l===o.NONE&&oe(W()),i.enableDamping?(d.theta+=f.theta*i.dampingFactor,d.phi+=f.phi*i.dampingFactor):(d.theta+=f.theta,d.phi+=f.phi);let at=i.minAzimuthAngle,Et=i.maxAzimuthAngle;isFinite(at)&&isFinite(Et)&&(at<-Math.PI?at+=We:at>Math.PI&&(at-=We),Et<-Math.PI?Et+=We:Et>Math.PI&&(Et-=We),at<=Et?d.theta=Math.max(at,Math.min(Et,d.theta)):d.theta=d.theta>(at+Et)/2?Math.max(at,d.theta):Math.min(Et,d.theta)),d.phi=Math.max(i.minPolarAngle,Math.min(i.maxPolarAngle,d.phi)),d.makeSafe(),i.enableDamping===!0?i.target.addScaledVector(m,i.dampingFactor):i.target.add(m),i.zoomToCursor&&N||i.object.isOrthographicCamera?d.radius=nt(d.radius):d.radius=nt(d.radius*p),J.setFromSpherical(d),J.applyQuaternion(j),Re.copy(i.target).add(J),i.object.matrixAutoUpdate||i.object.updateMatrix(),i.object.lookAt(i.target),i.enableDamping===!0?(f.theta*=1-i.dampingFactor,f.phi*=1-i.dampingFactor,m.multiplyScalar(1-i.dampingFactor)):(f.set(0,0,0),m.set(0,0,0));let Gt=!1;if(i.zoomToCursor&&N){let kt=null;if(i.object instanceof si&&i.object.isPerspectiveCamera){const mi=J.length();kt=nt(mi*p);const gi=mi-kt;i.object.position.addScaledVector(L,gi),i.object.updateMatrixWorld()}else if(i.object.isOrthographicCamera){const mi=new D(U.x,U.y,0);mi.unproject(i.object),i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/p)),i.object.updateProjectionMatrix(),Gt=!0;const gi=new D(U.x,U.y,0);gi.unproject(i.object),i.object.position.sub(gi).add(mi),i.object.updateMatrixWorld(),kt=J.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),i.zoomToCursor=!1;kt!==null&&(i.screenSpacePanning?i.target.set(0,0,-1).transformDirection(i.object.matrix).multiplyScalar(kt).add(i.object.position):(fx.origin.copy(i.object.position),fx.direction.set(0,0,-1).transformDirection(i.object.matrix),Math.abs(i.object.up.dot(fx.direction))u||8*(1-ge.dot(i.object.quaternion))>u?(i.dispatchEvent(r),ke.copy(i.object.position),ge.copy(i.object.quaternion),Gt=!1,!0):!1}})(),this.connect=J=>{i.domElement=J,i.domElement.style.touchAction="none",i.domElement.addEventListener("contextmenu",Tt),i.domElement.addEventListener("pointerdown",ht),i.domElement.addEventListener("pointercancel",P),i.domElement.addEventListener("wheel",Ie)},this.dispose=()=>{var J,me,Le,j,ke,ge;i.domElement&&(i.domElement.style.touchAction="auto"),(J=i.domElement)==null||J.removeEventListener("contextmenu",Tt),(me=i.domElement)==null||me.removeEventListener("pointerdown",ht),(Le=i.domElement)==null||Le.removeEventListener("pointercancel",P),(j=i.domElement)==null||j.removeEventListener("wheel",Ie),(ke=i.domElement)==null||ke.ownerDocument.removeEventListener("pointermove",k),(ge=i.domElement)==null||ge.ownerDocument.removeEventListener("pointerup",P),i._domElementKeyEvents!==null&&i._domElementKeyEvents.removeEventListener("keydown",Se)};const i=this,r={type:"change"},a={type:"start"},s={type:"end"},o={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let l=o.NONE;const u=1e-6,d=new Iy,f=new Iy;let p=1;const m=new D,v=new re,x=new re,S=new re,_=new re,T=new re,E=new re,b=new re,R=new re,w=new re,L=new D,U=new re;let N=!1;const C=[],z={};function W(){return 2*Math.PI/60/60*i.autoRotateSpeed}function K(){return Math.pow(.95,i.zoomSpeed)}function oe(J){i.reverseOrbit||i.reverseHorizontalOrbit?f.theta+=J:f.theta-=J}function ae(J){i.reverseOrbit||i.reverseVerticalOrbit?f.phi+=J:f.phi-=J}const X=(()=>{const J=new D;return function(Le,j){J.setFromMatrixColumn(j,0),J.multiplyScalar(-Le),m.add(J)}})(),te=(()=>{const J=new D;return function(Le,j){i.screenSpacePanning===!0?J.setFromMatrixColumn(j,1):(J.setFromMatrixColumn(j,0),J.crossVectors(i.object.up,J)),J.multiplyScalar(Le),m.add(J)}})(),Q=(()=>{const J=new D;return function(Le,j){const ke=i.domElement;if(ke&&i.object instanceof si&&i.object.isPerspectiveCamera){const ge=i.object.position;J.copy(ge).sub(i.target);let We=J.length();We*=Math.tan(i.object.fov/2*Math.PI/180),X(2*Le*We/ke.clientHeight,i.object.matrix),te(2*j*We/ke.clientHeight,i.object.matrix)}else ke&&i.object instanceof Za&&i.object.isOrthographicCamera?(X(Le*(i.object.right-i.object.left)/i.object.zoom/ke.clientWidth,i.object.matrix),te(j*(i.object.top-i.object.bottom)/i.object.zoom/ke.clientHeight,i.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),i.enablePan=!1)}})();function ce(J){i.object instanceof si&&i.object.isPerspectiveCamera||i.object instanceof Za&&i.object.isOrthographicCamera?p=J:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function se(J){ce(p/J)}function De(J){ce(p*J)}function Xe(J){if(!i.zoomToCursor||!i.domElement)return;N=!0;const me=i.domElement.getBoundingClientRect(),Le=J.clientX-me.left,j=J.clientY-me.top,ke=me.width,ge=me.height;U.x=Le/ke*2-1,U.y=-(j/ge)*2+1,L.set(U.x,U.y,1).unproject(i.object).sub(i.object.position).normalize()}function nt(J){return Math.max(i.minDistance,Math.min(i.maxDistance,J))}function tt(J){v.set(J.clientX,J.clientY)}function xt(J){Xe(J),b.set(J.clientX,J.clientY)}function ve(J){_.set(J.clientX,J.clientY)}function we(J){x.set(J.clientX,J.clientY),S.subVectors(x,v).multiplyScalar(i.rotateSpeed);const me=i.domElement;me&&(oe(2*Math.PI*S.x/me.clientHeight),ae(2*Math.PI*S.y/me.clientHeight)),v.copy(x),i.update()}function Ze(J){R.set(J.clientX,J.clientY),w.subVectors(R,b),w.y>0?se(K()):w.y<0&&De(K()),b.copy(R),i.update()}function de(J){T.set(J.clientX,J.clientY),E.subVectors(T,_).multiplyScalar(i.panSpeed),Q(E.x,E.y),_.copy(T),i.update()}function it(J){Xe(J),J.deltaY<0?De(K()):J.deltaY>0&&se(K()),i.update()}function wt(J){let me=!1;switch(J.code){case i.keys.UP:Q(0,i.keyPanSpeed),me=!0;break;case i.keys.BOTTOM:Q(0,-i.keyPanSpeed),me=!0;break;case i.keys.LEFT:Q(i.keyPanSpeed,0),me=!0;break;case i.keys.RIGHT:Q(-i.keyPanSpeed,0),me=!0;break}me&&(J.preventDefault(),i.update())}function ct(){if(C.length==1)v.set(C[0].pageX,C[0].pageY);else{const J=.5*(C[0].pageX+C[1].pageX),me=.5*(C[0].pageY+C[1].pageY);v.set(J,me)}}function Qe(){if(C.length==1)_.set(C[0].pageX,C[0].pageY);else{const J=.5*(C[0].pageX+C[1].pageX),me=.5*(C[0].pageY+C[1].pageY);_.set(J,me)}}function Ee(){const J=C[0].pageX-C[1].pageX,me=C[0].pageY-C[1].pageY,Le=Math.sqrt(J*J+me*me);b.set(0,Le)}function V(){i.enableZoom&&Ee(),i.enablePan&&Qe()}function Ae(){i.enableZoom&&Ee(),i.enableRotate&&ct()}function Oe(J){if(C.length==1)x.set(J.pageX,J.pageY);else{const Le=pt(J),j=.5*(J.pageX+Le.x),ke=.5*(J.pageY+Le.y);x.set(j,ke)}S.subVectors(x,v).multiplyScalar(i.rotateSpeed);const me=i.domElement;me&&(oe(2*Math.PI*S.x/me.clientHeight),ae(2*Math.PI*S.y/me.clientHeight)),v.copy(x)}function Ve(J){if(C.length==1)T.set(J.pageX,J.pageY);else{const me=pt(J),Le=.5*(J.pageX+me.x),j=.5*(J.pageY+me.y);T.set(Le,j)}E.subVectors(T,_).multiplyScalar(i.panSpeed),Q(E.x,E.y),_.copy(T)}function Fe(J){const me=pt(J),Le=J.pageX-me.x,j=J.pageY-me.y,ke=Math.sqrt(Le*Le+j*j);R.set(0,ke),w.set(0,Math.pow(R.y/b.y,i.zoomSpeed)),se(w.y),b.copy(R)}function $e(J){i.enableZoom&&Fe(J),i.enablePan&&Ve(J)}function Je(J){i.enableZoom&&Fe(J),i.enableRotate&&Oe(J)}function ht(J){var me,Le;i.enabled!==!1&&(C.length===0&&((me=i.domElement)==null||me.ownerDocument.addEventListener("pointermove",k),(Le=i.domElement)==null||Le.ownerDocument.addEventListener("pointerup",P)),vt(J),J.pointerType==="touch"?yt(J):he(J))}function k(J){i.enabled!==!1&&(J.pointerType==="touch"?je(J):be(J))}function P(J){var me,Le,j;Ue(J),C.length===0&&((me=i.domElement)==null||me.releasePointerCapture(J.pointerId),(Le=i.domElement)==null||Le.ownerDocument.removeEventListener("pointermove",k),(j=i.domElement)==null||j.ownerDocument.removeEventListener("pointerup",P)),i.dispatchEvent(s),l=o.NONE}function he(J){let me;switch(J.button){case 0:me=i.mouseButtons.LEFT;break;case 1:me=i.mouseButtons.MIDDLE;break;case 2:me=i.mouseButtons.RIGHT;break;default:me=-1}switch(me){case rh.DOLLY:if(i.enableZoom===!1)return;xt(J),l=o.DOLLY;break;case rh.ROTATE:if(J.ctrlKey||J.metaKey||J.shiftKey){if(i.enablePan===!1)return;ve(J),l=o.PAN}else{if(i.enableRotate===!1)return;tt(J),l=o.ROTATE}break;case rh.PAN:if(J.ctrlKey||J.metaKey||J.shiftKey){if(i.enableRotate===!1)return;tt(J),l=o.ROTATE}else{if(i.enablePan===!1)return;ve(J),l=o.PAN}break;default:l=o.NONE}l!==o.NONE&&i.dispatchEvent(a)}function be(J){if(i.enabled!==!1)switch(l){case o.ROTATE:if(i.enableRotate===!1)return;we(J);break;case o.DOLLY:if(i.enableZoom===!1)return;Ze(J);break;case o.PAN:if(i.enablePan===!1)return;de(J);break}}function Ie(J){i.enabled===!1||i.enableZoom===!1||l!==o.NONE&&l!==o.ROTATE||(J.preventDefault(),i.dispatchEvent(a),it(J),i.dispatchEvent(s))}function Se(J){i.enabled===!1||i.enablePan===!1||wt(J)}function yt(J){switch(He(J),C.length){case 1:switch(i.touches.ONE){case ah.ROTATE:if(i.enableRotate===!1)return;ct(),l=o.TOUCH_ROTATE;break;case ah.PAN:if(i.enablePan===!1)return;Qe(),l=o.TOUCH_PAN;break;default:l=o.NONE}break;case 2:switch(i.touches.TWO){case ah.DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;V(),l=o.TOUCH_DOLLY_PAN;break;case ah.DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;Ae(),l=o.TOUCH_DOLLY_ROTATE;break;default:l=o.NONE}break;default:l=o.NONE}l!==o.NONE&&i.dispatchEvent(a)}function je(J){switch(He(J),l){case o.TOUCH_ROTATE:if(i.enableRotate===!1)return;Oe(J),i.update();break;case o.TOUCH_PAN:if(i.enablePan===!1)return;Ve(J),i.update();break;case o.TOUCH_DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;$e(J),i.update();break;case o.TOUCH_DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;Je(J),i.update();break;default:l=o.NONE}}function Tt(J){i.enabled!==!1&&J.preventDefault()}function vt(J){C.push(J)}function Ue(J){delete z[J.pointerId];for(let me=0;me{De(J),i.update()},this.dollyOut=(J=K())=>{se(J),i.update()},this.getScale=()=>p,this.setScale=J=>{ce(J),i.update()},this.getZoomScale=()=>K(),t!==void 0&&this.connect(t),this.update()}};function Mie(n,e,t){const i=pn(m=>m.size),r=pn(m=>m.viewport),a=typeof n=="number"?n:i.width*r.dpr,s=i.height*r.dpr,o=(typeof n=="number"?t:n)||{},{samples:l=0,depth:u,...d}=o,f=u??o.depthBuffer,p=ie.useMemo(()=>{const m=new pi(a,s,{minFilter:Bt,magFilter:Bt,type:Jn,...d});return f&&(m.depthTexture=new iv(a,s,fi)),m.samples=l,m},[]);return ie.useLayoutEffect(()=>{p.setSize(a,s),l&&(p.samples=l)},[l,p,a,s]),ie.useEffect(()=>()=>p.dispose(),[]),p}const Aie=n=>typeof n=="function",Bz=ie.forwardRef(({envMap:n,resolution:e=256,frames:t=1/0,makeDefault:i,children:r,...a},s)=>{const o=pn(({set:S})=>S),l=pn(({camera:S})=>S),u=pn(({size:S})=>S),d=ie.useRef(null);ie.useImperativeHandle(s,()=>d.current,[]);const f=ie.useRef(null),p=Mie(e);ie.useLayoutEffect(()=>{a.manual||(d.current.aspect=u.width/u.height)},[u,a]),ie.useLayoutEffect(()=>{d.current.updateProjectionMatrix()});let m=0,v=null;const x=Aie(r);return _a(S=>{x&&(t===1/0||m{if(i){const S=l;return o(()=>({camera:d.current})),()=>o(()=>({camera:S}))}},[d,i,o]),ie.createElement(ie.Fragment,null,ie.createElement("perspectiveCamera",ky({ref:d},a),!x&&r),ie.createElement("group",{ref:f},x&&r(p.texture)))}),wie=ie.forwardRef(({makeDefault:n,camera:e,regress:t,domElement:i,enableDamping:r=!0,keyEvents:a=!1,onChange:s,onStart:o,onEnd:l,...u},d)=>{const f=pn(w=>w.invalidate),p=pn(w=>w.camera),m=pn(w=>w.gl),v=pn(w=>w.events),x=pn(w=>w.setEvents),S=pn(w=>w.set),_=pn(w=>w.get),T=pn(w=>w.performance),E=e||p,b=i||v.connected||m.domElement,R=ie.useMemo(()=>new bie(E),[E]);return _a(()=>{R.enabled&&R.update()},-1),ie.useEffect(()=>(a&&R.connect(a===!0?b:a),R.connect(b),()=>void R.dispose()),[a,b,t,R,f]),ie.useEffect(()=>{const w=N=>{f(),t&&T.regress(),s&&s(N)},L=N=>{o&&o(N)},U=N=>{l&&l(N)};return R.addEventListener("change",w),R.addEventListener("start",L),R.addEventListener("end",U),()=>{R.removeEventListener("start",L),R.removeEventListener("end",U),R.removeEventListener("change",w)}},[s,o,l,R,f,x]),ie.useEffect(()=>{if(n){const w=_().controls;return S({controls:R}),()=>S({controls:w})}},[n,R]),ie.createElement("primitive",ky({ref:d,object:R,enableDamping:r},u))});/** + * postprocessing v6.38.0 build Sat Nov 08 2025 + * https://github.com/pmndrs/postprocessing + * Copyright 2015-2025 Raoul van Rüschen + * @license Zlib + */var Qb=1/1e3,Rie=1e3,Cie=class{constructor(){this.startTime=performance.now(),this.previousTime=0,this.currentTime=0,this._delta=0,this._elapsed=0,this._fixedDelta=1e3/60,this.timescale=1,this.useFixedDelta=!1,this._autoReset=!1}get autoReset(){return this._autoReset}set autoReset(n){typeof document<"u"&&document.hidden!==void 0&&(n?document.addEventListener("visibilitychange",this):document.removeEventListener("visibilitychange",this),this._autoReset=n)}get delta(){return this._delta*Qb}get fixedDelta(){return this._fixedDelta*Qb}set fixedDelta(n){this._fixedDelta=n*Rie}get elapsed(){return this._elapsed*Qb}update(n){this.useFixedDelta?this._delta=this.fixedDelta:(this.previousTime=this.currentTime,this.currentTime=(n!==void 0?n:performance.now())-this.startTime,this._delta=this.currentTime-this.previousTime),this._delta*=this.timescale,this._elapsed+=this._delta}reset(){this._delta=0,this._elapsed=0,this.currentTime=performance.now()-this.startTime}getDelta(){return this.delta}getElapsed(){return this.elapsed}handleEvent(n){document.hidden||(this.currentTime=performance.now()-this.startTime)}dispose(){this.autoReset=!1}},Die=(()=>{const n=new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),e=new Float32Array([0,0,2,0,0,2]),t=new Ct;return t.setAttribute("position",new bt(n,3)),t.setAttribute("uv",new bt(e,2)),t})(),Qr=class hA{static get fullscreenGeometry(){return Die}constructor(e="Pass",t=new Rp,i=new Za){this.name=e,this.renderer=null,this.scene=t,this.camera=i,this.screen=null,this.rtt=!0,this.needsSwap=!0,this.needsDepthTexture=!1,this.enabled=!0}get renderToScreen(){return!this.rtt}set renderToScreen(e){if(this.rtt===e){const t=this.fullscreenMaterial;t!==null&&(t.needsUpdate=!0),this.rtt=!e}}set mainScene(e){}set mainCamera(e){}setRenderer(e){this.renderer=e}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}get fullscreenMaterial(){return this.screen!==null?this.screen.material:null}set fullscreenMaterial(e){let t=this.screen;t!==null?t.material=e:(t=new jn(hA.fullscreenGeometry,e),t.frustumCulled=!1,this.scene===null&&(this.scene=new Rp),this.scene.add(t),this.screen=t)}getFullscreenMaterial(){return this.fullscreenMaterial}setFullscreenMaterial(e){this.fullscreenMaterial=e}getDepthTexture(){return null}setDepthTexture(e,t=su){}render(e,t,i,r,a){throw new Error("Render method not implemented!")}setSize(e,t){}initialize(e,t,i){}dispose(){for(const e of Object.keys(this)){const t=this[e];(t instanceof pi||t instanceof ei||t instanceof In||t instanceof hA)&&this[e].dispose()}this.fullscreenMaterial!==null&&this.fullscreenMaterial.dispose()}},Nie=class extends Qr{constructor(){super("ClearMaskPass",null,null),this.needsSwap=!1}render(n,e,t,i,r){const a=n.state.buffers.stencil;a.setLocked(!1),a.setTest(!1)}},Oie=`#ifdef COLOR_WRITE +#include +#include +#ifdef FRAMEBUFFER_PRECISION_HIGH +uniform mediump sampler2D inputBuffer; +#else +uniform lowp sampler2D inputBuffer; +#endif +#endif +#ifdef DEPTH_WRITE +#include +#ifdef GL_FRAGMENT_PRECISION_HIGH +uniform highp sampler2D depthBuffer; +#else +uniform mediump sampler2D depthBuffer; +#endif +float readDepth(const in vec2 uv){ +#if DEPTH_PACKING == 3201 +return unpackRGBAToDepth(texture2D(depthBuffer,uv)); +#else +return texture2D(depthBuffer,uv).r; +#endif +} +#endif +#ifdef USE_WEIGHTS +uniform vec4 channelWeights; +#endif +uniform float opacity;varying vec2 vUv;void main(){ +#ifdef COLOR_WRITE +vec4 texel=texture2D(inputBuffer,vUv); +#ifdef USE_WEIGHTS +texel*=channelWeights; +#endif +gl_FragColor=opacity*texel; +#ifdef COLOR_SPACE_CONVERSION +#include +#endif +#include +#else +gl_FragColor=vec4(0.0); +#endif +#ifdef DEPTH_WRITE +gl_FragDepth=readDepth(vUv); +#endif +}`,BR="varying vec2 vUv;void main(){vUv=position.xy*0.5+0.5;gl_Position=vec4(position.xy,1.0,1.0);}",Lie=class extends Oi{constructor(){super({name:"CopyMaterial",defines:{DEPTH_PACKING:"0",COLOR_WRITE:"1"},uniforms:{inputBuffer:new $(null),depthBuffer:new $(null),channelWeights:new $(null),opacity:new $(1)},blending:Lr,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:Oie,vertexShader:BR}),this.depthFunc=Eg}get inputBuffer(){return this.uniforms.inputBuffer.value}set inputBuffer(n){const e=n!==null;this.colorWrite!==e&&(e?this.defines.COLOR_WRITE=!0:delete this.defines.COLOR_WRITE,this.colorWrite=e,this.needsUpdate=!0),this.uniforms.inputBuffer.value=n}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(n){const e=n!==null;this.depthWrite!==e&&(e?this.defines.DEPTH_WRITE=!0:delete this.defines.DEPTH_WRITE,this.depthTest=e,this.depthWrite=e,this.needsUpdate=!0),this.uniforms.depthBuffer.value=n}set depthPacking(n){this.defines.DEPTH_PACKING=n.toFixed(0),this.needsUpdate=!0}get channelWeights(){return this.uniforms.channelWeights.value}set channelWeights(n){n!==null?(this.defines.USE_WEIGHTS="1",this.uniforms.channelWeights.value=n):delete this.defines.USE_WEIGHTS,this.needsUpdate=!0}setInputBuffer(n){this.uniforms.inputBuffer.value=n}getOpacity(n){return this.uniforms.opacity.value}setOpacity(n){this.uniforms.opacity.value=n}},Fz=class extends Qr{constructor(n,e=!0){super("CopyPass"),this.fullscreenMaterial=new Lie,this.needsSwap=!1,this.renderTarget=n,n===void 0&&(this.renderTarget=new pi(1,1,{minFilter:Bt,magFilter:Bt,stencilBuffer:!1,depthBuffer:!1}),this.renderTarget.texture.name="CopyPass.Target"),this.autoResize=e}get resize(){return this.autoResize}set resize(n){this.autoResize=n}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}setAutoResizeEnabled(n){this.autoResize=n}render(n,e,t,i,r){this.fullscreenMaterial.inputBuffer=e.texture,n.setRenderTarget(this.renderToScreen?null:this.renderTarget),n.render(this.scene,this.camera)}setSize(n,e){this.autoResize&&this.renderTarget.setSize(n,e)}initialize(n,e,t){t!==void 0&&(this.renderTarget.texture.type=t,t!==Ni?this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1":n!==null&&n.outputColorSpace===mn&&(this.renderTarget.texture.colorSpace=mn))}},II=new Ye,Hz=class extends Qr{constructor(n=!0,e=!0,t=!1){super("ClearPass",null,null),this.needsSwap=!1,this.color=n,this.depth=e,this.stencil=t,this.overrideClearColor=null,this.overrideClearAlpha=-1}setClearFlags(n,e,t){this.color=n,this.depth=e,this.stencil=t}getOverrideClearColor(){return this.overrideClearColor}setOverrideClearColor(n){this.overrideClearColor=n}getOverrideClearAlpha(){return this.overrideClearAlpha}setOverrideClearAlpha(n){this.overrideClearAlpha=n}render(n,e,t,i,r){const a=this.overrideClearColor,s=this.overrideClearAlpha,o=n.getClearAlpha(),l=a!==null,u=s>=0;l?(n.getClearColor(II),n.setClearColor(a,u?s:o)):u&&n.setClearAlpha(s),n.setRenderTarget(this.renderToScreen?null:e),n.clear(this.color,this.depth,this.stencil),l?n.setClearColor(II,o):u&&n.setClearAlpha(o)}},Iie=class extends Qr{constructor(n,e){super("MaskPass",n,e),this.needsSwap=!1,this.clearPass=new Hz(!1,!1,!0),this.inverse=!1}set mainScene(n){this.scene=n}set mainCamera(n){this.camera=n}get inverted(){return this.inverse}set inverted(n){this.inverse=n}get clear(){return this.clearPass.enabled}set clear(n){this.clearPass.enabled=n}getClearPass(){return this.clearPass}isInverted(){return this.inverted}setInverted(n){this.inverted=n}render(n,e,t,i,r){const a=n.getContext(),s=n.state.buffers,o=this.scene,l=this.camera,u=this.clearPass,d=this.inverted?0:1,f=1-d;s.color.setMask(!1),s.depth.setMask(!1),s.color.setLocked(!0),s.depth.setLocked(!0),s.stencil.setTest(!0),s.stencil.setOp(a.REPLACE,a.REPLACE,a.REPLACE),s.stencil.setFunc(a.ALWAYS,d,4294967295),s.stencil.setClear(f),s.stencil.setLocked(!0),this.clearPass.enabled&&(this.renderToScreen?u.render(n,null):(u.render(n,e),u.render(n,t))),this.renderToScreen?(n.setRenderTarget(null),n.render(o,l)):(n.setRenderTarget(e),n.render(o,l),n.setRenderTarget(t),n.render(o,l)),s.color.setLocked(!1),s.depth.setLocked(!1),s.stencil.setLocked(!1),s.stencil.setFunc(a.EQUAL,1,4294967295),s.stencil.setOp(a.KEEP,a.KEEP,a.KEEP),s.stencil.setLocked(!0)}},Uie=class{constructor(n=null,{depthBuffer:e=!0,stencilBuffer:t=!1,multisampling:i=0,frameBufferType:r}={}){this.renderer=null,this.inputBuffer=this.createBuffer(e,t,r,i),this.outputBuffer=this.inputBuffer.clone(),this.copyPass=new Fz,this.depthTexture=null,this.passes=[],this.timer=new Cie,this.autoRenderToScreen=!0,this.setRenderer(n)}get multisampling(){return this.inputBuffer.samples||0}set multisampling(n){const e=this.inputBuffer,t=this.multisampling;t>0&&n>0?(this.inputBuffer.samples=n,this.outputBuffer.samples=n,this.inputBuffer.dispose(),this.outputBuffer.dispose()):t!==n&&(this.inputBuffer.dispose(),this.outputBuffer.dispose(),this.inputBuffer=this.createBuffer(e.depthBuffer,e.stencilBuffer,e.texture.type,n),this.inputBuffer.depthTexture=this.depthTexture,this.outputBuffer=this.inputBuffer.clone())}getTimer(){return this.timer}getRenderer(){return this.renderer}setRenderer(n){if(this.renderer=n,n!==null){const e=n.getSize(new re),t=n.getContext().getContextAttributes().alpha,i=this.inputBuffer.texture.type;i===Ni&&n.outputColorSpace===mn&&(this.inputBuffer.texture.colorSpace=mn,this.outputBuffer.texture.colorSpace=mn,this.inputBuffer.dispose(),this.outputBuffer.dispose()),n.autoClear=!1,this.setSize(e.width,e.height);for(const r of this.passes)r.initialize(n,t,i)}}replaceRenderer(n,e=!0){const t=this.renderer,i=t.domElement.parentNode;return this.setRenderer(n),e&&i!==null&&(i.removeChild(t.domElement),i.appendChild(n.domElement)),t}createDepthTexture(){const n=this.depthTexture=new iv;return this.inputBuffer.depthTexture=n,this.inputBuffer.dispose(),this.inputBuffer.stencilBuffer?(n.format=zh,n.type=Ph):n.type=to,n}deleteDepthTexture(){if(this.depthTexture!==null){this.depthTexture.dispose(),this.depthTexture=null,this.inputBuffer.depthTexture=null,this.inputBuffer.dispose();for(const n of this.passes)n.setDepthTexture(null)}}createBuffer(n,e,t,i){const r=this.renderer,a=r===null?new re:r.getDrawingBufferSize(new re),s={minFilter:Bt,magFilter:Bt,stencilBuffer:e,depthBuffer:n,type:t},o=new pi(a.width,a.height,s);return i>0&&(o.samples=i),t===Ni&&r!==null&&r.outputColorSpace===mn&&(o.texture.colorSpace=mn),o.texture.name="EffectComposer.Buffer",o.texture.generateMipmaps=!1,o}setMainScene(n){for(const e of this.passes)e.mainScene=n}setMainCamera(n){for(const e of this.passes)e.mainCamera=n}addPass(n,e){const t=this.passes,i=this.renderer,r=i.getDrawingBufferSize(new re),a=i.getContext().getContextAttributes().alpha,s=this.inputBuffer.texture.type;if(n.setRenderer(i),n.setSize(r.width,r.height),n.initialize(i,a,s),this.autoRenderToScreen&&(t.length>0&&(t[t.length-1].renderToScreen=!1),n.renderToScreen&&(this.autoRenderToScreen=!1)),e!==void 0?t.splice(e,0,n):t.push(n),this.autoRenderToScreen&&(t[t.length-1].renderToScreen=!0),n.needsDepthTexture||this.depthTexture!==null)if(this.depthTexture===null){const o=this.createDepthTexture();for(n of t)n.setDepthTexture(o)}else n.setDepthTexture(this.depthTexture)}removePass(n){const e=this.passes,t=e.indexOf(n);if(t!==-1&&e.splice(t,1).length>0){if(this.depthTexture!==null){const a=(o,l)=>o||l.needsDepthTexture;e.reduce(a,!1)||(n.getDepthTexture()===this.depthTexture&&n.setDepthTexture(null),this.deleteDepthTexture())}this.autoRenderToScreen&&t===e.length&&(n.renderToScreen=!1,e.length>0&&(e[e.length-1].renderToScreen=!0))}}removeAllPasses(){const n=this.passes;this.deleteDepthTexture(),n.length>0&&(this.autoRenderToScreen&&(n[n.length-1].renderToScreen=!1),this.passes=[])}render(n){const e=this.renderer,t=this.copyPass;let i=this.inputBuffer,r=this.outputBuffer,a=!1,s,o,l;n===void 0&&(this.timer.update(),n=this.timer.getDelta());for(const u of this.passes)u.enabled&&(u.render(e,i,r,n,a),u.needsSwap&&(a&&(t.renderToScreen=u.renderToScreen,s=e.getContext(),o=e.state.buffers.stencil,o.setFunc(s.NOTEQUAL,1,4294967295),t.render(e,i,r,n,a),o.setFunc(s.EQUAL,1,4294967295)),l=i,i=r,r=l),u instanceof Iie?a=!0:u instanceof Nie&&(a=!1))}setSize(n,e,t){const i=this.renderer,r=i.getSize(new re);(n===void 0||e===void 0)&&(n=r.width,e=r.height),(r.width!==n||r.height!==e)&&i.setSize(n,e,t);const a=i.getDrawingBufferSize(new re);this.inputBuffer.setSize(a.width,a.height),this.outputBuffer.setSize(a.width,a.height);for(const s of this.passes)s.setSize(a.width,a.height)}reset(){this.dispose(),this.autoRenderToScreen=!0}dispose(){for(const n of this.passes)n.dispose();this.passes=[],this.inputBuffer!==null&&this.inputBuffer.dispose(),this.outputBuffer!==null&&this.outputBuffer.dispose(),this.deleteDepthTexture(),this.copyPass.dispose(),this.timer.dispose(),Qr.fullscreenGeometry.dispose()}},Dl={NONE:0,DEPTH:1,CONVOLUTION:2},Sn={FRAGMENT_HEAD:"FRAGMENT_HEAD",FRAGMENT_MAIN_UV:"FRAGMENT_MAIN_UV",FRAGMENT_MAIN_IMAGE:"FRAGMENT_MAIN_IMAGE",VERTEX_HEAD:"VERTEX_HEAD",VERTEX_MAIN_SUPPORT:"VERTEX_MAIN_SUPPORT"},Pie=class{constructor(){this.shaderParts=new Map([[Sn.FRAGMENT_HEAD,null],[Sn.FRAGMENT_MAIN_UV,null],[Sn.FRAGMENT_MAIN_IMAGE,null],[Sn.VERTEX_HEAD,null],[Sn.VERTEX_MAIN_SUPPORT,null]]),this.defines=new Map,this.uniforms=new Map,this.blendModes=new Map,this.extensions=new Set,this.attributes=Dl.NONE,this.varyings=new Set,this.uvTransformation=!1,this.readDepth=!1,this.colorSpace=Xn}},Kb=!1,UI=class{constructor(n=null){this.originalMaterials=new Map,this.material=null,this.materials=null,this.materialsBackSide=null,this.materialsDoubleSide=null,this.materialsFlatShaded=null,this.materialsFlatShadedBackSide=null,this.materialsFlatShadedDoubleSide=null,this.setMaterial(n),this.meshCount=0,this.replaceMaterial=e=>{if(e.isMesh){let t;if(e.material.flatShading)switch(e.material.side){case xr:t=this.materialsFlatShadedDoubleSide;break;case ki:t=this.materialsFlatShadedBackSide;break;default:t=this.materialsFlatShaded;break}else switch(e.material.side){case xr:t=this.materialsDoubleSide;break;case ki:t=this.materialsBackSide;break;default:t=this.materials;break}this.originalMaterials.set(e,e.material),e.isSkinnedMesh?e.material=t[2]:e.isInstancedMesh?e.material=t[1]:e.material=t[0],++this.meshCount}}}cloneMaterial(n){if(!(n instanceof Oi))return n.clone();const e=n.uniforms,t=new Map;for(const r in e){const a=e[r].value;a.isRenderTargetTexture&&(e[r].value=null,t.set(r,a))}const i=n.clone();for(const r of t)e[r[0]].value=r[1],i.uniforms[r[0]].value=r[1];return i}setMaterial(n){if(this.disposeMaterials(),this.material=n,n!==null){const e=this.materials=[this.cloneMaterial(n),this.cloneMaterial(n),this.cloneMaterial(n)];for(const t of e)t.uniforms=Object.assign({},n.uniforms),t.side=eo;e[2].skinning=!0,this.materialsBackSide=e.map(t=>{const i=this.cloneMaterial(t);return i.uniforms=Object.assign({},n.uniforms),i.side=ki,i}),this.materialsDoubleSide=e.map(t=>{const i=this.cloneMaterial(t);return i.uniforms=Object.assign({},n.uniforms),i.side=xr,i}),this.materialsFlatShaded=e.map(t=>{const i=this.cloneMaterial(t);return i.uniforms=Object.assign({},n.uniforms),i.flatShading=!0,i}),this.materialsFlatShadedBackSide=e.map(t=>{const i=this.cloneMaterial(t);return i.uniforms=Object.assign({},n.uniforms),i.flatShading=!0,i.side=ki,i}),this.materialsFlatShadedDoubleSide=e.map(t=>{const i=this.cloneMaterial(t);return i.uniforms=Object.assign({},n.uniforms),i.flatShading=!0,i.side=xr,i})}}render(n,e,t){const i=n.shadowMap.enabled;if(n.shadowMap.enabled=!1,Kb){const r=this.originalMaterials;this.meshCount=0,e.traverse(this.replaceMaterial),n.render(e,t);for(const a of r)a[0].material=a[1];this.meshCount!==r.size&&r.clear()}else{const r=e.overrideMaterial;e.overrideMaterial=this.material,n.render(e,t),e.overrideMaterial=r}n.shadowMap.enabled=i}disposeMaterials(){if(this.material!==null){const n=this.materials.concat(this.materialsBackSide).concat(this.materialsDoubleSide).concat(this.materialsFlatShaded).concat(this.materialsFlatShadedBackSide).concat(this.materialsFlatShadedDoubleSide);for(const e of n)e.dispose()}}dispose(){this.originalMaterials.clear(),this.disposeMaterials()}static get workaroundEnabled(){return Kb}static set workaroundEnabled(n){Kb=n}},fc=-1,Rs=class extends Mi{constructor(n,e=fc,t=fc,i=1){super(),this.resizable=n,this.baseSize=new re(1,1),this.preferredSize=new re(e,t),this.target=this.preferredSize,this.s=i,this.effectiveSize=new re,this.addEventListener("change",()=>this.updateEffectiveSize()),this.updateEffectiveSize()}updateEffectiveSize(){const n=this.baseSize,e=this.preferredSize,t=this.effectiveSize,i=this.scale;e.width!==fc?t.width=e.width:e.height!==fc?t.width=Math.round(e.height*(n.width/Math.max(n.height,1))):t.width=Math.round(n.width*i),e.height!==fc?t.height=e.height:e.width!==fc?t.height=Math.round(e.width/Math.max(n.width/Math.max(n.height,1),1)):t.height=Math.round(n.height*i)}get width(){return this.effectiveSize.width}set width(n){this.preferredWidth=n}get height(){return this.effectiveSize.height}set height(n){this.preferredHeight=n}getWidth(){return this.width}getHeight(){return this.height}get scale(){return this.s}set scale(n){this.s!==n&&(this.s=n,this.preferredSize.setScalar(fc),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getScale(){return this.scale}setScale(n){this.scale=n}get baseWidth(){return this.baseSize.width}set baseWidth(n){this.baseSize.width!==n&&(this.baseSize.width=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseWidth(){return this.baseWidth}setBaseWidth(n){this.baseWidth=n}get baseHeight(){return this.baseSize.height}set baseHeight(n){this.baseSize.height!==n&&(this.baseSize.height=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseHeight(){return this.baseHeight}setBaseHeight(n){this.baseHeight=n}setBaseSize(n,e){(this.baseSize.width!==n||this.baseSize.height!==e)&&(this.baseSize.set(n,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}get preferredWidth(){return this.preferredSize.width}set preferredWidth(n){this.preferredSize.width!==n&&(this.preferredSize.width=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredWidth(){return this.preferredWidth}setPreferredWidth(n){this.preferredWidth=n}get preferredHeight(){return this.preferredSize.height}set preferredHeight(n){this.preferredSize.height!==n&&(this.preferredSize.height=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredHeight(){return this.preferredHeight}setPreferredHeight(n){this.preferredHeight=n}setPreferredSize(n,e){(this.preferredSize.width!==n||this.preferredSize.height!==e)&&(this.preferredSize.set(n,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}copy(n){this.s=n.scale,this.baseSize.set(n.baseWidth,n.baseHeight),this.preferredSize.set(n.preferredWidth,n.preferredHeight),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height)}static get AUTO_SIZE(){return fc}},cn={ADD:0,AVERAGE:2,COLOR:3,COLOR_BURN:4,COLOR_DODGE:5,DARKEN:6,DIFFERENCE:7,DIVIDE:8,DST:9,EXCLUSION:10,HARD_LIGHT:11,HARD_MIX:12,HUE:13,INVERT:14,INVERT_RGB:15,LIGHTEN:16,LINEAR_BURN:17,LINEAR_DODGE:18,LINEAR_LIGHT:19,LUMINOSITY:20,MULTIPLY:21,NEGATION:22,NORMAL:23,OVERLAY:24,PIN_LIGHT:25,REFLECT:26,SATURATION:27,SCREEN:28,SOFT_LIGHT:29,SRC:30,SUBTRACT:31,VIVID_LIGHT:32},zie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(x.rgb+y.rgb,y.a),y.a*opacity);}",Bie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4((x.rgb+y.rgb)*0.5,y.a),y.a*opacity);}",Fie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.xy,xHSL.z));return mix(x,vec4(z,y.a),y.a*opacity);}",Hie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 a=x.rgb,b=y.rgb;vec3 z=mix(step(0.0,b)*(1.0-min(vec3(1.0),(1.0-a)/b)),vec3(1.0),step(1.0,a));return mix(x,vec4(z,y.a),y.a*opacity);}",Vie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 a=x.rgb,b=y.rgb;vec3 z=step(0.0,a)*mix(min(vec3(1.0),a/max(1.0-b,1e-9)),vec3(1.0),step(1.0,b));return mix(x,vec4(z,y.a),y.a*opacity);}",Gie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(min(x.rgb,y.rgb),y.a),y.a*opacity);}",kie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(abs(x.rgb-y.rgb),y.a),y.a*opacity);}",Wie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(x.rgb/max(y.rgb,1e-12),y.a),y.a*opacity);}",Xie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4((x.rgb+y.rgb-2.0*x.rgb*y.rgb),y.a),y.a*opacity);}",qie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 a=min(x.rgb,1.0);vec3 b=min(y.rgb,1.0);vec3 z=mix(2.0*a*b,1.0-2.0*(1.0-a)*(1.0-b),step(0.5,b));return mix(x,vec4(z,y.a),y.a*opacity);}",Yie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(step(1.0,x.rgb+y.rgb),y.a),y.a*opacity);}",jie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.x,xHSL.yz));return mix(x,vec4(z,y.a),y.a*opacity);}",Zie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(1.0-y.rgb,y.a),y.a*opacity);}",Qie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(y.rgb*(1.0-x.rgb),y.a),y.a*opacity);}",Kie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(max(x.rgb,y.rgb),y.a),y.a*opacity);}",Jie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(clamp(y.rgb+x.rgb-1.0,0.0,1.0),y.a),y.a*opacity);}",$ie="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(min(x.rgb+y.rgb,1.0),y.a),y.a*opacity);}",ere="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(clamp(2.0*y.rgb+x.rgb-1.0,0.0,1.0),y.a),y.a*opacity);}",tre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.xy,yHSL.z));return mix(x,vec4(z,y.a),y.a*opacity);}",nre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(x.rgb*y.rgb,y.a),y.a*opacity);}",ire="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(1.0-abs(1.0-x.rgb-y.rgb),y.a),y.a*opacity);}",rre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y,y.a*opacity);}",are="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 z=mix(2.0*y.rgb*x.rgb,1.0-2.0*(1.0-y.rgb)*(1.0-x.rgb),step(0.5,x.rgb));return mix(x,vec4(z,y.a),y.a*opacity);}",sre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 y2=2.0*y.rgb;vec3 z=mix(mix(y2,x.rgb,step(0.5*x.rgb,y.rgb)),max(y2-1.0,vec3(0.0)),step(x.rgb,y2-1.0));return mix(x,vec4(z,y.a),y.a*opacity);}",ore="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 z=mix(min(x.rgb*x.rgb/max(1.0-y.rgb,1e-12),1.0),y.rgb,step(1.0,y.rgb));return mix(x,vec4(z,y.a),y.a*opacity);}",lre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.x,yHSL.y,xHSL.z));return mix(x,vec4(z,y.a),y.a*opacity);}",cre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(x.rgb+y.rgb-min(x.rgb*y.rgb,1.0),y.a),y.a*opacity);}",ure="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 a=x.rgb;vec3 b=y.rgb;vec3 y2=2.0*b;vec3 w=step(0.5,b);vec3 c=a-(1.0-y2)*a*(1.0-a);vec3 d=mix(a+(y2-1.0)*(sqrt(a)-a),a+(y2-1.0)*a*((16.0*a-12.0)*a+3.0),w*(1.0-step(0.25,a)));vec3 z=mix(c,d,w);return mix(x,vec4(z,y.a),y.a*opacity);}",hre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return y;}",dre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(max(x.rgb+y.rgb-1.0,0.0),y.a),y.a*opacity);}",fre="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 z=mix(max(1.0-min((1.0-x.rgb)/(2.0*y.rgb),1.0),0.0),min(x.rgb/(2.0*(1.0-y.rgb)),1.0),step(0.5,y.rgb));return mix(x,vec4(z,y.a),y.a*opacity);}",pre=new Map([[cn.ADD,zie],[cn.AVERAGE,Bie],[cn.COLOR,Fie],[cn.COLOR_BURN,Hie],[cn.COLOR_DODGE,Vie],[cn.DARKEN,Gie],[cn.DIFFERENCE,kie],[cn.DIVIDE,Wie],[cn.DST,null],[cn.EXCLUSION,Xie],[cn.HARD_LIGHT,qie],[cn.HARD_MIX,Yie],[cn.HUE,jie],[cn.INVERT,Zie],[cn.INVERT_RGB,Qie],[cn.LIGHTEN,Kie],[cn.LINEAR_BURN,Jie],[cn.LINEAR_DODGE,$ie],[cn.LINEAR_LIGHT,ere],[cn.LUMINOSITY,tre],[cn.MULTIPLY,nre],[cn.NEGATION,ire],[cn.NORMAL,rre],[cn.OVERLAY,are],[cn.PIN_LIGHT,sre],[cn.REFLECT,ore],[cn.SATURATION,lre],[cn.SCREEN,cre],[cn.SOFT_LIGHT,ure],[cn.SRC,hre],[cn.SUBTRACT,dre],[cn.VIVID_LIGHT,fre]]),mre=class extends Mi{constructor(n,e=1){super(),this._blendFunction=n,this.opacity=new $(e)}getOpacity(){return this.opacity.value}setOpacity(n){this.opacity.value=n}get blendFunction(){return this._blendFunction}set blendFunction(n){this._blendFunction=n,this.dispatchEvent({type:"change"})}getBlendFunction(){return this.blendFunction}setBlendFunction(n){this.blendFunction=n}getShaderCode(){return pre.get(this.blendFunction)}},Ug=class extends Mi{constructor(n,e,{attributes:t=Dl.NONE,blendFunction:i=cn.NORMAL,defines:r=new Map,uniforms:a=new Map,extensions:s=null,vertexShader:o=null}={}){super(),this.name=n,this.renderer=null,this.attributes=t,this.fragmentShader=e,this.vertexShader=o,this.defines=r,this.uniforms=a,this.extensions=s,this.blendMode=new mre(i),this.blendMode.addEventListener("change",l=>this.setChanged()),this._inputColorSpace=Xn,this._outputColorSpace=Xr}get inputColorSpace(){return this._inputColorSpace}set inputColorSpace(n){this._inputColorSpace=n,this.setChanged()}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(n){this._outputColorSpace=n,this.setChanged()}set mainScene(n){}set mainCamera(n){}getName(){return this.name}setRenderer(n){this.renderer=n}getDefines(){return this.defines}getUniforms(){return this.uniforms}getExtensions(){return this.extensions}getBlendMode(){return this.blendMode}getAttributes(){return this.attributes}setAttributes(n){this.attributes=n,this.setChanged()}getFragmentShader(){return this.fragmentShader}setFragmentShader(n){this.fragmentShader=n,this.setChanged()}getVertexShader(){return this.vertexShader}setVertexShader(n){this.vertexShader=n,this.setChanged()}setChanged(){this.dispatchEvent({type:"change"})}setDepthTexture(n,e=su){}update(n,e,t){}setSize(n,e){}initialize(n,e,t){}dispose(){for(const n of Object.keys(this)){const e=this[n];(e instanceof pi||e instanceof ei||e instanceof In||e instanceof Qr)&&this[n].dispose()}}},gre=`#include +#ifdef FRAMEBUFFER_PRECISION_HIGH +uniform mediump sampler2D inputBuffer; +#else +uniform lowp sampler2D inputBuffer; +#endif +#ifdef RANGE +uniform vec2 range; +#elif defined(THRESHOLD) +uniform float threshold;uniform float smoothing; +#endif +varying vec2 vUv;void main(){vec4 texel=texture2D(inputBuffer,vUv);float l=luminance(texel.rgb);float mask=1.0; +#ifdef RANGE +float low=step(range.x,l);float high=step(l,range.y);mask=low*high; +#elif defined(THRESHOLD) +mask=smoothstep(threshold,threshold+smoothing,l); +#endif +#ifdef COLOR +gl_FragColor=texel*mask; +#else +gl_FragColor=vec4(l*mask); +#endif +}`,vre=class extends Oi{constructor(n=!1,e=null){super({name:"LuminanceMaterial",defines:{THREE_REVISION:$s.replace(/\D+/g,"")},uniforms:{inputBuffer:new $(null),threshold:new $(0),smoothing:new $(1),range:new $(null)},blending:Lr,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:gre,vertexShader:BR}),this.colorOutput=n,this.luminanceRange=e}set inputBuffer(n){this.uniforms.inputBuffer.value=n}setInputBuffer(n){this.uniforms.inputBuffer.value=n}get threshold(){return this.uniforms.threshold.value}set threshold(n){this.smoothing>0||n>0?this.defines.THRESHOLD="1":delete this.defines.THRESHOLD,this.uniforms.threshold.value=n}getThreshold(){return this.threshold}setThreshold(n){this.threshold=n}get smoothing(){return this.uniforms.smoothing.value}set smoothing(n){this.threshold>0||n>0?this.defines.THRESHOLD="1":delete this.defines.THRESHOLD,this.uniforms.smoothing.value=n}getSmoothingFactor(){return this.smoothing}setSmoothingFactor(n){this.smoothing=n}get useThreshold(){return this.threshold>0||this.smoothing>0}set useThreshold(n){}get colorOutput(){return this.defines.COLOR!==void 0}set colorOutput(n){n?this.defines.COLOR="1":delete this.defines.COLOR,this.needsUpdate=!0}isColorOutputEnabled(n){return this.colorOutput}setColorOutputEnabled(n){this.colorOutput=n}get useRange(){return this.luminanceRange!==null}set useRange(n){this.luminanceRange=null}get luminanceRange(){return this.uniforms.range.value}set luminanceRange(n){n!==null?this.defines.RANGE="1":delete this.defines.RANGE,this.uniforms.range.value=n,this.needsUpdate=!0}getLuminanceRange(){return this.luminanceRange}setLuminanceRange(n){this.luminanceRange=n}},_re=class extends Qr{constructor({renderTarget:n,luminanceRange:e,colorOutput:t,resolutionScale:i=1,width:r=Rs.AUTO_SIZE,height:a=Rs.AUTO_SIZE,resolutionX:s=r,resolutionY:o=a}={}){super("LuminancePass"),this.fullscreenMaterial=new vre(t,e),this.needsSwap=!1,this.renderTarget=n,this.renderTarget===void 0&&(this.renderTarget=new pi(1,1,{depthBuffer:!1}),this.renderTarget.texture.name="LuminancePass.Target");const l=this.resolution=new Rs(this,s,o,i);l.addEventListener("change",u=>this.setSize(l.baseWidth,l.baseHeight))}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}render(n,e,t,i,r){const a=this.fullscreenMaterial;a.inputBuffer=e.texture,n.setRenderTarget(this.renderToScreen?null:this.renderTarget),n.render(this.scene,this.camera)}setSize(n,e){const t=this.resolution;t.setBaseSize(n,e),this.renderTarget.setSize(t.width,t.height)}initialize(n,e,t){t!==void 0&&t!==Ni&&(this.renderTarget.texture.type=t,this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1")}},dA=class extends Qr{constructor(n,e="inputBuffer"){super("ShaderPass"),this.fullscreenMaterial=n,this.input=e}setInput(n){this.input=n}render(n,e,t,i,r){const a=this.fullscreenMaterial.uniforms;e!==null&&a!==void 0&&a[this.input]!==void 0&&(a[this.input].value=e.texture),n.setRenderTarget(this.renderToScreen?null:t),n.render(this.scene,this.camera)}initialize(n,e,t){t!==void 0&&t!==Ni&&(this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1")}},FR=class extends Qr{constructor(n,e,t=null){super("RenderPass",n,e),this.needsSwap=!1,this.clearPass=new Hz,this.overrideMaterialManager=t===null?null:new UI(t),this.ignoreBackground=!1,this.skipShadowMapUpdate=!1,this.selection=null}set mainScene(n){this.scene=n}set mainCamera(n){this.camera=n}get renderToScreen(){return super.renderToScreen}set renderToScreen(n){super.renderToScreen=n,this.clearPass.renderToScreen=n}get overrideMaterial(){const n=this.overrideMaterialManager;return n!==null?n.material:null}set overrideMaterial(n){const e=this.overrideMaterialManager;n!==null?e!==null?e.setMaterial(n):this.overrideMaterialManager=new UI(n):e!==null&&(e.dispose(),this.overrideMaterialManager=null)}getOverrideMaterial(){return this.overrideMaterial}setOverrideMaterial(n){this.overrideMaterial=n}get clear(){return this.clearPass.enabled}set clear(n){this.clearPass.enabled=n}getSelection(){return this.selection}setSelection(n){this.selection=n}isBackgroundDisabled(){return this.ignoreBackground}setBackgroundDisabled(n){this.ignoreBackground=n}isShadowMapDisabled(){return this.skipShadowMapUpdate}setShadowMapDisabled(n){this.skipShadowMapUpdate=n}getClearPass(){return this.clearPass}render(n,e,t,i,r){const a=this.scene,s=this.camera,o=this.selection,l=s.layers.mask,u=a.background,d=n.shadowMap.autoUpdate,f=this.renderToScreen?null:e;o!==null&&s.layers.set(o.getLayer()),this.skipShadowMapUpdate&&(n.shadowMap.autoUpdate=!1),(this.ignoreBackground||this.clearPass.overrideClearColor!==null)&&(a.background=null),this.clearPass.enabled&&this.clearPass.render(n,e),n.setRenderTarget(f),this.overrideMaterialManager!==null?this.overrideMaterialManager.render(n,a,s):n.render(a,s),s.layers.mask=l,a.background=u,n.shadowMap.autoUpdate=d}},ca={LINEAR:0,REINHARD:1,REINHARD2:2,REINHARD2_ADAPTIVE:3,OPTIMIZED_CINEON:5,CINEON:5,ACES_FILMIC:6,AGX:7,NEUTRAL:8},xre=`#include +#ifdef GL_FRAGMENT_PRECISION_HIGH +uniform highp sampler2D depthBuffer; +#else +uniform mediump sampler2D depthBuffer; +#endif +#ifdef DOWNSAMPLE_NORMALS +uniform lowp sampler2D normalBuffer; +#endif +varying vec2 vUv0;varying vec2 vUv1;varying vec2 vUv2;varying vec2 vUv3;float readDepth(const in vec2 uv){ +#if DEPTH_PACKING == 3201 +return unpackRGBAToDepth(texture2D(depthBuffer,uv)); +#else +return texture2D(depthBuffer,uv).r; +#endif +}int findBestDepth(const in float samples[4]){float c=(samples[0]+samples[1]+samples[2]+samples[3])*0.25;float distances[4];distances[0]=abs(c-samples[0]);distances[1]=abs(c-samples[1]);distances[2]=abs(c-samples[2]);distances[3]=abs(c-samples[3]);float maxDistance=max(max(distances[0],distances[1]),max(distances[2],distances[3]));int remaining[3];int rejected[3];int i,j,k;for(i=0,j=0,k=0;i<4;++i){if(distances[i]this.setSize(o.baseWidth,o.baseHeight))}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}setDepthTexture(n,e=su){this.fullscreenMaterial.depthBuffer=n,this.fullscreenMaterial.depthPacking=e}render(n,e,t,i,r){n.setRenderTarget(this.renderToScreen?null:this.renderTarget),n.render(this.scene,this.camera)}setSize(n,e){const t=this.resolution;t.setBaseSize(n,e),this.renderTarget.setSize(t.width,t.height),this.fullscreenMaterial.setSize(n,e)}initialize(n,e,t){const i=n.getContext();if(!(i.getExtension("EXT_color_buffer_float")||i.getExtension("EXT_color_buffer_half_float")))throw new Error("Rendering to float texture is not supported.")}},Ere=`#include +#define packFloatToRGBA(v) packDepthToRGBA(v) +#define unpackRGBAToFloat(v) unpackRGBAToDepth(v) +uniform lowp sampler2D luminanceBuffer0;uniform lowp sampler2D luminanceBuffer1;uniform float minLuminance;uniform float deltaTime;uniform float tau;varying vec2 vUv;void main(){float l0=unpackRGBAToFloat(texture2D(luminanceBuffer0,vUv)); +#if __VERSION__ < 300 +float l1=texture2DLodEXT(luminanceBuffer1,vUv,MIP_LEVEL_1X1).r; +#else +float l1=textureLod(luminanceBuffer1,vUv,MIP_LEVEL_1X1).r; +#endif +l0=max(minLuminance,l0);l1=max(minLuminance,l1);float adaptedLum=l0+(l1-l0)*(1.0-exp(-deltaTime*tau));gl_FragColor=(adaptedLum==1.0)?vec4(1.0):packFloatToRGBA(adaptedLum);}`,bre=class extends Oi{constructor(){super({name:"AdaptiveLuminanceMaterial",defines:{MIP_LEVEL_1X1:"0.0"},uniforms:{luminanceBuffer0:new $(null),luminanceBuffer1:new $(null),minLuminance:new $(.01),deltaTime:new $(0),tau:new $(1)},extensions:{shaderTextureLOD:!0},blending:Lr,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:Ere,vertexShader:BR})}set luminanceBuffer0(n){this.uniforms.luminanceBuffer0.value=n}setLuminanceBuffer0(n){this.uniforms.luminanceBuffer0.value=n}set luminanceBuffer1(n){this.uniforms.luminanceBuffer1.value=n}setLuminanceBuffer1(n){this.uniforms.luminanceBuffer1.value=n}set mipLevel1x1(n){this.defines.MIP_LEVEL_1X1=n.toFixed(1),this.needsUpdate=!0}setMipLevel1x1(n){this.mipLevel1x1=n}set deltaTime(n){this.uniforms.deltaTime.value=n}setDeltaTime(n){this.uniforms.deltaTime.value=n}get minLuminance(){return this.uniforms.minLuminance.value}set minLuminance(n){this.uniforms.minLuminance.value=n}getMinLuminance(){return this.uniforms.minLuminance.value}setMinLuminance(n){this.uniforms.minLuminance.value=n}get adaptationRate(){return this.uniforms.tau.value}set adaptationRate(n){this.uniforms.tau.value=n}getAdaptationRate(){return this.uniforms.tau.value}setAdaptationRate(n){this.uniforms.tau.value=n}},Mre=class extends Qr{constructor(n,{minLuminance:e=.01,adaptationRate:t=1}={}){super("AdaptiveLuminancePass"),this.fullscreenMaterial=new bre,this.needsSwap=!1,this.renderTargetPrevious=new pi(1,1,{minFilter:Yn,magFilter:Yn,depthBuffer:!1}),this.renderTargetPrevious.texture.name="Luminance.Previous";const i=this.fullscreenMaterial;i.luminanceBuffer0=this.renderTargetPrevious.texture,i.luminanceBuffer1=n,i.minLuminance=e,i.adaptationRate=t,this.renderTargetAdapted=this.renderTargetPrevious.clone(),this.renderTargetAdapted.texture.name="Luminance.Adapted",this.copyPass=new Fz(this.renderTargetPrevious,!1)}get texture(){return this.renderTargetAdapted.texture}getTexture(){return this.renderTargetAdapted.texture}set mipLevel1x1(n){this.fullscreenMaterial.mipLevel1x1=n}get adaptationRate(){return this.fullscreenMaterial.adaptationRate}set adaptationRate(n){this.fullscreenMaterial.adaptationRate=n}render(n,e,t,i,r){this.fullscreenMaterial.deltaTime=i,n.setRenderTarget(this.renderToScreen?null:this.renderTargetAdapted),n.render(this.scene,this.camera),this.copyPass.render(n,this.renderTargetAdapted)}},Are=`#include +uniform float whitePoint; +#if TONE_MAPPING_MODE == 2 || TONE_MAPPING_MODE == 3 +uniform float middleGrey; +#if TONE_MAPPING_MODE == 3 +uniform lowp sampler2D luminanceBuffer; +#else +uniform float averageLuminance; +#endif +vec3 Reinhard2ToneMapping(vec3 color){color*=toneMappingExposure;float l=luminance(color); +#if TONE_MAPPING_MODE == 3 +float lumAvg=unpackRGBAToFloat(texture2D(luminanceBuffer,vec2(0.5))); +#else +float lumAvg=averageLuminance; +#endif +float lumScaled=(l*middleGrey)/max(lumAvg,1e-6);float lumCompressed=lumScaled*(1.0+lumScaled/(whitePoint*whitePoint));lumCompressed/=(1.0+lumScaled);return clamp(lumCompressed*color,0.0,1.0);} +#elif TONE_MAPPING_MODE == 4 +#define A 0.15 +#define B 0.50 +#define C 0.10 +#define D 0.20 +#define E 0.02 +#define F 0.30 +vec3 Uncharted2Helper(const in vec3 x){return((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}vec3 Uncharted2ToneMapping(vec3 color){color*=toneMappingExposure;return clamp(Uncharted2Helper(color)/Uncharted2Helper(vec3(whitePoint)),0.0,1.0);} +#endif +void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor){ +#if TONE_MAPPING_MODE == 2 || TONE_MAPPING_MODE == 3 +outputColor=vec4(Reinhard2ToneMapping(inputColor.rgb),inputColor.a); +#elif TONE_MAPPING_MODE == 4 +outputColor=vec4(Uncharted2ToneMapping(inputColor.rgb),inputColor.a); +#else +outputColor=vec4(toneMapping(inputColor.rgb),inputColor.a); +#endif +}`,wre=class extends Ug{constructor({blendFunction:n=cn.SRC,adaptive:e=!1,mode:t=e?ca.REINHARD2_ADAPTIVE:ca.AGX,resolution:i=256,maxLuminance:r=4,whitePoint:a=r,middleGrey:s=.6,minLuminance:o=.01,averageLuminance:l=1,adaptationRate:u=1}={}){super("ToneMappingEffect",Are,{blendFunction:n,uniforms:new Map([["luminanceBuffer",new $(null)],["maxLuminance",new $(r)],["whitePoint",new $(a)],["middleGrey",new $(s)],["averageLuminance",new $(l)]])}),this.renderTargetLuminance=new pi(1,1,{minFilter:Ga,depthBuffer:!1}),this.renderTargetLuminance.texture.generateMipmaps=!0,this.renderTargetLuminance.texture.name="Luminance",this.luminancePass=new _re({renderTarget:this.renderTargetLuminance}),this.adaptiveLuminancePass=new Mre(this.luminancePass.texture,{minLuminance:o,adaptationRate:u}),this.uniforms.get("luminanceBuffer").value=this.adaptiveLuminancePass.texture,this.resolution=i,this.mode=t}get mode(){return Number(this.defines.get("TONE_MAPPING_MODE"))}set mode(n){if(this.mode===n)return;const t=$s.replace(/\D+/g,"")>=168?"CineonToneMapping(texel)":"OptimizedCineonToneMapping(texel)";switch(this.defines.clear(),this.defines.set("TONE_MAPPING_MODE",n.toFixed(0)),n){case ca.LINEAR:this.defines.set("toneMapping(texel)","LinearToneMapping(texel)");break;case ca.REINHARD:this.defines.set("toneMapping(texel)","ReinhardToneMapping(texel)");break;case ca.CINEON:case ca.OPTIMIZED_CINEON:this.defines.set("toneMapping(texel)",t);break;case ca.ACES_FILMIC:this.defines.set("toneMapping(texel)","ACESFilmicToneMapping(texel)");break;case ca.AGX:this.defines.set("toneMapping(texel)","AgXToneMapping(texel)");break;case ca.NEUTRAL:this.defines.set("toneMapping(texel)","NeutralToneMapping(texel)");break;default:this.defines.set("toneMapping(texel)","texel");break}this.adaptiveLuminancePass.enabled=n===ca.REINHARD2_ADAPTIVE,this.setChanged()}getMode(){return this.mode}setMode(n){this.mode=n}get whitePoint(){return this.uniforms.get("whitePoint").value}set whitePoint(n){this.uniforms.get("whitePoint").value=n}get middleGrey(){return this.uniforms.get("middleGrey").value}set middleGrey(n){this.uniforms.get("middleGrey").value=n}get averageLuminance(){return this.uniforms.get("averageLuminance").value}set averageLuminance(n){this.uniforms.get("averageLuminance").value=n}get adaptiveLuminanceMaterial(){return this.adaptiveLuminancePass.fullscreenMaterial}getAdaptiveLuminanceMaterial(){return this.adaptiveLuminanceMaterial}get resolution(){return this.luminancePass.resolution.width}set resolution(n){const e=Math.max(0,Math.ceil(Math.log2(n))),t=Math.pow(2,e);this.luminancePass.resolution.setPreferredSize(t,t),this.adaptiveLuminanceMaterial.mipLevel1x1=e}getResolution(){return this.resolution}setResolution(n){this.resolution=n}get adaptive(){return this.mode===ca.REINHARD2_ADAPTIVE}set adaptive(n){this.mode=n?ca.REINHARD2_ADAPTIVE:ca.REINHARD2}get adaptationRate(){return this.adaptiveLuminanceMaterial.adaptationRate}set adaptationRate(n){this.adaptiveLuminanceMaterial.adaptationRate=n}get distinction(){return console.warn(this.name,"distinction was removed."),1}set distinction(n){console.warn(this.name,"distinction was removed.")}update(n,e,t){this.adaptiveLuminancePass.enabled&&(this.luminancePass.render(n,e),this.adaptiveLuminancePass.render(n,null,null,t))}initialize(n,e,t){this.adaptiveLuminancePass.initialize(n,e,t)}},Rre=`#include +#include +#include +#define packFloatToRGBA(v) packDepthToRGBA(v) +#define unpackRGBAToFloat(v) unpackRGBAToDepth(v) +#ifdef FRAMEBUFFER_PRECISION_HIGH +uniform mediump sampler2D inputBuffer; +#else +uniform lowp sampler2D inputBuffer; +#endif +#if DEPTH_PACKING == 3201 +uniform lowp sampler2D depthBuffer; +#elif defined(GL_FRAGMENT_PRECISION_HIGH) +uniform highp sampler2D depthBuffer; +#else +uniform mediump sampler2D depthBuffer; +#endif +uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;vec4 sRGBToLinear(const 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);}float readDepth(const in vec2 uv){ +#if DEPTH_PACKING == 3201 +float depth=unpackRGBAToDepth(texture2D(depthBuffer,uv)); +#else +float depth=texture2D(depthBuffer,uv).r; +#endif +#if defined(USE_LOGARITHMIC_DEPTH_BUFFER) || defined(LOG_DEPTH) +float d=pow(2.0,depth*log2(cameraFar+1.0))-1.0;float a=cameraFar/(cameraFar-cameraNear);float b=cameraFar*cameraNear/(cameraNear-cameraFar);depth=a+b/d; +#elif defined(USE_REVERSED_DEPTH_BUFFER) +depth=1.0-depth; +#endif +return depth;}float getViewZ(const in float depth){ +#ifdef PERSPECTIVE_CAMERA +return perspectiveDepthToViewZ(depth,cameraNear,cameraFar); +#else +return orthographicDepthToViewZ(depth,cameraNear,cameraFar); +#endif +}vec3 RGBToHCV(const in vec3 RGB){vec4 P=mix(vec4(RGB.bg,-1.0,2.0/3.0),vec4(RGB.gb,0.0,-1.0/3.0),step(RGB.b,RGB.g));vec4 Q=mix(vec4(P.xyw,RGB.r),vec4(RGB.r,P.yzx),step(P.x,RGB.r));float C=Q.x-min(Q.w,Q.y);float H=abs((Q.w-Q.y)/(6.0*C+EPSILON)+Q.z);return vec3(H,C,Q.x);}vec3 RGBToHSL(const in vec3 RGB){vec3 HCV=RGBToHCV(RGB);float L=HCV.z-HCV.y*0.5;float S=HCV.y/(1.0-abs(L*2.0-1.0)+EPSILON);return vec3(HCV.x,S,L);}vec3 HueToRGB(const in float H){float R=abs(H*6.0-3.0)-1.0;float G=2.0-abs(H*6.0-2.0);float B=2.0-abs(H*6.0-4.0);return clamp(vec3(R,G,B),0.0,1.0);}vec3 HSLToRGB(const in vec3 HSL){vec3 RGB=HueToRGB(HSL.x);float C=(1.0-abs(2.0*HSL.z-1.0))*HSL.y;return(RGB-0.5)*C+HSL.z;}FRAGMENT_HEAD void main(){FRAGMENT_MAIN_UV vec4 color0=texture2D(inputBuffer,UV);vec4 color1=vec4(0.0);FRAGMENT_MAIN_IMAGE color0.a=clamp(color0.a,0.0,1.0);gl_FragColor=color0; +#ifdef ENCODE_OUTPUT +#include +#endif +#include +}`,Cre="uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;VERTEX_HEAD void main(){vUv=position.xy*0.5+0.5;VERTEX_MAIN_SUPPORT gl_Position=vec4(position.xy,1.0,1.0);}",Dre=class extends Oi{constructor(n,e,t,i,r=!1){super({name:"EffectMaterial",defines:{THREE_REVISION:$s.replace(/\D+/g,""),DEPTH_PACKING:"0",ENCODE_OUTPUT:"1"},uniforms:{inputBuffer:new $(null),depthBuffer:new $(null),resolution:new $(new re),texelSize:new $(new re),cameraNear:new $(.3),cameraFar:new $(1e3),aspect:new $(1),time:new $(0)},blending:Lr,toneMapped:!1,depthWrite:!1,depthTest:!1,dithering:r}),n&&this.setShaderParts(n),e&&this.setDefines(e),t&&this.setUniforms(t),this.copyCameraSettings(i)}set inputBuffer(n){this.uniforms.inputBuffer.value=n}setInputBuffer(n){this.uniforms.inputBuffer.value=n}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(n){this.uniforms.depthBuffer.value=n}get depthPacking(){return Number(this.defines.DEPTH_PACKING)}set depthPacking(n){this.defines.DEPTH_PACKING=n.toFixed(0),this.needsUpdate=!0}setDepthBuffer(n,e=su){this.depthBuffer=n,this.depthPacking=e}setShaderData(n){this.setShaderParts(n.shaderParts),this.setDefines(n.defines),this.setUniforms(n.uniforms),this.setExtensions(n.extensions)}setShaderParts(n){return this.fragmentShader=Rre.replace(Sn.FRAGMENT_HEAD,n.get(Sn.FRAGMENT_HEAD)||"").replace(Sn.FRAGMENT_MAIN_UV,n.get(Sn.FRAGMENT_MAIN_UV)||"").replace(Sn.FRAGMENT_MAIN_IMAGE,n.get(Sn.FRAGMENT_MAIN_IMAGE)||""),this.vertexShader=Cre.replace(Sn.VERTEX_HEAD,n.get(Sn.VERTEX_HEAD)||"").replace(Sn.VERTEX_MAIN_SUPPORT,n.get(Sn.VERTEX_MAIN_SUPPORT)||""),this.needsUpdate=!0,this}setDefines(n){for(const e of n.entries())this.defines[e[0]]=e[1];return this.needsUpdate=!0,this}setUniforms(n){for(const e of n.entries())this.uniforms[e[0]]=e[1];return this}setExtensions(n){this.extensions={};for(const e of n)this.extensions[e]=!0;return this}get encodeOutput(){return this.defines.ENCODE_OUTPUT!==void 0}set encodeOutput(n){this.encodeOutput!==n&&(n?this.defines.ENCODE_OUTPUT="1":delete this.defines.ENCODE_OUTPUT,this.needsUpdate=!0)}isOutputEncodingEnabled(n){return this.encodeOutput}setOutputEncodingEnabled(n){this.encodeOutput=n}get time(){return this.uniforms.time.value}set time(n){this.uniforms.time.value=n}setDeltaTime(n){this.uniforms.time.value+=n}adoptCameraSettings(n){this.copyCameraSettings(n)}copyCameraSettings(n){n&&(this.uniforms.cameraNear.value=n.near,this.uniforms.cameraFar.value=n.far,n instanceof si?this.defines.PERSPECTIVE_CAMERA="1":delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0)}setSize(n,e){const t=this.uniforms;t.resolution.value.set(n,e),t.texelSize.value.set(1/n,1/e),t.aspect.value=n/e}static get Section(){return Sn}};function PI(n,e,t){for(const i of e){const r="$1"+n+i.charAt(0).toUpperCase()+i.slice(1),a=new RegExp("([^\\.])(\\b"+i+"\\b)","g");for(const s of t.entries())s[1]!==null&&t.set(s[0],s[1].replace(a,r))}}function Nre(n,e,t){let i=e.getFragmentShader(),r=e.getVertexShader();const a=i!==void 0&&/mainImage/.test(i),s=i!==void 0&&/mainUv/.test(i);if(t.attributes|=e.getAttributes(),i===void 0)throw new Error(`Missing fragment shader (${e.name})`);if(s&&t.attributes&Dl.CONVOLUTION)throw new Error(`Effects that transform UVs are incompatible with convolution effects (${e.name})`);if(!a&&!s)throw new Error(`Could not find mainImage or mainUv function (${e.name})`);{const o=/\w+\s+(\w+)\([\w\s,]*\)\s*{/g,l=t.shaderParts;let u=l.get(Sn.FRAGMENT_HEAD)||"",d=l.get(Sn.FRAGMENT_MAIN_UV)||"",f=l.get(Sn.FRAGMENT_MAIN_IMAGE)||"",p=l.get(Sn.VERTEX_HEAD)||"",m=l.get(Sn.VERTEX_MAIN_SUPPORT)||"";const v=new Set,x=new Set;if(s&&(d+=` ${n}MainUv(UV); +`,t.uvTransformation=!0),r!==null&&/mainSupport/.test(r)){const T=/mainSupport *\([\w\s]*?uv\s*?\)/.test(r);m+=` ${n}MainSupport(`,m+=T?`vUv); +`:`); +`;for(const E of r.matchAll(/(?:varying\s+\w+\s+([\S\s]*?);)/g))for(const b of E[1].split(/\s*,\s*/))t.varyings.add(b),v.add(b),x.add(b);for(const E of r.matchAll(o))x.add(E[1])}for(const T of i.matchAll(o))x.add(T[1]);for(const T of e.defines.keys())x.add(T.replace(/\([\w\s,]*\)/g,""));for(const T of e.uniforms.keys())x.add(T);x.delete("while"),x.delete("for"),x.delete("if"),e.uniforms.forEach((T,E)=>t.uniforms.set(n+E.charAt(0).toUpperCase()+E.slice(1),T)),e.defines.forEach((T,E)=>t.defines.set(n+E.charAt(0).toUpperCase()+E.slice(1),T));const S=new Map([["fragment",i],["vertex",r]]);PI(n,x,t.defines),PI(n,x,S),i=S.get("fragment"),r=S.get("vertex");const _=e.blendMode;if(t.blendModes.set(_.blendFunction,_),a){e.inputColorSpace!==null&&e.inputColorSpace!==t.colorSpace&&(f+=e.inputColorSpace===mn?`color0 = sRGBTransferOETF(color0); + `:`color0 = sRGBToLinear(color0); + `),e.outputColorSpace!==Xr?t.colorSpace=e.outputColorSpace:e.inputColorSpace!==null&&(t.colorSpace=e.inputColorSpace);const T=/MainImage *\([\w\s,]*?depth[\w\s,]*?\)/;f+=`${n}MainImage(color0, UV, `,t.attributes&Dl.DEPTH&&T.test(i)&&(f+="depth, ",t.readDepth=!0),f+=`color1); + `;const E=n+"BlendOpacity";t.uniforms.set(E,_.opacity),f+=`color0 = blend${_.blendFunction}(color0, color1, ${E}); + + `,u+=`uniform float ${E}; + +`}if(u+=i+` +`,r!==null&&(p+=r+` +`),l.set(Sn.FRAGMENT_HEAD,u),l.set(Sn.FRAGMENT_MAIN_UV,d),l.set(Sn.FRAGMENT_MAIN_IMAGE,f),l.set(Sn.VERTEX_HEAD,p),l.set(Sn.VERTEX_MAIN_SUPPORT,m),e.extensions!==null)for(const T of e.extensions)t.extensions.add(T)}}var Ore=class extends Qr{constructor(n,...e){super("EffectPass"),this.fullscreenMaterial=new Dre(null,null,null,n),this.listener=t=>this.handleEvent(t),this.effects=[],this.setEffects(e),this.skipRendering=!1,this.minTime=1,this.maxTime=Number.POSITIVE_INFINITY,this.timeScale=1}set mainScene(n){for(const e of this.effects)e.mainScene=n}set mainCamera(n){this.fullscreenMaterial.copyCameraSettings(n);for(const e of this.effects)e.mainCamera=n}get encodeOutput(){return this.fullscreenMaterial.encodeOutput}set encodeOutput(n){this.fullscreenMaterial.encodeOutput=n}get dithering(){return this.fullscreenMaterial.dithering}set dithering(n){const e=this.fullscreenMaterial;e.dithering=n,e.needsUpdate=!0}setEffects(n){for(const e of this.effects)e.removeEventListener("change",this.listener);this.effects=n.sort((e,t)=>t.attributes-e.attributes);for(const e of this.effects)e.addEventListener("change",this.listener)}updateMaterial(){const n=new Pie;let e=0;for(const s of this.effects)if(s.blendMode.blendFunction===cn.DST)n.attributes|=s.getAttributes()&Dl.DEPTH;else{if(n.attributes&s.getAttributes()&Dl.CONVOLUTION)throw new Error(`Convolution effects cannot be merged (${s.name})`);Nre("e"+e++,s,n)}let t=n.shaderParts.get(Sn.FRAGMENT_HEAD),i=n.shaderParts.get(Sn.FRAGMENT_MAIN_IMAGE),r=n.shaderParts.get(Sn.FRAGMENT_MAIN_UV);const a=/\bblend\b/g;for(const s of n.blendModes.values())t+=s.getShaderCode().replace(a,`blend${s.blendFunction}`)+` +`;n.attributes&Dl.DEPTH?(n.readDepth&&(i=`float depth = readDepth(UV); + + `+i),this.needsDepthTexture=this.getDepthTexture()===null):this.needsDepthTexture=!1,n.colorSpace===mn&&(i+=`color0 = sRGBToLinear(color0); + `),n.uvTransformation?(r=`vec2 transformedUv = vUv; +`+r,n.defines.set("UV","transformedUv")):n.defines.set("UV","vUv"),n.shaderParts.set(Sn.FRAGMENT_HEAD,t),n.shaderParts.set(Sn.FRAGMENT_MAIN_IMAGE,i),n.shaderParts.set(Sn.FRAGMENT_MAIN_UV,r);for(const[s,o]of n.shaderParts)o!==null&&n.shaderParts.set(s,o.trim().replace(/^#/,` +#`));this.skipRendering=e===0,this.needsSwap=!this.skipRendering,this.fullscreenMaterial.setShaderData(n)}recompile(){this.updateMaterial()}getDepthTexture(){return this.fullscreenMaterial.depthBuffer}setDepthTexture(n,e=su){this.fullscreenMaterial.depthBuffer=n,this.fullscreenMaterial.depthPacking=e;for(const t of this.effects)t.setDepthTexture(n,e)}render(n,e,t,i,r){for(const a of this.effects)a.update(n,e,i);if(!this.skipRendering||this.renderToScreen){const a=this.fullscreenMaterial;a.inputBuffer=e.texture,a.time+=i*this.timeScale,n.setRenderTarget(this.renderToScreen?null:t),n.render(this.scene,this.camera)}}setSize(n,e){this.fullscreenMaterial.setSize(n,e);for(const t of this.effects)t.setSize(n,e)}initialize(n,e,t){this.renderer=n;for(const i of this.effects)i.initialize(n,e,t);this.updateMaterial(),t!==void 0&&t!==Ni&&(this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1")}dispose(){super.dispose();for(const n of this.effects)n.removeEventListener("change",this.listener),n.dispose()}handleEvent(n){switch(n.type){case"change":this.recompile();break}}},Lre=class extends Qr{constructor(n,e,{renderTarget:t,resolutionScale:i=1,width:r=Rs.AUTO_SIZE,height:a=Rs.AUTO_SIZE,resolutionX:s=r,resolutionY:o=a}={}){super("NormalPass"),this.needsSwap=!1,this.renderPass=new FR(n,e,new vR);const l=this.renderPass;l.ignoreBackground=!0,l.skipShadowMapUpdate=!0;const u=l.getClearPass();u.overrideClearColor=new Ye(7829503),u.overrideClearAlpha=1,this.renderTarget=t,this.renderTarget===void 0&&(this.renderTarget=new pi(1,1,{minFilter:Yn,magFilter:Yn}),this.renderTarget.texture.name="NormalPass.Target");const d=this.resolution=new Rs(this,s,o,i);d.addEventListener("change",f=>this.setSize(d.baseWidth,d.baseHeight))}set mainScene(n){this.renderPass.mainScene=n}set mainCamera(n){this.renderPass.mainCamera=n}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}getResolutionScale(){return this.resolution.scale}setResolutionScale(n){this.resolution.scale=n}render(n,e,t,i,r){const a=this.renderToScreen?null:this.renderTarget;this.renderPass.render(n,a,a)}setSize(n,e){const t=this.resolution;t.setBaseSize(n,e),this.renderTarget.setSize(t.width,t.height)}};function rg(n,e,t){return e in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}new re;new re;function Vz(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}var us=function n(e,t,i){var r=this;Vz(this,n),rg(this,"dot2",function(a,s){return r.x*a+r.y*s}),rg(this,"dot3",function(a,s,o){return r.x*a+r.y*s+r.z*o}),this.x=e,this.y=t,this.z=i},Ire=[new us(1,1,0),new us(-1,1,0),new us(1,-1,0),new us(-1,-1,0),new us(1,0,1),new us(-1,0,1),new us(1,0,-1),new us(-1,0,-1),new us(0,1,1),new us(0,-1,1),new us(0,1,-1),new us(0,-1,-1)],zI=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180],BI=new Array(512),FI=new Array(512),Ure=function(e){e>0&&e<1&&(e*=65536),e=Math.floor(e),e<256&&(e|=e<<8);for(var t=0;t<256;t++){var i;t&1?i=zI[t]^e&255:i=zI[t]^e>>8&255,BI[t]=BI[t+256]=i,FI[t]=FI[t+256]=Ire[i%12]}};Ure(0);function Pre(n){if(typeof n=="number")n=Math.abs(n);else if(typeof n=="string"){var e=n;n=0;for(var t=0;t(n.getAttributes()&2)===2,Vre=ie.memo(ie.forwardRef(({children:n,camera:e,scene:t,resolutionScale:i,enabled:r=!0,renderPriority:a=1,autoClear:s=!0,depthBuffer:o,enableNormalPass:l,stencilBuffer:u,multisampling:d=8,frameBufferType:f=Jn},p)=>{const{gl:m,scene:v,camera:x,size:S}=pn(),_=t||v,T=e||x,[E,b,R]=ie.useMemo(()=>{const U=new Uie(m,{depthBuffer:o,stencilBuffer:u,multisampling:d,frameBufferType:f});U.addPass(new FR(_,T));let N=null,C=null;return l&&(C=new Lre(_,T),C.enabled=!1,U.addPass(C),i!==void 0&&(N=new Tre({normalBuffer:C.texture,resolutionScale:i}),N.enabled=!1,U.addPass(N))),[U,C,N]},[T,m,o,u,d,f,_,l,i]);ie.useEffect(()=>E==null?void 0:E.setSize(S.width,S.height),[E,S]),_a((U,N)=>{if(r){const C=m.autoClear;m.autoClear=s,u&&!s&&m.clearStencil(),E.render(N),m.autoClear=C}},r?a:0);const w=ie.useRef(null);ie.useLayoutEffect(()=>{var C;const U=[],N=w.current.__r3f;if(N&&E){const z=N.children;for(let W=0;W{for(const z of U)E==null||E.removePass(z);b&&(b.enabled=!1),R&&(R.enabled=!1)}},[E,n,T,b,R]),ie.useEffect(()=>{const U=m.toneMapping;return m.toneMapping=As,()=>{m.toneMapping=U}},[m]);const L=ie.useMemo(()=>({composer:E,normalPass:b,downSamplingPass:R,resolutionScale:i,camera:T,scene:_}),[E,b,R,i,T,_]);return ie.useImperativeHandle(p,()=>E,[E]),ot.jsx(HR.Provider,{value:L,children:ot.jsx("group",{ref:w,children:n})})}));let Gre=0;const GI=new WeakMap,kre=(n,e)=>function({blendFunction:t=e==null?void 0:e.blendFunction,opacity:i=e==null?void 0:e.opacity,...r}){let a=GI.get(n);if(!a){const l=`@react-three/postprocessing/${n.name}-${Gre++}`;rz({[l]:n}),GI.set(n,a=l)}const s=pn(l=>l.camera),o=QA.useMemo(()=>[...(e==null?void 0:e.args)??[],...r.args??[{...e,...r}]],[JSON.stringify(r)]);return ot.jsx(a,{camera:s,"blendMode-blendFunction":t,"blendMode-opacity-value":i,...r,args:o})},Wre=kre(wre);var Xre="Invariant failed";function Wy(n,e){if(!n)throw new Error(Xre)}const qre=new D;function kz(n,e,t=new D,i){const{x:r,y:a,z:s}=n,o=e.x,l=e.y,u=e.z,d=r*r*o,f=a*a*l,p=s*s*u,m=d+f+p,v=Math.sqrt(1/m);if(!Number.isFinite(v))return;const x=qre.copy(n).multiplyScalar(v);if(m<((i==null?void 0:i.centerTolerance)??.1))return t.copy(x);const S=x.multiply(e).multiplyScalar(2);let _=(1-v)*n.length()/(S.length()/2),T=0,E,b,R,w;do{_-=T,E=1/(1+_*o),b=1/(1+_*l),R=1/(1+_*u);const L=E*E,U=b*b,N=R*R,C=L*E,z=U*b,W=N*R;w=d*L+f*U+p*N-1,T=w/((d*C*o+f*z*l+p*W*u)*-2)}while(Math.abs(w)>1e-12);return t.set(r*E,a*b,s*R)}const uf=new D,Jb=new D,$b=new D,fA=class{constructor(e,t,i){this.radii=new D(e,t,i)}get minimumRadius(){return Math.min(this.radii.x,this.radii.y,this.radii.z)}get maximumRadius(){return Math.max(this.radii.x,this.radii.y,this.radii.z)}get flattening(){return 1-this.minimumRadius/this.maximumRadius}get eccentricity(){return Math.sqrt(this.eccentricitySquared)}get eccentricitySquared(){const e=this.maximumRadius**2,t=this.minimumRadius**2;return(e-t)/e}reciprocalRadii(e=new D){const{x:t,y:i,z:r}=this.radii;return e.set(1/t,1/i,1/r)}reciprocalRadiiSquared(e=new D){const{x:t,y:i,z:r}=this.radii;return e.set(1/t**2,1/i**2,1/r**2)}projectOnSurface(e,t=new D,i){return kz(e,this.reciprocalRadiiSquared(),t,i)}getSurfaceNormal(e,t=new D){return t.multiplyVectors(this.reciprocalRadiiSquared(uf),e).normalize()}getEastNorthUpVectors(e,t=new D,i=new D,r=new D){this.getSurfaceNormal(e,r),t.set(-e.y,e.x,0).normalize(),i.crossVectors(r,t).normalize()}getEastNorthUpFrame(e,t=new Me){const i=uf,r=Jb,a=$b;return this.getEastNorthUpVectors(e,i,r,a),t.makeBasis(i,r,a).setPosition(e)}getNorthUpEastFrame(e,t=new Me){const i=uf,r=Jb,a=$b;return this.getEastNorthUpVectors(e,i,r,a),t.makeBasis(r,a,i).setPosition(e)}getIntersection(e,t=new D){const i=this.reciprocalRadii(uf),r=Jb.copy(i).multiply(e.origin),a=$b.copy(i).multiply(e.direction),s=r.lengthSq(),o=a.lengthSq(),l=r.dot(a),u=l**2-o*(s-1);if(s===1)return t.copy(e.origin);if(s>1){if(l>=0||u<0)return;const d=Math.sqrt(u),f=(-l-d)/o,p=(-l+d)/o;return e.at(Math.min(f,p),t)}if(s<1){const d=l**2-o*(s-1),f=Math.sqrt(d),p=(-l+f)/o;return e.at(p,t)}if(l<0)return e.at(-l/o,t)}getOsculatingSphereCenter(e,t,i=new D){Wy(this.radii.x===this.radii.y);const r=this.radii.x**2,a=this.radii.z**2,s=uf.set(e.x/r,e.y/r,e.z/a).normalize();return i.copy(s.multiplyScalar(-t).add(e))}getNormalAtHorizon(e,t,i=new D){Wy(this.radii.x===this.radii.y);const r=this.radii.x**2,a=this.radii.z**2,s=e,o=t;let l=(s.x*o.x+s.y*o.y)/r+s.z*o.z/a;l/=(s.x**2+s.y**2)/r+s.z**2/a;const u=uf.copy(o).multiplyScalar(-l).add(e);return i.set(u.x/r,u.y/r,u.z/a).normalize()}};fA.WGS84=new fA(6378137,6378137,6356752314245179e-9);let kh=fA;const px=new D,kI=new D,D0=class pA{constructor(e=0,t=0,i=0){this.longitude=e,this.latitude=t,this.height=i}set(e,t,i){return this.longitude=e,this.latitude=t,i!=null&&(this.height=i),this}clone(){return new pA(this.longitude,this.latitude,this.height)}copy(e){return this.longitude=e.longitude,this.latitude=e.latitude,this.height=e.height,this}equals(e){return e.longitude===this.longitude&&e.latitude===this.latitude&&e.height===this.height}setLongitude(e){return this.longitude=e,this}setLatitude(e){return this.latitude=e,this}setHeight(e){return this.height=e,this}normalize(){return this.longitude +Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE +version 0.8.2 +*/var Es=Uint8Array,Gf=Uint16Array,Yre=Int32Array,Wz=new Es([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Xz=new Es([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),jre=new Es([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qz=function(n,e){for(var t=new Gf(31),i=0;i<31;++i)t[i]=e+=1<>1|(oi&21845)<<1;pc=(pc&52428)>>2|(pc&13107)<<2,pc=(pc&61680)>>4|(pc&3855)<<4,mA[oi]=((pc&65280)>>8|(pc&255)<<8)>>1}var ag=function(n,e,t){for(var i=n.length,r=0,a=new Gf(e);r>l]=u}else for(o=new Gf(i),r=0;r>15-n[r]);return o},hv=new Es(288);for(var oi=0;oi<144;++oi)hv[oi]=8;for(var oi=144;oi<256;++oi)hv[oi]=9;for(var oi=256;oi<280;++oi)hv[oi]=7;for(var oi=280;oi<288;++oi)hv[oi]=8;var Zz=new Es(32);for(var oi=0;oi<32;++oi)Zz[oi]=5;var Jre=ag(hv,9,1),$re=ag(Zz,5,1),eM=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},Hs=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},tM=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},eae=function(n){return(n+7)/8|0},tae=function(n,e,t){return(t==null||t>n.length)&&(t=n.length),new Es(n.subarray(e,t))},nae=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],qs=function(n,e,t){var i=new Error(e||nae[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,qs),!t)throw i;return i},iae=function(n,e,t,i){var r=n.length,a=0;if(!r||e.f&&!e.l)return t||new Es(0);var s=!t,o=s||e.i!=2,l=e.i;s&&(t=new Es(r*3));var u=function(wt){var ct=t.length;if(wt>ct){var Qe=new Es(Math.max(ct*2,wt));Qe.set(t),t=Qe}},d=e.f||0,f=e.p||0,p=e.b||0,m=e.l,v=e.d,x=e.m,S=e.n,_=r*8;do{if(!m){d=Hs(n,f,1);var T=Hs(n,f+1,3);if(f+=3,T)if(T==1)m=Jre,v=$re,x=9,S=5;else if(T==2){var w=Hs(n,f,31)+257,L=Hs(n,f+10,15)+4,U=w+Hs(n,f+5,31)+1;f+=14;for(var N=new Es(U),C=new Es(19),z=0;z>4;if(E<16)N[z++]=E;else{var X=0,te=0;for(E==16?(te=3+Hs(n,f,3),f+=2,X=N[z-1]):E==17?(te=3+Hs(n,f,7),f+=3):E==18&&(te=11+Hs(n,f,127),f+=7);te--;)N[z++]=X}}var Q=N.subarray(0,w),ce=N.subarray(w);x=eM(Q),S=eM(ce),m=ag(Q,x,1),v=ag(ce,S,1)}else qs(1);else{var E=eae(f)+4,b=n[E-4]|n[E-3]<<8,R=E+b;if(R>r){l&&qs(0);break}o&&u(p+b),t.set(n.subarray(E,R),p),e.b=p+=b,e.p=f=R*8,e.f=d;continue}if(f>_){l&&qs(0);break}}o&&u(p+131072);for(var se=(1<>4;if(f+=X&15,f>_){l&&qs(0);break}if(X||qs(2),nt<256)t[p++]=nt;else if(nt==256){Xe=f,m=null;break}else{var tt=nt-254;if(nt>264){var z=nt-257,xt=Wz[z];tt=Hs(n,f,(1<>4;ve||qs(3),f+=ve&15;var ce=Kre[we];if(we>3){var xt=Xz[we];ce+=tM(n,f)&(1<_){l&&qs(0);break}o&&u(p+131072);var Ze=p+tt;if(p>4>7||(n[0]<<8|n[1])%31)&&qs(6,"invalid zlib data"),(n[1]>>5&1)==1&&qs(6,"invalid zlib data: "+(n[1]&32?"need":"unexpected")+" dictionary"),(n[1]>>3&4)+2};function mx(n,e){return iae(n.subarray(aae(n),-4),{i:2},e,e)}var sae=typeof TextDecoder<"u"&&new TextDecoder,oae=0;try{sae.decode(rae,{stream:!0}),oae=1}catch{}class Qz extends h7{constructor(e){super(e),this.type=Jn,this.outputFormat=ai}parse(e){const N=Math.pow(2.7182818,2.2);function C(O,B){let Y=0;for(let G=0;G<65536;++G)(G==0||O[G>>3]&1<<(G&7))&&(B[Y++]=G);const I=Y-1;for(;Y<65536;)B[Y++]=0;return I}function z(O){for(let B=0;B<16384;B++)O[B]={},O[B].len=0,O[B].lit=0,O[B].p=null}const W={l:0,c:0,lc:0};function K(O,B,Y,I,G){for(;Y>Y&(1<0;--Y){const I=B+oe[Y]>>1;oe[Y]=B,B=I}for(let Y=0;Y<65537;++Y){const I=O[Y];I>0&&(O[Y]=I|oe[I]++<<6)}}function X(O,B,Y,I,G,Z){const F=B;let q=0,ne=0;for(;I<=G;I++){if(F.value-B.value>Y)return!1;K(6,q,ne,O,F);const le=W.l;if(q=W.c,ne=W.lc,Z[I]=le,le==63){if(F.value-B.value>Y)throw new Error("Something wrong with hufUnpackEncTable");K(8,q,ne,O,F);let pe=W.l+6;if(q=W.c,ne=W.lc,I+pe>G+1)throw new Error("Something wrong with hufUnpackEncTable");for(;pe--;)Z[I++]=0;I--}else if(le>=59){let pe=le-59+2;if(I+pe>G+1)throw new Error("Something wrong with hufUnpackEncTable");for(;pe--;)Z[I++]=0;I--}}ae(Z)}function te(O){return O&63}function Q(O){return O>>6}function ce(O,B,Y,I){for(;B<=Y;B++){const G=Q(O[B]),Z=te(O[B]);if(G>>Z)throw new Error("Invalid table entry");if(Z>14){const F=I[G>>Z-14];if(F.len)throw new Error("Invalid table entry");if(F.lit++,F.p){const q=F.p;F.p=new Array(F.lit);for(let ne=0;ne0;q--){const ne=I[(G<<14-Z)+F];if(ne.len||ne.p)throw new Error("Invalid table entry");ne.len=Z,ne.lit=B,F++}}}return!0}const se={c:0,lc:0};function De(O,B,Y,I){O=O<<8|J(Y,I),B+=8,se.c=O,se.lc=B}const Xe={c:0,lc:0};function nt(O,B,Y,I,G,Z,F,q,ne){if(O==B){I<8&&(De(Y,I,G,Z),Y=se.c,I=se.lc),I-=8;let le=Y>>I;if(le=new Uint8Array([le])[0],q.value+le>ne)return!1;const pe=F[q.value-1];for(;le-- >0;)F[q.value++]=pe}else if(q.value32767?B-65536:B}const ve={a:0,b:0};function we(O,B){const Y=xt(O),G=xt(B),Z=Y+(G&1)+(G>>1),F=Z,q=Z-G;ve.a=F,ve.b=q}function Ze(O,B){const Y=tt(O),I=tt(B),G=Y-(I>>1)&65535,Z=I+G-32768&65535;ve.a=Z,ve.b=G}function de(O,B,Y,I,G,Z,F){const q=F<16384,ne=Y>G?G:Y;let le=1,pe,xe;for(;le<=ne;)le<<=1;for(le>>=1,pe=le,le>>=1;le>=1;){xe=0;const Te=xe+Z*(G-pe),Ce=Z*le,ze=Z*pe,Be=I*le,qe=I*pe;let ut,At,Rt,mt;for(;xe<=Te;xe+=ze){let Dt=xe;const st=xe+I*(Y-pe);for(;Dt<=st;Dt+=qe){const Kt=Dt+Be,Pn=Dt+Ce,Yt=Pn+Be;q?(we(O[Dt+B],O[Pn+B]),ut=ve.a,Rt=ve.b,we(O[Kt+B],O[Yt+B]),At=ve.a,mt=ve.b,we(ut,At),O[Dt+B]=ve.a,O[Kt+B]=ve.b,we(Rt,mt),O[Pn+B]=ve.a,O[Yt+B]=ve.b):(Ze(O[Dt+B],O[Pn+B]),ut=ve.a,Rt=ve.b,Ze(O[Kt+B],O[Yt+B]),At=ve.a,mt=ve.b,Ze(ut,At),O[Dt+B]=ve.a,O[Kt+B]=ve.b,Ze(Rt,mt),O[Pn+B]=ve.a,O[Yt+B]=ve.b)}if(Y&le){const Kt=Dt+Ce;q?we(O[Dt+B],O[Kt+B]):Ze(O[Dt+B],O[Kt+B]),ut=ve.a,O[Kt+B]=ve.b,O[Dt+B]=ut}}if(G&le){let Dt=xe;const st=xe+I*(Y-pe);for(;Dt<=st;Dt+=qe){const Kt=Dt+Be;q?we(O[Dt+B],O[Kt+B]):Ze(O[Dt+B],O[Kt+B]),ut=ve.a,O[Kt+B]=ve.b,O[Dt+B]=ut}}pe=le,le>>=1}return xe}function it(O,B,Y,I,G,Z,F,q,ne){let le=0,pe=0;const xe=F,Te=Math.trunc(I.value+(G+7)/8);for(;I.value=14;){const ze=le>>pe-14&16383,Be=B[ze];if(Be.len)pe-=Be.len,nt(Be.lit,Z,le,pe,Y,I,q,ne,xe),le=Xe.c,pe=Xe.lc;else{if(!Be.p)throw new Error("hufDecode issues");let qe;for(qe=0;qe=ut&&Q(O[Be.p[qe]])==(le>>pe-ut&(1<>=Ce,pe-=Ce;pe>0;){const ze=B[le<<14-pe&16383];if(ze.len)pe-=ze.len,nt(ze.lit,Z,le,pe,Y,I,q,ne,xe),le=Xe.c,pe=Xe.lc;else throw new Error("hufDecode issues")}return!0}function wt(O,B,Y,I,G,Z){const F={value:0},q=Y.value,ne=pt(B,Y),le=pt(B,Y);Y.value+=4;const pe=pt(B,Y);if(Y.value+=4,ne<0||ne>=65537||le<0||le>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const xe=new Array(65537),Te=new Array(16384);z(Te);const Ce=I-(Y.value-q);if(X(O,Y,Ce,ne,le,xe),pe>8*(I-(Y.value-q)))throw new Error("Something wrong with hufUncompress");ce(xe,ne,le,Te),it(xe,Te,O,Y,pe,le,Z,G,F)}function ct(O,B,Y){for(let I=0;IZ||(B[G++]=O[Y++],G>Z));)B[G++]=O[I++]}function V(O){let B=O.byteLength;const Y=new Array;let I=0;const G=new DataView(O);for(;B>0;){const Z=G.getInt8(I++);if(Z<0){const F=-Z;B-=F+1;for(let q=0;q>8==255?G+=I&255:(Y[G]=I,G++),O.value++}function Fe(O,B){B[0]=ge(O[0]),B[1]=ge(O[1]),B[2]=ge(O[5]),B[3]=ge(O[6]),B[4]=ge(O[14]),B[5]=ge(O[15]),B[6]=ge(O[27]),B[7]=ge(O[28]),B[8]=ge(O[2]),B[9]=ge(O[4]),B[10]=ge(O[7]),B[11]=ge(O[13]),B[12]=ge(O[16]),B[13]=ge(O[26]),B[14]=ge(O[29]),B[15]=ge(O[42]),B[16]=ge(O[3]),B[17]=ge(O[8]),B[18]=ge(O[12]),B[19]=ge(O[17]),B[20]=ge(O[25]),B[21]=ge(O[30]),B[22]=ge(O[41]),B[23]=ge(O[43]),B[24]=ge(O[9]),B[25]=ge(O[11]),B[26]=ge(O[18]),B[27]=ge(O[24]),B[28]=ge(O[31]),B[29]=ge(O[40]),B[30]=ge(O[44]),B[31]=ge(O[53]),B[32]=ge(O[10]),B[33]=ge(O[19]),B[34]=ge(O[23]),B[35]=ge(O[32]),B[36]=ge(O[39]),B[37]=ge(O[45]),B[38]=ge(O[52]),B[39]=ge(O[54]),B[40]=ge(O[20]),B[41]=ge(O[22]),B[42]=ge(O[33]),B[43]=ge(O[38]),B[44]=ge(O[46]),B[45]=ge(O[51]),B[46]=ge(O[55]),B[47]=ge(O[60]),B[48]=ge(O[21]),B[49]=ge(O[34]),B[50]=ge(O[37]),B[51]=ge(O[47]),B[52]=ge(O[50]),B[53]=ge(O[56]),B[54]=ge(O[59]),B[55]=ge(O[61]),B[56]=ge(O[35]),B[57]=ge(O[36]),B[58]=ge(O[48]),B[59]=ge(O[49]),B[60]=ge(O[57]),B[61]=ge(O[58]),B[62]=ge(O[62]),B[63]=ge(O[63])}function $e(O){const B=.5*Math.cos(.7853975),Y=.5*Math.cos(3.14159/16),I=.5*Math.cos(3.14159/8),G=.5*Math.cos(3*3.14159/16),Z=.5*Math.cos(5*3.14159/16),F=.5*Math.cos(3*3.14159/8),q=.5*Math.cos(7*3.14159/16),ne=new Array(4),le=new Array(4),pe=new Array(4),xe=new Array(4);for(let Te=0;Te<8;++Te){const Ce=Te*8;ne[0]=I*O[Ce+2],ne[1]=F*O[Ce+2],ne[2]=I*O[Ce+6],ne[3]=F*O[Ce+6],le[0]=Y*O[Ce+1]+G*O[Ce+3]+Z*O[Ce+5]+q*O[Ce+7],le[1]=G*O[Ce+1]-q*O[Ce+3]-Y*O[Ce+5]-Z*O[Ce+7],le[2]=Z*O[Ce+1]-Y*O[Ce+3]+q*O[Ce+5]+G*O[Ce+7],le[3]=q*O[Ce+1]-Z*O[Ce+3]+G*O[Ce+5]-Y*O[Ce+7],pe[0]=B*(O[Ce+0]+O[Ce+4]),pe[3]=B*(O[Ce+0]-O[Ce+4]),pe[1]=ne[0]+ne[3],pe[2]=ne[1]-ne[2],xe[0]=pe[0]+pe[1],xe[1]=pe[3]+pe[2],xe[2]=pe[3]-pe[2],xe[3]=pe[0]-pe[1],O[Ce+0]=xe[0]+le[0],O[Ce+1]=xe[1]+le[1],O[Ce+2]=xe[2]+le[2],O[Ce+3]=xe[3]+le[3],O[Ce+4]=xe[3]-le[3],O[Ce+5]=xe[2]-le[2],O[Ce+6]=xe[1]-le[1],O[Ce+7]=xe[0]-le[0]}for(let Te=0;Te<8;++Te)ne[0]=I*O[16+Te],ne[1]=F*O[16+Te],ne[2]=I*O[48+Te],ne[3]=F*O[48+Te],le[0]=Y*O[8+Te]+G*O[24+Te]+Z*O[40+Te]+q*O[56+Te],le[1]=G*O[8+Te]-q*O[24+Te]-Y*O[40+Te]-Z*O[56+Te],le[2]=Z*O[8+Te]-Y*O[24+Te]+q*O[40+Te]+G*O[56+Te],le[3]=q*O[8+Te]-Z*O[24+Te]+G*O[40+Te]-Y*O[56+Te],pe[0]=B*(O[Te]+O[32+Te]),pe[3]=B*(O[Te]-O[32+Te]),pe[1]=ne[0]+ne[3],pe[2]=ne[1]-ne[2],xe[0]=pe[0]+pe[1],xe[1]=pe[3]+pe[2],xe[2]=pe[3]-pe[2],xe[3]=pe[0]-pe[1],O[0+Te]=xe[0]+le[0],O[8+Te]=xe[1]+le[1],O[16+Te]=xe[2]+le[2],O[24+Te]=xe[3]+le[3],O[32+Te]=xe[3]-le[3],O[40+Te]=xe[2]-le[2],O[48+Te]=xe[1]-le[1],O[56+Te]=xe[0]-le[0]}function Je(O){for(let B=0;B<64;++B){const Y=O[0][B],I=O[1][B],G=O[2][B];O[0][B]=Y+1.5747*G,O[1][B]=Y-.1873*I-.4682*G,O[2][B]=Y+1.8556*I}}function ht(O,B,Y){for(let I=0;I<64;++I)B[Y+I]=H3.toHalfFloat(k(O[I]))}function k(O){return O<=1?Math.sign(O)*Math.pow(Math.abs(O),2.2):Math.sign(O)*Math.pow(N,Math.abs(O)-1)}function P(O){return new DataView(O.array.buffer,O.offset.value,O.size)}function he(O){const B=O.viewer.buffer.slice(O.offset.value,O.offset.value+O.size),Y=new Uint8Array(V(B)),I=new Uint8Array(Y.length);return Qe(Y),Ee(Y,I),new DataView(I.buffer)}function be(O){const B=O.array.slice(O.offset.value,O.offset.value+O.size),Y=mx(B),I=new Uint8Array(Y.length);return Qe(Y),Ee(Y,I),new DataView(I.buffer)}function Ie(O){const B=O.viewer,Y={value:O.offset.value},I=new Uint16Array(O.columns*O.lines*(O.inputChannels.length*O.type)),G=new Uint8Array(8192);let Z=0;const F=new Array(O.inputChannels.length);for(let ze=0,Be=O.inputChannels.length;ze=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(q<=ne)for(let ze=0;ze0;){const Be=je(B.buffer,Y),qe=me(B,Y),ut=qe>>2&3,At=(qe>>4)-1,Rt=new Int8Array([At])[0],mt=me(B,Y);Z.push({name:Be,index:Rt,type:mt,compression:ut}),F-=Be.length+3}const q=Sa.channels,ne=new Array(O.inputChannels.length);for(let Be=0;Be=0&&(le.idx[At.index]=Be),qe.offset=Be)}}let pe,xe,Te;if(G.acCompressedSize>0)switch(G.acCompression){case 0:pe=new Uint16Array(G.totalAcUncompressedCount),wt(O.array,B,Y,G.acCompressedSize,pe,G.totalAcUncompressedCount);break;case 1:const Be=O.array.slice(Y.value,Y.value+G.totalAcUncompressedCount),qe=mx(Be);pe=new Uint16Array(qe.buffer),Y.value+=G.totalAcUncompressedCount;break}if(G.dcCompressedSize>0){const Be={array:O.array,offset:Y,size:G.dcCompressedSize};xe=new Uint16Array(be(Be).buffer),Y.value+=G.dcCompressedSize}if(G.rleRawSize>0){const Be=O.array.slice(Y.value,Y.value+G.rleCompressedSize),qe=mx(Be);Te=V(qe.buffer),Y.value+=G.rleCompressedSize}let Ce=0;const ze=new Array(ne.length);for(let Be=0;Be>10,Y=O&1023;return(O>>15?-1:1)*(B?B===31?Y?NaN:1/0:Math.pow(2,B-15)*(1+Y/1024):6103515625e-14*(Y/1024))}function We(O,B){const Y=O.getUint16(B.value,!0);return B.value+=2,Y}function Ge(O,B){return ge(We(O,B))}function Re(O,B,Y,I){const G=Y.value,Z=[];for(;Y.value>4]}}function Po(O,B){const Y=j(O,B),I=j(O,B);return[Y,I]}function ro(O,B){const Y=j(O,B),I=j(O,B),G=j(O,B);return[Y,I,G]}function ao(O,B,Y,I,G){if(I==="string"||I==="stringvector"||I==="iccProfile")return Tt(B,Y,G);if(I==="chlist")return Re(O,B,Y,G);if(I==="chromaticities")return at(O,Y);if(I==="compression")return Et(O,Y);if(I==="box2i")return Gt(O,Y);if(I==="envmap")return mi(O,Y);if(I==="tiledesc")return gi(O,Y);if(I==="lineOrder")return kt(O,Y);if(I==="float")return j(O,Y);if(I==="v2f")return Po(O,Y);if(I==="v3f")return ro(O,Y);if(I==="int")return He(O,Y);if(I==="rational")return vt(O,Y);if(I==="timecode")return Ue(O,Y);if(I==="preview")return Y.value+=G,"skipped";Y.value+=G}function Li(O,B){const Y=Math.log2(O);return B=="ROUND_DOWN"?Math.floor(Y):Math.ceil(Y)}function so(O,B,Y){let I=0;switch(O.levelMode){case"ONE_LEVEL":I=1;break;case"MIPMAP_LEVELS":I=Li(Math.max(B,Y),O.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return I}function Er(O,B,Y,I){const G=new Array(O);for(let Z=0;ZO.width?O.width-F:O.blockWidth,O.lines=q+O.blockHeight>O.height?O.height-q:O.blockHeight;const ne=O.columns*O.totalBytes,pe=O.sizeO.height?O.height-G:O.blockHeight;const Z=O.columns*O.totalBytes,q=O.size=O.height)continue;const xe=ne*Z,Te=(O.height-1-pe)*O.outLineWidth;for(let Ce=0;CeTe:F.scanOrder=Te=>F.height-1-Te,O.spec.singleTile){F.blockHeight=O.tiles.ySize,F.blockWidth=O.tiles.xSize;const Te=so(O.tiles,F.width,F.height),Ce=Er(Te,F.width,O.tiles.xSize,O.tiles.roundingMode),ze=Er(Te,F.height,O.tiles.ySize,O.tiles.roundingMode);F.tileCount=Ce[0]*ze[0];for(let Be=0;Be{Wy(s instanceof ArrayBuffer);try{t(s)}catch(o){r!=null?r(o):console.error(o),this.manager.itemError(e)}},i,r)}};function Kz(n){var e,t;return n instanceof uT?n.getContext().getExtension("OES_texture_float_linear")!=null:((t=(e=n.backend).hasFeature)==null?void 0:t.call(e,"float32-filterable"))??!1}const cae=128,uae=128,hae=64,dae="9627216cc50057994c98a2118f3c4a23765d43b9",Jz=`https://media.githubusercontent.com/media/takram-design-engineering/three-geospatial/${dae}/packages/core/assets/stbn.bin`,fae="This is not an object",pae="This is not a Float16Array object",WI="This constructor is not a subclass of Float16Array",$z="The constructor property value is not an object",mae="Species constructor didn't return TypedArray object",gae="Derived constructor created TypedArray object which was too small length",sg="Attempting to access detached ArrayBuffer",gA="Cannot convert undefined or null to object",vA="Cannot mix BigInt and other types, use explicit conversions",XI="@@iterator property is not callable",qI="Reduce of empty array with no initial value",vae="The comparison function must be either a function or undefined",nM="Offset is out of bounds";function ti(n){return(e,...t)=>ua(n,e,t)}function em(n,e){return ti(Ip(n,e).get)}const{apply:ua,construct:N0,defineProperty:_ae,get:iM,getOwnPropertyDescriptor:Ip,getPrototypeOf:dv,has:_A,ownKeys:eB,set:YI,setPrototypeOf:tB}=Reflect,xae=Proxy,{EPSILON:yae,MAX_SAFE_INTEGER:jI,isFinite:nB,isNaN:Up}=Number,{iterator:Lo,species:Sae,toStringTag:VR,for:Tae}=Symbol,Pp=Object,{create:fT,defineProperty:fv,freeze:Eae,is:ZI}=Pp,xA=Pp.prototype,bae=xA.__lookupGetter__?ti(xA.__lookupGetter__):(n,e)=>{if(n==null)throw hi(gA);let t=Pp(n);do{const i=Ip(t,e);if(i!==void 0)return Tl(i,"get")?i.get:void 0}while((t=dv(t))!==null)},Tl=Pp.hasOwn||ti(xA.hasOwnProperty),iB=Array,rB=iB.isArray,pT=iB.prototype,Mae=ti(pT.join),Aae=ti(pT.push),wae=ti(pT.toLocaleString),GR=pT[Lo],Rae=ti(GR),{abs:Cae,trunc:aB}=Math,mT=ArrayBuffer,Dae=mT.isView,sB=mT.prototype,Nae=ti(sB.slice),Oae=em(sB,"byteLength"),yA=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:null,Lae=yA&&em(yA.prototype,"byteLength"),kR=dv(Uint8Array),Iae=kR.from,dr=kR.prototype,Uae=dr[Lo],Pae=ti(dr.keys),zae=ti(dr.values),Bae=ti(dr.entries),Fae=ti(dr.set),QI=ti(dr.reverse),Hae=ti(dr.fill),Vae=ti(dr.copyWithin),KI=ti(dr.sort),i0=ti(dr.slice),Gae=ti(dr.subarray),sr=em(dr,"buffer"),Zu=em(dr,"byteOffset"),Mn=em(dr,"length"),oB=em(dr,VR),kae=Uint8Array,za=Uint16Array,JI=(...n)=>ua(Iae,za,n),WR=Uint32Array,Wae=Float32Array,Wh=dv([][Lo]()),gT=ti(Wh.next),Xae=ti(function*(){}().next),qae=dv(Wh),Yae=DataView.prototype,jae=ti(Yae.getUint16),hi=TypeError,rM=RangeError,lB=WeakSet,cB=lB.prototype,Zae=ti(cB.add),Qae=ti(cB.has),vT=WeakMap,XR=vT.prototype,Xy=ti(XR.get),Kae=ti(XR.has),qR=ti(XR.set),uB=new vT,Jae=fT(null,{next:{value:function(){const n=Xy(uB,this);return gT(n)}},[Lo]:{value:function(){return this}}});function O0(n){if(n[Lo]===GR&&Wh.next===gT)return n;const e=fT(Jae);return qR(uB,e,Rae(n)),e}const hB=new vT,dB=fT(qae,{next:{value:function(){const n=Xy(hB,this);return Xae(n)},writable:!0,configurable:!0}});for(const n of eB(Wh))n!=="next"&&fv(dB,n,Ip(Wh,n));function $I(n){const e=fT(dB);return qR(hB,e,n),e}function qy(n){return n!==null&&typeof n=="object"||typeof n=="function"}function e5(n){return n!==null&&typeof n=="object"}function Yy(n){return oB(n)!==void 0}function SA(n){const e=oB(n);return e==="BigInt64Array"||e==="BigUint64Array"}function $ae(n){try{return rB(n)?!1:(Oae(n),!0)}catch{return!1}}function fB(n){if(yA===null)return!1;try{return Lae(n),!0}catch{return!1}}function ese(n){return $ae(n)||fB(n)}function t5(n){return rB(n)?n[Lo]===GR&&Wh.next===gT:!1}function tse(n){return Yy(n)?n[Lo]===Uae&&Wh.next===gT:!1}function gx(n){if(typeof n!="string")return!1;const e=+n;return n!==e+""||!nB(e)?!1:e===aB(e)}const jy=Tae("__Float16Array__");function nse(n){if(!e5(n))return!1;const e=dv(n);if(!e5(e))return!1;const t=e.constructor;if(t===void 0)return!1;if(!qy(t))throw hi($z);return _A(t,jy)}const TA=1/yae;function ise(n){return n+TA-TA}const pB=6103515625e-14,rse=65504,mB=.0009765625,n5=mB*pB,ase=mB*TA;function sse(n){const e=+n;if(!nB(e)||e===0)return e;const t=e>0?1:-1,i=Cae(e);if(irse||Up(a)?t*(1/0):t*a}const gB=new mT(4),vB=new Wae(gB),_B=new WR(gB),Gs=new za(512),ks=new kae(512);for(let n=0;n<256;++n){const e=n-127;e<-24?(Gs[n]=0,Gs[n|256]=32768,ks[n]=24,ks[n|256]=24):e<-14?(Gs[n]=1024>>-e-14,Gs[n|256]=1024>>-e-14|32768,ks[n]=-e-1,ks[n|256]=-e-1):e<=15?(Gs[n]=e+15<<10,Gs[n|256]=e+15<<10|32768,ks[n]=13,ks[n|256]=13):e<128?(Gs[n]=31744,Gs[n|256]=64512,ks[n]=24,ks[n|256]=24):(Gs[n]=31744,Gs[n|256]=64512,ks[n]=13,ks[n|256]=13)}function So(n){vB[0]=sse(n);const e=_B[0],t=e>>23&511;return Gs[t]+((e&8388607)>>ks[t])}const YR=new WR(2048);for(let n=1;n<1024;++n){let e=n<<13,t=0;for(;!(e&8388608);)e<<=1,t-=8388608;e&=-8388609,t+=947912704,YR[n]=e|t}for(let n=1024;n<2048;++n)YR[n]=939524096+(n-1024<<13);const tm=new WR(64);for(let n=1;n<31;++n)tm[n]=n<<23;tm[31]=1199570944;tm[32]=2147483648;for(let n=33;n<63;++n)tm[n]=2147483648+(n-32<<23);tm[63]=3347054592;const xB=new za(64);for(let n=1;n<64;++n)n!==32&&(xB[n]=1024);function Cn(n){const e=n>>10;return _B[0]=YR[xB[e]+(n&1023)]+tm[e],vB[0]}function ml(n){const e=+n;return Up(e)||e===0?0:aB(e)}function aM(n){const e=ml(n);return e<0?0:ee)return 1;if(n===0&&e===0){const r=ZI(n,0),a=ZI(e,0);if(!r&&a)return-1;if(r&&!a)return 1}return 0}const jR=2,Zy=new vT;function kf(n){return Kae(Zy,n)||!Dae(n)&&nse(n)}function bn(n){if(!kf(n))throw hi(pae)}function _x(n,e){const t=kf(n),i=Yy(n);if(!t&&!i)throw hi(mae);if(typeof e=="number"){let r;if(t){const a=$t(n);r=Mn(a)}else r=Mn(n);if(r=0?r:i+r;if(!(a<0||a>=i))return Cn(t[a])}with(e,t){bn(this);const i=$t(this),r=Mn(i),a=ml(e),s=a>=0?a:r+a,o=+t;if(s<0||s>=r)throw rM(nM);const l=new za(sr(i),Zu(i),Mn(i)),u=new or(sr(i0(l))),d=$t(u);return d[s]=So(o),u}map(e,...t){bn(this);const i=$t(this),r=Mn(i),a=t[0],s=vx(i,or);if(s===or){const l=new or(r),u=$t(l);for(let d=0;d=0;--o)a=e(a,Cn(i[o]),o,this);return a}forEach(e,...t){bn(this);const i=$t(this),r=Mn(i),a=t[0];for(let s=0;s=0;--s){const o=Cn(i[s]);if(ua(e,a,[o,s,this]))return o}}findLastIndex(e,...t){bn(this);const i=$t(this),r=Mn(i),a=t[0];for(let s=r-1;s>=0;--s){const o=Cn(i[s]);if(ua(e,a,[o,s,this]))return s}return-1}every(e,...t){bn(this);const i=$t(this),r=Mn(i),a=t[0];for(let s=0;sa)throw rM(nM);for(let l=0;li(Cn(r),Cn(a))),this}toSorted(e){bn(this);const t=$t(this);if(e!==void 0&&typeof e!="function")throw new hi(vae);const i=e!==void 0?e:i5,r=new za(sr(t),Zu(t),Mn(t)),a=new or(sr(i0(r))),s=$t(a);return KI(s,(o,l)=>i(Cn(o),Cn(l))),a}slice(e,t){bn(this);const i=$t(this),r=vx(i,or);if(r===or){const v=new za(sr(i),Zu(i),Mn(i));return new or(sr(i0(v,e,t)))}const a=Mn(i),s=ml(e),o=t===void 0?a:ml(t);let l;s===-1/0?l=0:s<0?l=a+s>0?a+s:0:l=a0?a+o:0:u=a0?u-l:0,f=new r(d);if(_x(f,d),d===0)return f;const p=sr(i);if(og(p))throw hi(sg);let m=0;for(;l=1?ml(t[0]):r-1;if(a===-1/0)return-1;a>=0?a=a=0;--s)if(Tl(i,s)&&Cn(i[s])===e)return s;return-1}includes(e,...t){bn(this);const i=$t(this),r=Mn(i);let a=ml(t[0]);if(a===1/0)return!1;a<0&&(a+=r,a<0&&(a=0));const s=Up(e);for(let o=a;o{try{t(this.parser(s))}catch(o){r!=null?r(o):console.error(o),this.manager.itemError(e)}},i,r)}};function use(n){const e=n instanceof Int8Array?CS:n instanceof Uint8Array||n instanceof Uint8ClampedArray?Ni:n instanceof Int16Array?DS:n instanceof Uint16Array?Uh:n instanceof Int32Array?$g:n instanceof Uint32Array?to:n instanceof Vl?Jn:n instanceof Float32Array||n instanceof Float64Array?fi:null;return Wy(e!=null),e}let ch=class extends wi{constructor(e,t,i={},r){super(r),this.textureClass=e,this.parser=t,this.options={format:ai,minFilter:Bt,magFilter:Bt,...i}}load(e,t,i,r){const a=new this.textureClass,s=new cse(this.parser,this.manager);return s.setRequestHeader(this.requestHeader),s.setPath(this.path),s.setWithCredentials(this.withCredentials),s.load(e,o=>{a.image.data=o instanceof Vl?new Uint16Array(o.buffer):o;const{width:l,height:u,depth:d,...f}=this.options;l!=null&&(a.image.width=l),u!=null&&(a.image.height=u),"depth"in a.image&&d!=null&&(a.image.depth=d),a.type=use(o),Object.assign(a,f),a.needsUpdate=!0,t==null||t(a)},i,r),a}};const zg=lt.clamp;lt.euclideanModulo;lt.inverseLerp;const SB=lt.lerp,oh=lt.degToRad;lt.radToDeg;lt.isPowerOfTwo;lt.ceilPowerOfTwo;lt.floorPowerOfTwo;lt.normalize;function hse(n,e,t,i=0,r=1){return lt.mapLinear(n,e,t,i,r)}function dse(n){return Math.min(Math.max(n,0),1)}function gn(n){return(e,t)=>{e instanceof ei?Object.defineProperty(e,t,{enumerable:!0,get(){var i;return((i=this.defines)==null?void 0:i[n])!=null},set(i){var r;i!==this[t]&&(i?(this.defines??(this.defines={}),this.defines[n]="1"):(r=this.defines)==null||delete r[n],this.needsUpdate=!0)}}):Object.defineProperty(e,t,{enumerable:!0,get(){return this.defines.has(n)},set(i){i!==this[t]&&(i?this.defines.set(n,"1"):this.defines.delete(n),this.setChanged())}})}}function ad(n,{min:e=Number.MIN_SAFE_INTEGER,max:t=Number.MAX_SAFE_INTEGER}={}){return(i,r)=>{i instanceof ei?Object.defineProperty(i,r,{enumerable:!0,get(){var s;const a=(s=this.defines)==null?void 0:s[n];return a!=null?parseInt(a,10):0},set(a){const s=this[r];a!==s&&(this.defines??(this.defines={}),this.defines[n]=zg(a,e,t).toFixed(0),this.needsUpdate=!0)}}):Object.defineProperty(i,r,{enumerable:!0,get(){const a=this.defines.get(n);return a!=null?parseInt(a,10):0},set(a){const s=this[r];a!==s&&(this.defines.set(n,zg(a,e,t).toFixed(0)),this.setChanged())}})}}function ZR(n,{min:e=-1/0,max:t=1/0,precision:i=7}={}){return(r,a)=>{r instanceof ei?Object.defineProperty(r,a,{enumerable:!0,get(){var o;const s=(o=this.defines)==null?void 0:o[n];return s!=null?parseFloat(s):0},set(s){const o=this[a];s!==o&&(this.defines??(this.defines={}),this.defines[n]=zg(s,e,t).toFixed(i),this.needsUpdate=!0)}}):Object.defineProperty(r,a,{enumerable:!0,get(){const s=this.defines.get(n);return s!=null?parseFloat(s):0},set(s){const o=this[a];s!==o&&(this.defines.set(n,zg(s,e,t).toFixed(i)),this.setChanged())}})}}function TB(n,{validate:e}={}){return(t,i)=>{t instanceof ei?Object.defineProperty(t,i,{enumerable:!0,get(){var r;return((r=this.defines)==null?void 0:r[n])??""},set(r){if(r!==this[i]){if((e==null?void 0:e(r))===!1){console.error(`Expression validation failed: ${r}`);return}this.defines??(this.defines={}),this.defines[n]=r,this.needsUpdate=!0}}}):Object.defineProperty(t,i,{enumerable:!0,get(){return this.defines.get(n)??""},set(r){if(r!==this[i]){if((e==null?void 0:e(r))===!1){console.error(`Expression validation failed: ${r}`);return}this.defines.set(n,r),this.setChanged()}}})}}function a5(n,...e){const t={};for(let i=0;ir[s],set:o=>{r[s]=o}}}return Object.defineProperties(n,t),n}function s5(n,e,t){const i={};for(const r of t)i[r]={enumerable:!0,get:()=>e.uniforms[r].value,set:a=>{e.uniforms[r].value=a}};return Object.defineProperties(n,i),n}class sM extends wi{constructor(e={},t){super(t),this.options=e}load(e,t,i,r){const{width:a,height:s,depth:o}=this.options,l=new ws(null,a,s,o),u=new Qz(this.manager);return u.setRequestHeader(this.requestHeader),u.setPath(this.path),u.setWithCredentials(this.withCredentials),u.load(e,d=>{const{image:f}=d;l.image={data:f.data,width:a??f.width,height:s??f.height,depth:o??Math.sqrt(f.height)},l.type=d.type,l.format=d.format,l.colorSpace=d.colorSpace,l.needsUpdate=!0;try{t==null||t(l)}catch(p){r!=null?r(p):console.error(p),this.manager.itemError(e)}},i,r),l}}class o5 extends wi{constructor(e={},t){super(t),this.options=e}load(e,t,i,r){const{width:a,height:s}=this.options,o=new Ur(null,a,s),l=new Qz(this.manager);return l.setRequestHeader(this.requestHeader),l.setPath(this.path),l.setWithCredentials(this.withCredentials),l.load(e,u=>{const{image:d}=u;o.image={data:d.data,width:a??d.width,height:s??d.height},o.type=u.type,o.format=u.format,o.colorSpace=u.colorSpace,o.needsUpdate=!0;try{t==null||t(o)}catch(f){r!=null?r(f):console.error(f),this.manager.itemError(e)}},i,r),o}}const oM=1e-6,xx=new D,yx=new D,sl=new D,r0=new D,lM=new D,fse=new D,pse=new Me,mse=new ft,gse=new Pr;let vse=class EB{constructor(e=0,t=0,i=0,r=0){this.distance=e,this.heading=t,this.pitch=i,this.roll=r}get distance(){return this._distance}set distance(e){this._distance=Math.max(e,oM)}get pitch(){return this._pitch}set pitch(e){this._pitch=zg(e,-Math.PI/2+oM,Math.PI/2-oM)}set(e,t,i,r){return this.distance=e,this.heading=t,this.pitch=i,r!=null&&(this.roll=r),this}clone(){return new EB(this.distance,this.heading,this.pitch,this.roll)}copy(e){return this.distance=e.distance,this.heading=e.heading,this.pitch=e.pitch,this.roll=e.roll,this}equals(e){return e.distance===this.distance&&e.heading===this.heading&&e.pitch===this.pitch&&e.roll===this.roll}decompose(e,t,i,r,a=kh.WGS84){a.getEastNorthUpVectors(e,xx,yx,sl),r==null||r.copy(sl);const s=r0.copy(xx).multiplyScalar(Math.cos(this.heading)).add(lM.copy(yx).multiplyScalar(Math.sin(this.heading))).multiplyScalar(Math.cos(this.pitch)).add(lM.copy(sl).multiplyScalar(Math.sin(this.pitch))).normalize().multiplyScalar(this.distance);if(t.copy(e).sub(s),this.roll!==0){const o=r0.copy(e).sub(t).normalize();sl.applyQuaternion(mse.setFromAxisAngle(o,this.roll))}i.setFromRotationMatrix(pse.lookAt(t,e,sl))}setFromCamera(e,t=kh.WGS84){const i=r0.setFromMatrixPosition(e.matrixWorld),r=lM.set(0,0,.5).unproject(e).sub(i).normalize(),a=t.getIntersection(gse.set(i,r));if(a==null)return;this.distance=i.distanceTo(a),t.getEastNorthUpVectors(a,xx,yx,sl),this.heading=Math.atan2(yx.dot(r),xx.dot(r)),this.pitch=Math.asin(sl.dot(r));const s=r0.copy(e.up).applyQuaternion(e.quaternion),o=fse.copy(r).multiplyScalar(-s.dot(r)).add(s).normalize(),l=r0.copy(r).multiplyScalar(-sl.dot(r)).add(sl).normalize(),u=l.dot(o),d=r.dot(l.cross(o));return this.roll=Math.atan2(d,u),this}};const _se=/^[ \t]*#include +"([\w\d./]+)"/gm;function Wr(n,e){return n.replace(_se,(t,i)=>{const r=i.split("/").reduce((a,s)=>typeof a!="string"&&a!=null?a[s]:void 0,e);if(typeof r!="string")throw new Error(`Could not find include for ${i}.`);return Wr(r,e)})}let Sx;function xse(){if(Sx!=null)return Sx;const n=new Uint32Array([268435456]);return Sx=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)[0]===0,Sx}function yse(n,e,t,i=!0){if(i===xse())return new e(n);const r=Object.assign(new DataView(n),{getFloat16(s,o){return lse(this,s,o)}}),a=new e(r.byteLength/e.BYTES_PER_ELEMENT);for(let s=0,o=0;snew Uint8Array(n),a0=(n,e)=>yse(n,Vl,"getFloat16",e);class MB extends ch{constructor(e){super(ws,bB,{format:Qs,minFilter:Yn,magFilter:Yn,wrapS:Ir,wrapT:Ir,wrapR:Ir,width:cae,height:uae,depth:hae},e)}}const Sse=/#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*i)\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Tse(n,e,t,i){let r="";for(let a=parseInt(e,10);a= interval.x && depth < interval.y) { + return UNROLLED_LOOP_INDEX; + } + #endif // UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT + } + #pragma unroll_loop_end + return SHADOW_CASCADE_COUNT - 1; +} + +int getFadedCascadeIndex( + const mat4 viewMatrix, + const vec3 worldPosition, + const vec2 intervals[SHADOW_CASCADE_COUNT], + const float near, + const float far, + const float jitter +) { + vec4 viewPosition = viewMatrix * vec4(worldPosition, 1.0); + float depth = viewZToOrthographicDepth(viewPosition.z, near, far); + + vec2 interval; + float intervalCenter; + float closestEdge; + float margin; + int nextIndex = -1; + int prevIndex = -1; + float alpha; + + #pragma unroll_loop_start + for (int i = 0; i < 4; ++i) { + #if UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT + interval = intervals[i]; + intervalCenter = (interval.x + interval.y) * 0.5; + closestEdge = depth < intervalCenter ? interval.x : interval.y; + margin = closestEdge * closestEdge * 0.5; + interval += margin * vec2(-0.5, 0.5); + + #if UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT - 1 + if (depth >= interval.x && depth < interval.y) { + prevIndex = nextIndex; + nextIndex = UNROLLED_LOOP_INDEX; + alpha = saturate(min(depth - interval.x, interval.y - depth) / margin); + } + #else // UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT - 1 + // Don't fade out the last cascade. + if (depth >= interval.x) { + prevIndex = nextIndex; + nextIndex = UNROLLED_LOOP_INDEX; + alpha = saturate((depth - interval.x) / margin); + } + #endif // UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT - 1 + #endif // UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT + } + #pragma unroll_loop_end + + return jitter <= alpha + ? nextIndex + : prevIndex; +} +`,bse=`// cSpell:words logdepthbuf + +float reverseLogDepth(const float depth, const float near, const float far) { + #if defined(USE_LOGDEPTHBUF) || defined(USE_LOGARITHMIC_DEPTH_BUFFER) + float d = pow(2.0, depth * log2(far + 1.0)) - 1.0; + float a = far / (far - near); + float b = far * near / (near - far); + return a + b / d; + #else // defined(USE_LOGARITHMIC_DEPTH_BUFFER) || defined(USE_LOGARITHMIC_DEPTH_BUFFER) + return depth; + #endif // defined(USE_LOGARITHMIC_DEPTH_BUFFER) || defined(USE_LOGARITHMIC_DEPTH_BUFFER) +} + +float linearizeDepth(const float depth, const float near, const float far) { + float ndc = depth * 2.0 - 1.0; + return 2.0 * near * far / (far + near - ndc * (far - near)); +} +`,Mse=`float checker(const vec2 uv, const vec2 repeats) { + vec2 c = floor(repeats * uv); + float result = mod(c.x + c.y, 2.0); + return sign(result); +} + +float checker(const vec2 uv, const float repeats) { + return checker(uv, vec2(repeats)); +} +`,Ase=`// Reference: https://advances.realtimerendering.com/s2014/index.html#_NEXT_GENERATION_POST + +float interleavedGradientNoise(const vec2 coord) { + const vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189); + return fract(magic.z * fract(dot(coord, magic.xy))); +} +`,wse=`#if !defined(saturate) +#define saturate(a) clamp(a, 0.0, 1.0) +#endif // !defined(saturate) + +float remap(const float x, const float min1, const float max1, const float min2, const float max2) { + return min2 + (x - min1) / (max1 - min1) * (max2 - min2); +} + +vec2 remap(const vec2 x, const vec2 min1, const vec2 max1, const vec2 min2, const vec2 max2) { + return min2 + (x - min1) / (max1 - min1) * (max2 - min2); +} + +vec3 remap(const vec3 x, const vec3 min1, const vec3 max1, const vec3 min2, const vec3 max2) { + return min2 + (x - min1) / (max1 - min1) * (max2 - min2); +} + +vec4 remap(const vec4 x, const vec4 min1, const vec4 max1, const vec4 min2, const vec4 max2) { + return min2 + (x - min1) / (max1 - min1) * (max2 - min2); +} + +float remapClamped( + const float x, + const float min1, + const float max1, + const float min2, + const float max2 +) { + return clamp(min2 + (x - min1) / (max1 - min1) * (max2 - min2), min2, max2); +} + +vec2 remapClamped( + const vec2 x, + const vec2 min1, + const vec2 max1, + const vec2 min2, + const vec2 max2 +) { + return clamp(min2 + (x - min1) / (max1 - min1) * (max2 - min2), min2, max2); +} + +vec3 remapClamped( + const vec3 x, + const vec3 min1, + const vec3 max1, + const vec3 min2, + const vec3 max2 +) { + return clamp(min2 + (x - min1) / (max1 - min1) * (max2 - min2), min2, max2); +} + +vec4 remapClamped( + const vec4 x, + const vec4 min1, + const vec4 max1, + const vec4 min2, + const vec4 max2 +) { + return clamp(min2 + (x - min1) / (max1 - min1) * (max2 - min2), min2, max2); +} + +// Implicitly remap to 0 and 1 +float remap(const float x, const float min1, const float max1) { + return (x - min1) / (max1 - min1); +} + +vec2 remap(const vec2 x, const vec2 min1, const vec2 max1) { + return (x - min1) / (max1 - min1); +} + +vec3 remap(const vec3 x, const vec3 min1, const vec3 max1) { + return (x - min1) / (max1 - min1); +} + +vec4 remap(const vec4 x, const vec4 min1, const vec4 max1) { + return (x - min1) / (max1 - min1); +} + +float remapClamped(const float x, const float min1, const float max1) { + return saturate((x - min1) / (max1 - min1)); +} + +vec2 remapClamped(const vec2 x, const vec2 min1, const vec2 max1) { + return saturate((x - min1) / (max1 - min1)); +} + +vec3 remapClamped(const vec3 x, const vec3 min1, const vec3 max1) { + return saturate((x - min1) / (max1 - min1)); +} + +vec4 remapClamped(const vec4 x, const vec4 min1, const vec4 max1) { + return saturate((x - min1) / (max1 - min1)); +} +`,Rse=`// Reference: https://jcgt.org/published/0003/02/01/paper.pdf + +vec2 signNotZero(vec2 v) { + return vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0); +} + +vec2 packNormalToVec2(vec3 v) { + vec2 p = v.xy * (1.0 / (abs(v.x) + abs(v.y) + abs(v.z))); + return v.z <= 0.0 + ? (1.0 - abs(p.yx)) * signNotZero(p) + : p; +} + +vec3 unpackVec2ToNormal(vec2 e) { + vec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y)); + if (v.z < 0.0) { + v.xy = (1.0 - abs(v.yx)) * signNotZero(v.xy); + } + return normalize(v); +} +`,Cse=`float raySphereFirstIntersection( + const vec3 origin, + const vec3 direction, + const vec3 center, + const float radius +) { + vec3 a = origin - center; + float b = 2.0 * dot(direction, a); + float c = dot(a, a) - radius * radius; + float discriminant = b * b - 4.0 * c; + return discriminant < 0.0 + ? -1.0 + : (-b - sqrt(discriminant)) * 0.5; +} + +float raySphereFirstIntersection(const vec3 origin, const vec3 direction, const float radius) { + return raySphereFirstIntersection(origin, direction, vec3(0.0), radius); +} + +vec4 raySphereFirstIntersection( + const vec3 origin, + const vec3 direction, + const vec3 center, + const vec4 radius +) { + vec3 a = origin - center; + float b = 2.0 * dot(direction, a); + vec4 c = dot(a, a) - radius * radius; + vec4 discriminant = b * b - 4.0 * c; + vec4 mask = step(discriminant, vec4(0.0)); + return mix((-b - sqrt(max(vec4(0.0), discriminant))) * 0.5, vec4(-1.0), mask); +} + +vec4 raySphereFirstIntersection(const vec3 origin, const vec3 direction, const vec4 radius) { + return raySphereFirstIntersection(origin, direction, vec3(0.0), radius); +} + +float raySphereSecondIntersection( + const vec3 origin, + const vec3 direction, + const vec3 center, + const float radius +) { + vec3 a = origin - center; + float b = 2.0 * dot(direction, a); + float c = dot(a, a) - radius * radius; + float discriminant = b * b - 4.0 * c; + return discriminant < 0.0 + ? -1.0 + : (-b + sqrt(discriminant)) * 0.5; +} + +float raySphereSecondIntersection(const vec3 origin, const vec3 direction, const float radius) { + return raySphereSecondIntersection(origin, direction, vec3(0.0), radius); +} + +vec4 raySphereSecondIntersection( + const vec3 origin, + const vec3 direction, + const vec3 center, + const vec4 radius +) { + vec3 a = origin - center; + float b = 2.0 * dot(direction, a); + vec4 c = dot(a, a) - radius * radius; + vec4 discriminant = b * b - 4.0 * c; + vec4 mask = step(discriminant, vec4(0.0)); + return mix((-b + sqrt(max(vec4(0.0), discriminant))) * 0.5, vec4(-1.0), mask); +} + +vec4 raySphereSecondIntersection(const vec3 origin, const vec3 direction, const vec4 radius) { + return raySphereSecondIntersection(origin, direction, vec3(0.0), radius); +} + +void raySphereIntersections( + const vec3 origin, + const vec3 direction, + const vec3 center, + const float radius, + out float intersection1, + out float intersection2 +) { + vec3 a = origin - center; + float b = 2.0 * dot(direction, a); + float c = dot(a, a) - radius * radius; + float discriminant = b * b - 4.0 * c; + if (discriminant < 0.0) { + intersection1 = -1.0; + intersection2 = -1.0; + return; + } else { + float Q = sqrt(discriminant); + intersection1 = (-b - Q) * 0.5; + intersection2 = (-b + Q) * 0.5; + } +} + +void raySphereIntersections( + const vec3 origin, + const vec3 direction, + const float radius, + out float intersection1, + out float intersection2 +) { + raySphereIntersections(origin, direction, vec3(0.0), radius, intersection1, intersection2); +} + +void raySphereIntersections( + const vec3 origin, + const vec3 direction, + const vec3 center, + const vec4 radius, + out vec4 intersection1, + out vec4 intersection2 +) { + vec3 a = origin - center; + float b = 2.0 * dot(direction, a); + vec4 c = dot(a, a) - radius * radius; + vec4 discriminant = b * b - 4.0 * c; + vec4 mask = step(discriminant, vec4(0.0)); + vec4 Q = sqrt(max(vec4(0.0), discriminant)); + intersection1 = mix((-b - Q) * 0.5, vec4(-1.0), mask); + intersection2 = mix((-b + Q) * 0.5, vec4(-1.0), mask); +} + +void raySphereIntersections( + const vec3 origin, + const vec3 direction, + const vec4 radius, + out vec4 intersection1, + out vec4 intersection2 +) { + raySphereIntersections(origin, direction, vec3(0.0), radius, intersection1, intersection2); +} +`,Dse=`vec3 screenToView( + const vec2 uv, + const float depth, + const float viewZ, + const mat4 projectionMatrix, + const mat4 inverseProjectionMatrix +) { + vec4 clip = vec4(vec3(uv, depth) * 2.0 - 1.0, 1.0); + float clipW = projectionMatrix[2][3] * viewZ + projectionMatrix[3][3]; + clip *= clipW; + return (inverseProjectionMatrix * clip).xyz; +} +`,Nse=`// A fifth-order polynomial approximation of Turbo color map. +// See: https://observablehq.com/@mbostock/turbo +// prettier-ignore +vec3 turbo(const float x) { + float r = 0.1357 + x * (4.5974 - x * (42.3277 - x * (130.5887 - x * (150.5666 - x * 58.1375)))); + float g = 0.0914 + x * (2.1856 + x * (4.8052 - x * (14.0195 - x * (4.2109 + x * 2.7747)))); + float b = 0.1067 + x * (12.5925 - x * (60.1097 - x * (109.0745 - x * (88.5066 - x * 26.8183)))); + return vec3(r, g, b); +} +`,Ose=`// Reference: https://www.gamedev.net/tutorials/programming/graphics/contact-hardening-soft-shadows-made-fast-r4906/ + +vec2 vogelDisk(const int index, const int sampleCount, const float phi) { + const float goldenAngle = 2.39996322972865332; + float r = sqrt(float(index) + 0.5) / sqrt(float(sampleCount)); + float theta = float(index) * goldenAngle + phi; + return r * vec2(cos(theta), sin(theta)); +} +`,AB=Ese,wB=bse,Lse=Mse,RB=Ase,QR=wse,Ise=Rse,_T=Cse,Use=Dse,CB=Nse,DB=Ose,nm=64,im=16,xT=32,yT=128,ST=32,TT=8,Ah=TT*ST,wh=yT,Rh=xT,rm=256,am=64,Ky=1/1e3,Pse=new D;function KR(n,e,t,i){const r=t.projectOnSurface(n,Pse);return r!=null?t.getOsculatingSphereCenter(r,e,i).negate():i.setScalar(0)}var zse="Invariant failed";function Bse(n,e){if(!n)throw new Error(zse)}const l5=typeof window<"u"&&window.requestIdleCallback!=null?window.requestIdleCallback:function(n,e={}){const t=e.timeout??1,i=performance.now();return setTimeout(function(){n({get didTimeout(){return e.timeout!=null?!1:performance.now()-i-1>t},timeRemaining:function(){return Math.max(0,1+(performance.now()-i))}})},1)},To=`// Based on: https://github.com/ebruneton/precomputed_atmospheric_scattering/blob/master/atmosphere/functions.glsl + +/** + * Copyright (c) 2017 Eric Bruneton + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + * + * Precomputed Atmospheric Scattering + * Copyright (c) 2008 INRIA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +Number ClampCosine(const Number mu) { + return clamp(mu, Number(-1.0), Number(1.0)); +} + +Length ClampDistance(const Length d) { + return max(d, 0.0 * m); +} + +Length ClampRadius(const AtmosphereParameters atmosphere, const Length r) { + return clamp(r, atmosphere.bottom_radius, atmosphere.top_radius); +} + +Length SafeSqrt(const Area a) { + return sqrt(max(a, 0.0 * m2)); +} + +Length DistanceToTopAtmosphereBoundary(const AtmosphereParameters atmosphere, + const Length r, const Number mu) { + assert(r <= atmosphere.top_radius); + assert(mu >= -1.0 && mu <= 1.0); + Area discriminant = r * r * (mu * mu - 1.0) + + atmosphere.top_radius * atmosphere.top_radius; + return ClampDistance(-r * mu + SafeSqrt(discriminant)); +} + +Length DistanceToBottomAtmosphereBoundary(const AtmosphereParameters atmosphere, + const Length r, const Number mu) { + assert(r >= atmosphere.bottom_radius); + assert(mu >= -1.0 && mu <= 1.0); + Area discriminant = r * r * (mu * mu - 1.0) + + atmosphere.bottom_radius * atmosphere.bottom_radius; + return ClampDistance(-r * mu - SafeSqrt(discriminant)); +} + +bool RayIntersectsGround(const AtmosphereParameters atmosphere, + const Length r, const Number mu) { + assert(r >= atmosphere.bottom_radius); + assert(mu >= -1.0 && mu <= 1.0); + return mu < 0.0 && r * r * (mu * mu - 1.0) + + atmosphere.bottom_radius * atmosphere.bottom_radius >= 0.0 * m2; +} + +Number GetTextureCoordFromUnitRange(const Number x, const int texture_size) { + return 0.5 / Number(texture_size) + x * (1.0 - 1.0 / Number(texture_size)); +} + +vec2 GetTransmittanceTextureUvFromRMu(const AtmosphereParameters atmosphere, + const Length r, const Number mu) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu >= -1.0 && mu <= 1.0); + // Distance to top atmosphere boundary for a horizontal ray at ground level. + Length H = sqrt(atmosphere.top_radius * atmosphere.top_radius - + atmosphere.bottom_radius * atmosphere.bottom_radius); + // Distance to the horizon. + Length rho = + SafeSqrt(r * r - atmosphere.bottom_radius * atmosphere.bottom_radius); + // Distance to the top atmosphere boundary for the ray (r,mu), and its minimum + // and maximum values over all mu - obtained for (r,1) and (r,mu_horizon). + Length d = DistanceToTopAtmosphereBoundary(atmosphere, r, mu); + Length d_min = atmosphere.top_radius - r; + Length d_max = rho + H; + Number x_mu = (d - d_min) / (d_max - d_min); + Number x_r = rho / H; + return vec2(GetTextureCoordFromUnitRange(x_mu, TRANSMITTANCE_TEXTURE_WIDTH), + GetTextureCoordFromUnitRange(x_r, TRANSMITTANCE_TEXTURE_HEIGHT)); +} + +DimensionlessSpectrum GetTransmittanceToTopAtmosphereBoundary( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const Length r, const Number mu) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + vec2 uv = GetTransmittanceTextureUvFromRMu(atmosphere, r, mu); + // @shotamatsuda: Added for the precomputation stage in half-float precision. + #ifdef TRANSMITTANCE_PRECISION_LOG + // Manually interpolate the transmittance instead of the optical depth. + const vec2 size = vec2(TRANSMITTANCE_TEXTURE_WIDTH, TRANSMITTANCE_TEXTURE_HEIGHT); + const vec3 texel_size = vec3(1.0 / size, 0.0); + vec2 coord = (uv * size) - 0.5; + vec2 i = (floor(coord) + 0.5) * texel_size.xy; + vec2 f = fract(coord); + vec4 t1 = exp(-texture(transmittance_texture, i)); + vec4 t2 = exp(-texture(transmittance_texture, i + texel_size.xz)); + vec4 t3 = exp(-texture(transmittance_texture, i + texel_size.zy)); + vec4 t4 = exp(-texture(transmittance_texture, i + texel_size.xy)); + return DimensionlessSpectrum(mix(mix(t1, t2, f.x), mix(t3, t4, f.x), f.y)); + #else // TRANSMITTANCE_PRECISION_LOG + return DimensionlessSpectrum(texture(transmittance_texture, uv)); + #endif // TRANSMITTANCE_PRECISION_LOG +} + +DimensionlessSpectrum GetTransmittance( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const Length r, const Number mu, const Length d, + const bool ray_r_mu_intersects_ground) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu >= -1.0 && mu <= 1.0); + assert(d >= 0.0 * m); + + Length r_d = ClampRadius(atmosphere, sqrt(d * d + 2.0 * r * mu * d + r * r)); + Number mu_d = ClampCosine((r * mu + d) / r_d); + + if (ray_r_mu_intersects_ground) { + return min( + GetTransmittanceToTopAtmosphereBoundary( + atmosphere, transmittance_texture, r_d, -mu_d) / + GetTransmittanceToTopAtmosphereBoundary( + atmosphere, transmittance_texture, r, -mu), + DimensionlessSpectrum(1.0)); + } else { + return min( + GetTransmittanceToTopAtmosphereBoundary( + atmosphere, transmittance_texture, r, mu) / + GetTransmittanceToTopAtmosphereBoundary( + atmosphere, transmittance_texture, r_d, mu_d), + DimensionlessSpectrum(1.0)); + } +} + +DimensionlessSpectrum GetTransmittanceToSun( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const Length r, const Number mu_s) { + Number sin_theta_h = atmosphere.bottom_radius / r; + Number cos_theta_h = -sqrt(max(1.0 - sin_theta_h * sin_theta_h, 0.0)); + return GetTransmittanceToTopAtmosphereBoundary( + atmosphere, transmittance_texture, r, mu_s) * + smoothstep(-sin_theta_h * atmosphere.sun_angular_radius / rad, + sin_theta_h * atmosphere.sun_angular_radius / rad, + mu_s - cos_theta_h); +} + +InverseSolidAngle RayleighPhaseFunction(const Number nu) { + InverseSolidAngle k = 3.0 / (16.0 * PI * sr); + return k * (1.0 + nu * nu); +} + +InverseSolidAngle MiePhaseFunction(const Number g, const Number nu) { + InverseSolidAngle k = 3.0 / (8.0 * PI * sr) * (1.0 - g * g) / (2.0 + g * g); + return k * (1.0 + nu * nu) / pow(1.0 + g * g - 2.0 * g * nu, 1.5); +} + +vec4 GetScatteringTextureUvwzFromRMuMuSNu(const AtmosphereParameters atmosphere, + const Length r, const Number mu, const Number mu_s, const Number nu, + const bool ray_r_mu_intersects_ground) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu >= -1.0 && mu <= 1.0); + assert(mu_s >= -1.0 && mu_s <= 1.0); + assert(nu >= -1.0 && nu <= 1.0); + + // Distance to top atmosphere boundary for a horizontal ray at ground level. + Length H = sqrt(atmosphere.top_radius * atmosphere.top_radius - + atmosphere.bottom_radius * atmosphere.bottom_radius); + // Distance to the horizon. + Length rho = + SafeSqrt(r * r - atmosphere.bottom_radius * atmosphere.bottom_radius); + Number u_r = GetTextureCoordFromUnitRange(rho / H, SCATTERING_TEXTURE_R_SIZE); + + // Discriminant of the quadratic equation for the intersections of the ray + // (r,mu) with the ground (see RayIntersectsGround). + Length r_mu = r * mu; + Area discriminant = + r_mu * r_mu - r * r + atmosphere.bottom_radius * atmosphere.bottom_radius; + Number u_mu; + if (ray_r_mu_intersects_ground) { + // Distance to the ground for the ray (r,mu), and its minimum and maximum + // values over all mu - obtained for (r,-1) and (r,mu_horizon). + Length d = -r_mu - SafeSqrt(discriminant); + Length d_min = r - atmosphere.bottom_radius; + Length d_max = rho; + u_mu = 0.5 - 0.5 * GetTextureCoordFromUnitRange(d_max == d_min ? 0.0 : + (d - d_min) / (d_max - d_min), SCATTERING_TEXTURE_MU_SIZE / 2); + } else { + // Distance to the top atmosphere boundary for the ray (r,mu), and its + // minimum and maximum values over all mu - obtained for (r,1) and + // (r,mu_horizon). + Length d = -r_mu + SafeSqrt(discriminant + H * H); + Length d_min = atmosphere.top_radius - r; + Length d_max = rho + H; + u_mu = 0.5 + 0.5 * GetTextureCoordFromUnitRange( + (d - d_min) / (d_max - d_min), SCATTERING_TEXTURE_MU_SIZE / 2); + } + + Length d = DistanceToTopAtmosphereBoundary( + atmosphere, atmosphere.bottom_radius, mu_s); + Length d_min = atmosphere.top_radius - atmosphere.bottom_radius; + Length d_max = H; + Number a = (d - d_min) / (d_max - d_min); + Length D = DistanceToTopAtmosphereBoundary( + atmosphere, atmosphere.bottom_radius, atmosphere.mu_s_min); + Number A = (D - d_min) / (d_max - d_min); + // An ad-hoc function equal to 0 for mu_s = mu_s_min (because then d = D and + // thus a = A), equal to 1 for mu_s = 1 (because then d = d_min and thus + // a = 0), and with a large slope around mu_s = 0, to get more texture + // samples near the horizon. + Number u_mu_s = GetTextureCoordFromUnitRange( + max(1.0 - a / A, 0.0) / (1.0 + a), SCATTERING_TEXTURE_MU_S_SIZE); + + Number u_nu = (nu + 1.0) / 2.0; + return vec4(u_nu, u_mu_s, u_mu, u_r); +} + +vec2 GetIrradianceTextureUvFromRMuS(const AtmosphereParameters atmosphere, + const Length r, const Number mu_s) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu_s >= -1.0 && mu_s <= 1.0); + Number x_r = (r - atmosphere.bottom_radius) / + (atmosphere.top_radius - atmosphere.bottom_radius); + Number x_mu_s = mu_s * 0.5 + 0.5; + return vec2(GetTextureCoordFromUnitRange(x_mu_s, IRRADIANCE_TEXTURE_WIDTH), + GetTextureCoordFromUnitRange(x_r, IRRADIANCE_TEXTURE_HEIGHT)); +} + +IrradianceSpectrum GetIrradiance( + const AtmosphereParameters atmosphere, + const IrradianceTexture irradiance_texture, + const Length r, const Number mu_s) { + vec2 uv = GetIrradianceTextureUvFromRMuS(atmosphere, r, mu_s); + return IrradianceSpectrum(texture(irradiance_texture, uv)); +} +`,Eo=`// Based on: https://github.com/ebruneton/precomputed_atmospheric_scattering/blob/master/atmosphere/definitions.glsl + +/** + * Copyright (c) 2017 Eric Bruneton + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#define assert(x) + +#define Length float +#define Wavelength float +#define Angle float +#define SolidAngle float +#define Power float +#define LuminousPower float + +#define Number float +#define InverseLength float +#define Area float +#define Volume float +#define NumberDensity float +#define Irradiance float +#define Radiance float +#define SpectralPower float +#define SpectralIrradiance float +#define SpectralRadiance float +#define SpectralRadianceDensity float +#define ScatteringCoefficient float +#define InverseSolidAngle float +#define LuminousIntensity float +#define Luminance float +#define Illuminance float + +// A generic function from Wavelength to some other type. +#define AbstractSpectrum vec3 +// A function from Wavelength to Number. +#define DimensionlessSpectrum vec3 +// A function from Wavelength to SpectralPower. +#define PowerSpectrum vec3 +// A function from Wavelength to SpectralIrradiance. +#define IrradianceSpectrum vec3 +// A function from Wavelength to SpectralRadiance. +#define RadianceSpectrum vec3 +// A function from Wavelength to SpectralRadianceDensity. +#define RadianceDensitySpectrum vec3 +// A function from Wavelength to ScatteringCoefficient. +#define ScatteringSpectrum vec3 + +// A position in 3D (3 length values). +#define Position vec3 +// A unit direction vector in 3D (3 unit-less values). +#define Direction vec3 +// A vector of 3 luminance values. +#define Luminance3 vec3 +// A vector of 3 illuminance values. +#define Illuminance3 vec3 + +#define TransmittanceTexture sampler2D +#define AbstractScatteringTexture sampler3D +#define ReducedScatteringTexture sampler3D +#define ScatteringTexture sampler3D +#define ScatteringDensityTexture sampler3D +#define IrradianceTexture sampler2D + +const Length m = 1.0; +const Wavelength nm = 1.0; +const Angle rad = 1.0; +const SolidAngle sr = 1.0; +const Power watt = 1.0; +const LuminousPower lm = 1.0; + +#if !defined(PI) +const float PI = 3.14159265358979323846; +#endif // !defined(PI) + +const Length km = 1000.0 * m; +const Area m2 = m * m; +const Volume m3 = m * m * m; +const Angle pi = PI * rad; +const Angle deg = pi / 180.0; +const Irradiance watt_per_square_meter = watt / m2; +const Radiance watt_per_square_meter_per_sr = watt / (m2 * sr); +const SpectralIrradiance watt_per_square_meter_per_nm = watt / (m2 * nm); +const SpectralRadiance watt_per_square_meter_per_sr_per_nm = watt / (m2 * sr * nm); +const SpectralRadianceDensity watt_per_cubic_meter_per_sr_per_nm = watt / (m3 * sr * nm); +const LuminousIntensity cd = lm / sr; +const LuminousIntensity kcd = 1000.0 * cd; +const Luminance cd_per_square_meter = cd / m2; +const Luminance kcd_per_square_meter = kcd / m2; + +struct DensityProfileLayer { + Length width; + Number exp_term; + InverseLength exp_scale; + InverseLength linear_term; + Number constant_term; +}; + +struct DensityProfile { + DensityProfileLayer layers[2]; +}; + +// See AtmosphereParameter.ts for further details. +struct AtmosphereParameters { + IrradianceSpectrum solar_irradiance; + Angle sun_angular_radius; + Length bottom_radius; + Length top_radius; + DensityProfile rayleigh_density; + ScatteringSpectrum rayleigh_scattering; + DensityProfile mie_density; + ScatteringSpectrum mie_scattering; + ScatteringSpectrum mie_extinction; + Number mie_phase_function_g; + DensityProfile absorption_density; + ScatteringSpectrum absorption_extinction; + DimensionlessSpectrum ground_albedo; + Number mu_s_min; +}; +`,ET=`// Based on: https://github.com/ebruneton/precomputed_atmospheric_scattering/blob/master/atmosphere/functions.glsl + +/** + * Copyright (c) 2017 Eric Bruneton + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + * + * Precomputed Atmospheric Scattering + * Copyright (c) 2008 INRIA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifdef COMBINED_SCATTERING_TEXTURES +vec3 GetExtrapolatedSingleMieScattering( + const AtmosphereParameters atmosphere, const vec4 scattering) { + // Algebraically this can never be negative, but rounding errors can produce + // that effect for sufficiently short view rays. + // @shotamatsuda: Avoid division by infinitesimal values. + // See https://github.com/takram-design-engineering/three-geospatial/issues/47 + if (scattering.r < 1e-5) { + return vec3(0.0); + } + return scattering.rgb * scattering.a / scattering.r * + (atmosphere.rayleigh_scattering.r / atmosphere.mie_scattering.r) * + (atmosphere.mie_scattering / atmosphere.rayleigh_scattering); +} +#endif // COMBINED_SCATTERING_TEXTURES + +IrradianceSpectrum GetCombinedScattering( + const AtmosphereParameters atmosphere, + const ReducedScatteringTexture scattering_texture, + const ReducedScatteringTexture single_mie_scattering_texture, + const Length r, const Number mu, const Number mu_s, const Number nu, + const bool ray_r_mu_intersects_ground, + out IrradianceSpectrum single_mie_scattering) { + vec4 uvwz = GetScatteringTextureUvwzFromRMuMuSNu( + atmosphere, r, mu, mu_s, nu, ray_r_mu_intersects_ground); + Number tex_coord_x = uvwz.x * Number(SCATTERING_TEXTURE_NU_SIZE - 1); + Number tex_x = floor(tex_coord_x); + Number lerp = tex_coord_x - tex_x; + vec3 uvw0 = vec3((tex_x + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), + uvwz.z, uvwz.w); + vec3 uvw1 = vec3((tex_x + 1.0 + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), + uvwz.z, uvwz.w); +#ifdef COMBINED_SCATTERING_TEXTURES + vec4 combined_scattering = + texture(scattering_texture, uvw0) * (1.0 - lerp) + + texture(scattering_texture, uvw1) * lerp; + IrradianceSpectrum scattering = IrradianceSpectrum(combined_scattering); + single_mie_scattering = + GetExtrapolatedSingleMieScattering(atmosphere, combined_scattering); +#else // COMBINED_SCATTERING_TEXTURES + IrradianceSpectrum scattering = IrradianceSpectrum( + texture(scattering_texture, uvw0) * (1.0 - lerp) + + texture(scattering_texture, uvw1) * lerp); + single_mie_scattering = IrradianceSpectrum( + texture(single_mie_scattering_texture, uvw0) * (1.0 - lerp) + + texture(single_mie_scattering_texture, uvw1) * lerp); +#endif // COMBINED_SCATTERING_TEXTURES + return scattering; +} + +// @shotamatsuda: Added for reading higher-order scattering texture. +#ifdef HAS_HIGHER_ORDER_SCATTERING_TEXTURE +IrradianceSpectrum GetScattering( + const AtmosphereParameters atmosphere, + const ReducedScatteringTexture scattering_texture, + const Length r, const Number mu, const Number mu_s, const Number nu, + const bool ray_r_mu_intersects_ground) { + vec4 uvwz = GetScatteringTextureUvwzFromRMuMuSNu( + atmosphere, r, mu, mu_s, nu, ray_r_mu_intersects_ground); + Number tex_coord_x = uvwz.x * Number(SCATTERING_TEXTURE_NU_SIZE - 1); + Number tex_x = floor(tex_coord_x); + Number lerp = tex_coord_x - tex_x; + vec3 uvw0 = vec3((tex_x + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), + uvwz.z, uvwz.w); + vec3 uvw1 = vec3((tex_x + 1.0 + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), + uvwz.z, uvwz.w); + IrradianceSpectrum scattering = IrradianceSpectrum( + texture(scattering_texture, uvw0) * (1.0 - lerp) + + texture(scattering_texture, uvw1) * lerp); + return scattering; +} +#endif // HAS_HIGHER_ORDER_SCATTERING_TEXTURE + +RadianceSpectrum GetSkyRadiance( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const ReducedScatteringTexture scattering_texture, + const ReducedScatteringTexture single_mie_scattering_texture, + Position camera, const Direction view_ray, const Length shadow_length, + const Direction sun_direction, + out DimensionlessSpectrum transmittance) { + // Compute the distance to the top atmosphere boundary along the view ray, + // assuming the viewer is in space (or NaN if the view ray does not intersect + // the atmosphere). + Length r = length(camera); + Length rmu = dot(camera, view_ray); + // @shotamatsuda: Use SafeSqrt instead. + // See: https://github.com/takram-design-engineering/three-geospatial/pull/26 + Length distance_to_top_atmosphere_boundary = -rmu - + SafeSqrt(rmu * rmu - r * r + + atmosphere.top_radius * atmosphere.top_radius); + // If the viewer is in space and the view ray intersects the atmosphere, move + // the viewer to the top atmosphere boundary (along the view ray): + if (distance_to_top_atmosphere_boundary > 0.0 * m) { + camera = camera + view_ray * distance_to_top_atmosphere_boundary; + r = atmosphere.top_radius; + rmu += distance_to_top_atmosphere_boundary; + } else if (r > atmosphere.top_radius) { + // If the view ray does not intersect the atmosphere, simply return 0. + transmittance = DimensionlessSpectrum(1.0); + return RadianceSpectrum(0.0 * watt_per_square_meter_per_sr_per_nm); + } + // Compute the r, mu, mu_s and nu parameters needed for the texture lookups. + Number mu = rmu / r; + Number mu_s = dot(camera, sun_direction) / r; + Number nu = dot(view_ray, sun_direction); + + // @shotamatsuda: For rendering points below the bottom atmosphere. + #ifdef GROUND + bool ray_r_mu_intersects_ground = RayIntersectsGround(atmosphere, r, mu); + #else // GROUND + bool ray_r_mu_intersects_ground = false; + #endif // GROUND + + transmittance = ray_r_mu_intersects_ground ? DimensionlessSpectrum(0.0) : + GetTransmittanceToTopAtmosphereBoundary( + atmosphere, transmittance_texture, r, mu); + IrradianceSpectrum single_mie_scattering; + IrradianceSpectrum scattering; + if (shadow_length == 0.0 * m) { + scattering = GetCombinedScattering( + atmosphere, scattering_texture, single_mie_scattering_texture, + r, mu, mu_s, nu, ray_r_mu_intersects_ground, + single_mie_scattering); + } else { + // Case of light shafts (shadow_length is the total length noted l in our + // paper): we omit the scattering between the camera and the point at + // distance l, by implementing Eq. (18) of the paper (shadow_transmittance + // is the T(x,x_s) term, scattering is the S|x_s=x+lv term). + Length d = shadow_length; + Length r_p = + ClampRadius(atmosphere, sqrt(d * d + 2.0 * r * mu * d + r * r)); + Number mu_p = (r * mu + d) / r_p; + Number mu_s_p = (r * mu_s + d * nu) / r_p; + + scattering = GetCombinedScattering( + atmosphere, scattering_texture, single_mie_scattering_texture, + r_p, mu_p, mu_s_p, nu, ray_r_mu_intersects_ground, + single_mie_scattering); + DimensionlessSpectrum shadow_transmittance = + GetTransmittance(atmosphere, transmittance_texture, + r, mu, shadow_length, ray_r_mu_intersects_ground); + // @shotamatsuda: Occlude only single Rayleigh scattering by the shadow. +#ifdef HAS_HIGHER_ORDER_SCATTERING_TEXTURE + IrradianceSpectrum higher_order_scattering = GetScattering( + atmosphere, higher_order_scattering_texture, + r_p, mu_p, mu_s_p, nu, ray_r_mu_intersects_ground); + IrradianceSpectrum single_scattering = scattering - higher_order_scattering; + scattering = single_scattering * shadow_transmittance + higher_order_scattering; +#else // HAS_HIGHER_ORDER_SCATTERING_TEXTURE + scattering = scattering * shadow_transmittance; +#endif // HAS_HIGHER_ORDER_SCATTERING_TEXTURE + single_mie_scattering = single_mie_scattering * shadow_transmittance; + } + return scattering * RayleighPhaseFunction(nu) + single_mie_scattering * + MiePhaseFunction(atmosphere.mie_phase_function_g, nu); +} + +// @shotamatsuda: Returns the point on the ray closest to the origin. +vec3 ClosestPointOnRay(const Position camera, const Position point) { + Position ray = point - camera; + Number t = clamp(-dot(camera, ray) / dot(ray, ray), 0.0, 1.0); + return camera + t * ray; +} + +vec2 RaySphereIntersections( + const Position camera, const Direction direction, const Length radius) { + float b = 2.0 * dot(direction, camera); + float c = dot(camera, camera) - radius * radius; + float discriminant = b * b - 4.0 * c; + float Q = sqrt(discriminant); + return vec2(-b - Q, -b + Q) * 0.5; +} + +// @shotamatsuda: Clip the view ray at the bottom atmosphere boundary. +bool ClipAtBottomAtmosphere( + const AtmosphereParameters atmosphere, + const Direction view_ray, inout Position camera, inout Position point) { + const Length eps = 0.0; + Length bottom_radius = atmosphere.bottom_radius + eps; + Length r_camera = length(camera); + Length r_point = length(point); + bool camera_below = r_camera < bottom_radius; + bool point_below = r_point < bottom_radius; + + vec2 t = RaySphereIntersections(camera, view_ray, bottom_radius); + Position intersection = camera + view_ray * (camera_below ? t.y : t.x); + camera = camera_below ? intersection : camera; + point = point_below ? intersection : point; + + return camera_below && point_below; +} + +RadianceSpectrum GetSkyRadianceToPoint( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const ReducedScatteringTexture scattering_texture, + const ReducedScatteringTexture single_mie_scattering_texture, + Position camera, Position point, const Length shadow_length, + const Direction sun_direction, out DimensionlessSpectrum transmittance) { + // @shotamatsuda: Avoid artifacts when the ray does not intersect the top + // atmosphere boundary. + if (length(ClosestPointOnRay(camera, point)) > atmosphere.top_radius) { + transmittance = vec3(1.0); + return vec3(0.0); + } + + Direction view_ray = normalize(point - camera); + if (ClipAtBottomAtmosphere(atmosphere, view_ray, camera, point)) { + transmittance = vec3(1.0); + return vec3(0.0); + } + + // Compute the distance to the top atmosphere boundary along the view ray, + // assuming the viewer is in space (or NaN if the view ray does not intersect + // the atmosphere). + Length r = length(camera); + Length rmu = dot(camera, view_ray); + // @shotamatsuda: Use SafeSqrt instead. + // See: https://github.com/takram-design-engineering/three-geospatial/pull/26 + Length distance_to_top_atmosphere_boundary = -rmu - + SafeSqrt(rmu * rmu - r * r + + atmosphere.top_radius * atmosphere.top_radius); + // If the viewer is in space and the view ray intersects the atmosphere, move + // the viewer to the top atmosphere boundary (along the view ray): + if (distance_to_top_atmosphere_boundary > 0.0 * m) { + camera = camera + view_ray * distance_to_top_atmosphere_boundary; + r = atmosphere.top_radius; + rmu += distance_to_top_atmosphere_boundary; + } + + // Compute the r, mu, mu_s and nu parameters for the first texture lookup. + Number mu = rmu / r; + Number mu_s = dot(camera, sun_direction) / r; + Number nu = dot(view_ray, sun_direction); + Length d = length(point - camera); + bool ray_r_mu_intersects_ground = RayIntersectsGround(atmosphere, r, mu); + + // @shotamatsuda: Hack to avoid rendering artifacts near the horizon, due to + // finite atmosphere texture resolution and finite floating point precision. + // See: https://github.com/ebruneton/precomputed_atmospheric_scattering/pull/32 + if (!ray_r_mu_intersects_ground) { + Number mu_horizon = -SafeSqrt(1.0 - + (atmosphere.bottom_radius * atmosphere.bottom_radius) / (r * r)); + const Number eps = 0.004; + mu = max(mu, mu_horizon + eps); + } + + transmittance = GetTransmittance(atmosphere, transmittance_texture, + r, mu, d, ray_r_mu_intersects_ground); + + IrradianceSpectrum single_mie_scattering; + IrradianceSpectrum scattering = GetCombinedScattering( + atmosphere, scattering_texture, single_mie_scattering_texture, + r, mu, mu_s, nu, ray_r_mu_intersects_ground, + single_mie_scattering); + + // Compute the r, mu, mu_s and nu parameters for the second texture lookup. + // If shadow_length is not 0 (case of light shafts), we want to ignore the + // scattering along the last shadow_length meters of the view ray, which we + // do by subtracting shadow_length from d (this way scattering_p is equal to + // the S|x_s=x_0-lv term in Eq. (17) of our paper). + d = max(d - shadow_length, 0.0 * m); + Length r_p = ClampRadius(atmosphere, sqrt(d * d + 2.0 * r * mu * d + r * r)); + Number mu_p = (r * mu + d) / r_p; + Number mu_s_p = (r * mu_s + d * nu) / r_p; + + IrradianceSpectrum single_mie_scattering_p; + IrradianceSpectrum scattering_p = GetCombinedScattering( + atmosphere, scattering_texture, single_mie_scattering_texture, + r_p, mu_p, mu_s_p, nu, ray_r_mu_intersects_ground, + single_mie_scattering_p); + + // Combine the lookup results to get the scattering between camera and point. + DimensionlessSpectrum shadow_transmittance = transmittance; + if (shadow_length > 0.0 * m) { + // This is the T(x,x_s) term in Eq. (17) of our paper, for light shafts. + shadow_transmittance = GetTransmittance(atmosphere, transmittance_texture, + r, mu, d, ray_r_mu_intersects_ground); + } + // @shotamatsuda: Occlude only single Rayleigh scattering by the shadow. +#ifdef HAS_HIGHER_ORDER_SCATTERING_TEXTURE + IrradianceSpectrum higher_order_scattering = GetScattering( + atmosphere, higher_order_scattering_texture, + r, mu, mu_s, nu, ray_r_mu_intersects_ground); + IrradianceSpectrum single_scattering = scattering - higher_order_scattering; + IrradianceSpectrum higher_order_scattering_p = GetScattering( + atmosphere, higher_order_scattering_texture, + r_p, mu_p, mu_s_p, nu, ray_r_mu_intersects_ground); + IrradianceSpectrum single_scattering_p = + scattering_p - higher_order_scattering_p; + scattering = + single_scattering - shadow_transmittance * single_scattering_p + + higher_order_scattering - transmittance * higher_order_scattering_p; +#else // HAS_HIGHER_ORDER_SCATTERING_TEXTURE + scattering = scattering - shadow_transmittance * scattering_p; +#endif // HAS_HIGHER_ORDER_SCATTERING_TEXTURE + + single_mie_scattering = + single_mie_scattering - shadow_transmittance * single_mie_scattering_p; +#ifdef COMBINED_SCATTERING_TEXTURES + single_mie_scattering = GetExtrapolatedSingleMieScattering( + atmosphere, vec4(scattering, single_mie_scattering.r)); +#endif // COMBINED_SCATTERING_TEXTURES + + // Hack to avoid rendering artifacts when the sun is below the horizon. + single_mie_scattering = single_mie_scattering * + smoothstep(Number(0.0), Number(0.01), mu_s); + + return scattering * RayleighPhaseFunction(nu) + single_mie_scattering * + MiePhaseFunction(atmosphere.mie_phase_function_g, nu); +} + +IrradianceSpectrum GetSunAndSkyIrradiance( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const IrradianceTexture irradiance_texture, + const Position point, const Direction normal, const Direction sun_direction, + out IrradianceSpectrum sky_irradiance) { + Length r = length(point); + Number mu_s = dot(point, sun_direction) / r; + + // Indirect irradiance (approximated if the surface is not horizontal). + sky_irradiance = GetIrradiance(atmosphere, irradiance_texture, r, mu_s) * + (1.0 + dot(normal, point) / r) * 0.5; + + // Direct irradiance. + return atmosphere.solar_irradiance * + GetTransmittanceToSun( + atmosphere, transmittance_texture, r, mu_s) * + max(dot(normal, sun_direction), 0.0); +} + +// @shotamatsuda: Added for the clouds. +IrradianceSpectrum GetSunAndSkyScalarIrradiance( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const IrradianceTexture irradiance_texture, + const Position point, const Direction sun_direction, + out IrradianceSpectrum sky_irradiance) { + Length r = length(point); + Number mu_s = dot(point, sun_direction) / r; + + // Indirect irradiance. Integral over sphere yields 2π. + sky_irradiance = GetIrradiance(atmosphere, irradiance_texture, r, mu_s) * + 2.0 * PI; + + // Direct irradiance. Omit the cosine term. + return atmosphere.solar_irradiance * + GetTransmittanceToSun(atmosphere, transmittance_texture, r, mu_s); +} + +Luminance3 GetSolarLuminance() { + return ATMOSPHERE.solar_irradiance / + (PI * ATMOSPHERE.sun_angular_radius * ATMOSPHERE.sun_angular_radius) * + SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; +} + +Luminance3 GetSkyLuminance( + const Position camera, Direction view_ray, const Length shadow_length, + const Direction sun_direction, out DimensionlessSpectrum transmittance) { + return GetSkyRadiance(ATMOSPHERE, transmittance_texture, + scattering_texture, single_mie_scattering_texture, + camera, view_ray, shadow_length, sun_direction, + transmittance) * SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; +} + +Luminance3 GetSkyLuminanceToPoint( + const Position camera, const Position point, const Length shadow_length, + const Direction sun_direction, out DimensionlessSpectrum transmittance) { + return GetSkyRadianceToPoint(ATMOSPHERE, transmittance_texture, + scattering_texture, single_mie_scattering_texture, + camera, point, shadow_length, sun_direction, transmittance) * + SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; +} + +Illuminance3 GetSunAndSkyIlluminance( + const Position p, const Direction normal, const Direction sun_direction, + out IrradianceSpectrum sky_irradiance) { + IrradianceSpectrum sun_irradiance = GetSunAndSkyIrradiance( + ATMOSPHERE, transmittance_texture, irradiance_texture, p, normal, + sun_direction, sky_irradiance); + sky_irradiance *= SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; + return sun_irradiance * SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; +} + +// @shotamatsuda: Added for the clouds. +Illuminance3 GetSunAndSkyScalarIlluminance( + const Position p, const Direction sun_direction, + out IrradianceSpectrum sky_irradiance) { + IrradianceSpectrum sun_irradiance = GetSunAndSkyScalarIrradiance( + ATMOSPHERE, transmittance_texture, irradiance_texture, p, + sun_direction, sky_irradiance); + sky_irradiance *= SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; + return sun_irradiance * SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; +} + +#define GetSolarRadiance GetSolarLuminance +#define GetSkyRadiance GetSkyLuminance +#define GetSkyRadianceToPoint GetSkyLuminanceToPoint +#define GetSunAndSkyIrradiance GetSunAndSkyIlluminance +#define GetSunAndSkyScalarIrradiance GetSunAndSkyScalarIlluminance +`,hf=`// Based on: https://github.com/ebruneton/precomputed_atmospheric_scattering/blob/master/atmosphere/functions.glsl + +/** + * Copyright (c) 2017 Eric Bruneton + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + * + * Precomputed Atmospheric Scattering + * Copyright (c) 2008 INRIA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +Number GetLayerDensity(const DensityProfileLayer layer, const Length altitude) { + Number density = layer.exp_term * exp(layer.exp_scale * altitude) + + layer.linear_term * altitude + layer.constant_term; + return clamp(density, Number(0.0), Number(1.0)); +} + +Number GetProfileDensity(const DensityProfile profile, const Length altitude) { + DensityProfileLayer layers[2] = profile.layers; + return altitude < layers[0].width + ? GetLayerDensity(layers[0], altitude) + : GetLayerDensity(layers[1], altitude); +} + +Length ComputeOpticalLengthToTopAtmosphereBoundary( + const AtmosphereParameters atmosphere, const DensityProfile profile, + const Length r, const Number mu) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu >= -1.0 && mu <= 1.0); + // Number of intervals for the numerical integration. + const int SAMPLE_COUNT = 500; + // The integration step, i.e. the length of each integration interval. + Length dx = + DistanceToTopAtmosphereBoundary(atmosphere, r, mu) / Number(SAMPLE_COUNT); + // Integration loop. + Length result = 0.0 * m; + for (int i = 0; i <= SAMPLE_COUNT; ++i) { + Length d_i = Number(i) * dx; + // Distance between the current sample point and the planet center. + Length r_i = sqrt(d_i * d_i + 2.0 * r * mu * d_i + r * r); + // Number density at the current sample point (divided by the number density + // at the bottom of the atmosphere, yielding a dimensionless number). + Number y_i = GetProfileDensity(profile, r_i - atmosphere.bottom_radius); + // Sample weight (from the trapezoidal rule). + Number weight_i = i == 0 || i == SAMPLE_COUNT ? 0.5 : 1.0; + result += y_i * weight_i * dx; + } + return result; +} + +DimensionlessSpectrum ComputeTransmittanceToTopAtmosphereBoundary( + const AtmosphereParameters atmosphere, const Length r, const Number mu) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu >= -1.0 && mu <= 1.0); + vec3 optical_depth = ( + atmosphere.rayleigh_scattering * + ComputeOpticalLengthToTopAtmosphereBoundary( + atmosphere, atmosphere.rayleigh_density, r, mu) + + atmosphere.mie_extinction * + ComputeOpticalLengthToTopAtmosphereBoundary( + atmosphere, atmosphere.mie_density, r, mu) + + atmosphere.absorption_extinction * + ComputeOpticalLengthToTopAtmosphereBoundary( + atmosphere, atmosphere.absorption_density, r, mu)); + // @shotamatsuda: Added for the precomputation stage in half-float precision. + #ifdef TRANSMITTANCE_PRECISION_LOG + return optical_depth; + #else // TRANSMITTANCE_PRECISION_LOG + return exp(-optical_depth); + #endif // TRANSMITTANCE_PRECISION_LOG +} + +Number GetUnitRangeFromTextureCoord(const Number u, const int texture_size) { + return (u - 0.5 / Number(texture_size)) / (1.0 - 1.0 / Number(texture_size)); +} + +void GetRMuFromTransmittanceTextureUv(const AtmosphereParameters atmosphere, + const vec2 uv, out Length r, out Number mu) { + assert(uv.x >= 0.0 && uv.x <= 1.0); + assert(uv.y >= 0.0 && uv.y <= 1.0); + Number x_mu = GetUnitRangeFromTextureCoord(uv.x, TRANSMITTANCE_TEXTURE_WIDTH); + Number x_r = GetUnitRangeFromTextureCoord(uv.y, TRANSMITTANCE_TEXTURE_HEIGHT); + // Distance to top atmosphere boundary for a horizontal ray at ground level. + Length H = sqrt(atmosphere.top_radius * atmosphere.top_radius - + atmosphere.bottom_radius * atmosphere.bottom_radius); + // Distance to the horizon, from which we can compute r: + Length rho = H * x_r; + r = sqrt(rho * rho + atmosphere.bottom_radius * atmosphere.bottom_radius); + // Distance to the top atmosphere boundary for the ray (r,mu), and its minimum + // and maximum values over all mu - obtained for (r,1) and (r,mu_horizon) - + // from which we can recover mu: + Length d_min = atmosphere.top_radius - r; + Length d_max = rho + H; + Length d = d_min + x_mu * (d_max - d_min); + mu = d == 0.0 * m ? Number(1.0) : (H * H - rho * rho - d * d) / (2.0 * r * d); + mu = ClampCosine(mu); +} + +DimensionlessSpectrum ComputeTransmittanceToTopAtmosphereBoundaryTexture( + const AtmosphereParameters atmosphere, const vec2 frag_coord) { + const vec2 TRANSMITTANCE_TEXTURE_SIZE = + vec2(TRANSMITTANCE_TEXTURE_WIDTH, TRANSMITTANCE_TEXTURE_HEIGHT); + Length r; + Number mu; + GetRMuFromTransmittanceTextureUv( + atmosphere, frag_coord / TRANSMITTANCE_TEXTURE_SIZE, r, mu); + return ComputeTransmittanceToTopAtmosphereBoundary(atmosphere, r, mu); +} + +void ComputeSingleScatteringIntegrand( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const Length r, const Number mu, const Number mu_s, const Number nu, + const Length d, const bool ray_r_mu_intersects_ground, + out DimensionlessSpectrum rayleigh, out DimensionlessSpectrum mie) { + Length r_d = ClampRadius(atmosphere, sqrt(d * d + 2.0 * r * mu * d + r * r)); + Number mu_s_d = ClampCosine((r * mu_s + d * nu) / r_d); + DimensionlessSpectrum transmittance = + GetTransmittance( + atmosphere, transmittance_texture, r, mu, d, + ray_r_mu_intersects_ground) * + GetTransmittanceToSun( + atmosphere, transmittance_texture, r_d, mu_s_d); + rayleigh = transmittance * GetProfileDensity( + atmosphere.rayleigh_density, r_d - atmosphere.bottom_radius); + mie = transmittance * GetProfileDensity( + atmosphere.mie_density, r_d - atmosphere.bottom_radius); +} + +Length DistanceToNearestAtmosphereBoundary(const AtmosphereParameters atmosphere, + Length r, Number mu, bool ray_r_mu_intersects_ground) { + if (ray_r_mu_intersects_ground) { + return DistanceToBottomAtmosphereBoundary(atmosphere, r, mu); + } else { + return DistanceToTopAtmosphereBoundary(atmosphere, r, mu); + } +} + +void ComputeSingleScattering( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const Length r, const Number mu, const Number mu_s, const Number nu, + const bool ray_r_mu_intersects_ground, + out IrradianceSpectrum rayleigh, out IrradianceSpectrum mie) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu >= -1.0 && mu <= 1.0); + assert(mu_s >= -1.0 && mu_s <= 1.0); + assert(nu >= -1.0 && nu <= 1.0); + + // Number of intervals for the numerical integration. + const int SAMPLE_COUNT = 50; + // The integration step, i.e. the length of each integration interval. + Length dx = + DistanceToNearestAtmosphereBoundary(atmosphere, r, mu, + ray_r_mu_intersects_ground) / Number(SAMPLE_COUNT); + // Integration loop. + DimensionlessSpectrum rayleigh_sum = DimensionlessSpectrum(0.0); + DimensionlessSpectrum mie_sum = DimensionlessSpectrum(0.0); + for (int i = 0; i <= SAMPLE_COUNT; ++i) { + Length d_i = Number(i) * dx; + // The Rayleigh and Mie single scattering at the current sample point. + DimensionlessSpectrum rayleigh_i; + DimensionlessSpectrum mie_i; + ComputeSingleScatteringIntegrand(atmosphere, transmittance_texture, + r, mu, mu_s, nu, d_i, ray_r_mu_intersects_ground, rayleigh_i, mie_i); + // Sample weight (from the trapezoidal rule). + Number weight_i = (i == 0 || i == SAMPLE_COUNT) ? 0.5 : 1.0; + rayleigh_sum += rayleigh_i * weight_i; + mie_sum += mie_i * weight_i; + } + rayleigh = rayleigh_sum * dx * atmosphere.solar_irradiance * + atmosphere.rayleigh_scattering; + mie = mie_sum * dx * atmosphere.solar_irradiance * atmosphere.mie_scattering; +} + +void GetRMuMuSNuFromScatteringTextureUvwz(const AtmosphereParameters atmosphere, + const vec4 uvwz, out Length r, out Number mu, out Number mu_s, + out Number nu, out bool ray_r_mu_intersects_ground) { + assert(uvwz.x >= 0.0 && uvwz.x <= 1.0); + assert(uvwz.y >= 0.0 && uvwz.y <= 1.0); + assert(uvwz.z >= 0.0 && uvwz.z <= 1.0); + assert(uvwz.w >= 0.0 && uvwz.w <= 1.0); + + // Distance to top atmosphere boundary for a horizontal ray at ground level. + Length H = sqrt(atmosphere.top_radius * atmosphere.top_radius - + atmosphere.bottom_radius * atmosphere.bottom_radius); + // Distance to the horizon. + Length rho = + H * GetUnitRangeFromTextureCoord(uvwz.w, SCATTERING_TEXTURE_R_SIZE); + r = sqrt(rho * rho + atmosphere.bottom_radius * atmosphere.bottom_radius); + + if (uvwz.z < 0.5) { + // Distance to the ground for the ray (r,mu), and its minimum and maximum + // values over all mu - obtained for (r,-1) and (r,mu_horizon) - from which + // we can recover mu: + Length d_min = r - atmosphere.bottom_radius; + Length d_max = rho; + Length d = d_min + (d_max - d_min) * GetUnitRangeFromTextureCoord( + 1.0 - 2.0 * uvwz.z, SCATTERING_TEXTURE_MU_SIZE / 2); + mu = d == 0.0 * m ? Number(-1.0) : + ClampCosine(-(rho * rho + d * d) / (2.0 * r * d)); + ray_r_mu_intersects_ground = true; + } else { + // Distance to the top atmosphere boundary for the ray (r,mu), and its + // minimum and maximum values over all mu - obtained for (r,1) and + // (r,mu_horizon) - from which we can recover mu: + Length d_min = atmosphere.top_radius - r; + Length d_max = rho + H; + Length d = d_min + (d_max - d_min) * GetUnitRangeFromTextureCoord( + 2.0 * uvwz.z - 1.0, SCATTERING_TEXTURE_MU_SIZE / 2); + mu = d == 0.0 * m ? Number(1.0) : + ClampCosine((H * H - rho * rho - d * d) / (2.0 * r * d)); + ray_r_mu_intersects_ground = false; + } + + Number x_mu_s = + GetUnitRangeFromTextureCoord(uvwz.y, SCATTERING_TEXTURE_MU_S_SIZE); + Length d_min = atmosphere.top_radius - atmosphere.bottom_radius; + Length d_max = H; + Length D = DistanceToTopAtmosphereBoundary( + atmosphere, atmosphere.bottom_radius, atmosphere.mu_s_min); + Number A = (D - d_min) / (d_max - d_min); + Number a = (A - x_mu_s * A) / (1.0 + x_mu_s * A); + Length d = d_min + min(a, A) * (d_max - d_min); + mu_s = d == 0.0 * m ? Number(1.0) : + ClampCosine((H * H - d * d) / (2.0 * atmosphere.bottom_radius * d)); + + nu = ClampCosine(uvwz.x * 2.0 - 1.0); +} + +void GetRMuMuSNuFromScatteringTextureFragCoord( + const AtmosphereParameters atmosphere, const vec3 frag_coord, + out Length r, out Number mu, out Number mu_s, out Number nu, + out bool ray_r_mu_intersects_ground) { + const vec4 SCATTERING_TEXTURE_SIZE = vec4( + SCATTERING_TEXTURE_NU_SIZE - 1, + SCATTERING_TEXTURE_MU_S_SIZE, + SCATTERING_TEXTURE_MU_SIZE, + SCATTERING_TEXTURE_R_SIZE); + Number frag_coord_nu = + floor(frag_coord.x / Number(SCATTERING_TEXTURE_MU_S_SIZE)); + Number frag_coord_mu_s = + mod(frag_coord.x, Number(SCATTERING_TEXTURE_MU_S_SIZE)); + vec4 uvwz = + vec4(frag_coord_nu, frag_coord_mu_s, frag_coord.y, frag_coord.z) / + SCATTERING_TEXTURE_SIZE; + GetRMuMuSNuFromScatteringTextureUvwz( + atmosphere, uvwz, r, mu, mu_s, nu, ray_r_mu_intersects_ground); + // Clamp nu to its valid range of values, given mu and mu_s. + nu = clamp(nu, mu * mu_s - sqrt((1.0 - mu * mu) * (1.0 - mu_s * mu_s)), + mu * mu_s + sqrt((1.0 - mu * mu) * (1.0 - mu_s * mu_s))); +} + +void ComputeSingleScatteringTexture(const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, const vec3 frag_coord, + out IrradianceSpectrum rayleigh, out IrradianceSpectrum mie) { + Length r; + Number mu; + Number mu_s; + Number nu; + bool ray_r_mu_intersects_ground; + GetRMuMuSNuFromScatteringTextureFragCoord(atmosphere, frag_coord, + r, mu, mu_s, nu, ray_r_mu_intersects_ground); + ComputeSingleScattering(atmosphere, transmittance_texture, + r, mu, mu_s, nu, ray_r_mu_intersects_ground, rayleigh, mie); +} + +AbstractSpectrum GetScattering( + const AtmosphereParameters atmosphere, + const AbstractScatteringTexture scattering_texture, + const Length r, const Number mu, const Number mu_s, const Number nu, + const bool ray_r_mu_intersects_ground) { + vec4 uvwz = GetScatteringTextureUvwzFromRMuMuSNu( + atmosphere, r, mu, mu_s, nu, ray_r_mu_intersects_ground); + Number tex_coord_x = uvwz.x * Number(SCATTERING_TEXTURE_NU_SIZE - 1); + Number tex_x = floor(tex_coord_x); + Number lerp = tex_coord_x - tex_x; + vec3 uvw0 = vec3((tex_x + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), + uvwz.z, uvwz.w); + vec3 uvw1 = vec3((tex_x + 1.0 + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), + uvwz.z, uvwz.w); + return AbstractSpectrum(texture(scattering_texture, uvw0) * (1.0 - lerp) + + texture(scattering_texture, uvw1) * lerp); +} + +RadianceSpectrum GetScattering( + const AtmosphereParameters atmosphere, + const ReducedScatteringTexture single_rayleigh_scattering_texture, + const ReducedScatteringTexture single_mie_scattering_texture, + const ScatteringTexture multiple_scattering_texture, + const Length r, const Number mu, const Number mu_s, const Number nu, + const bool ray_r_mu_intersects_ground, + const int scattering_order) { + if (scattering_order == 1) { + IrradianceSpectrum rayleigh = GetScattering( + atmosphere, single_rayleigh_scattering_texture, r, mu, mu_s, nu, + ray_r_mu_intersects_ground); + IrradianceSpectrum mie = GetScattering( + atmosphere, single_mie_scattering_texture, r, mu, mu_s, nu, + ray_r_mu_intersects_ground); + return rayleigh * RayleighPhaseFunction(nu) + + mie * MiePhaseFunction(atmosphere.mie_phase_function_g, nu); + } else { + return GetScattering( + atmosphere, multiple_scattering_texture, r, mu, mu_s, nu, + ray_r_mu_intersects_ground); + } +} + +IrradianceSpectrum GetIrradiance( + const AtmosphereParameters atmosphere, + const IrradianceTexture irradiance_texture, + const Length r, const Number mu_s); + +RadianceDensitySpectrum ComputeScatteringDensity( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const ReducedScatteringTexture single_rayleigh_scattering_texture, + const ReducedScatteringTexture single_mie_scattering_texture, + const ScatteringTexture multiple_scattering_texture, + const IrradianceTexture irradiance_texture, + const Length r, const Number mu, const Number mu_s, const Number nu, + const int scattering_order) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu >= -1.0 && mu <= 1.0); + assert(mu_s >= -1.0 && mu_s <= 1.0); + assert(nu >= -1.0 && nu <= 1.0); + assert(scattering_order >= 2); + + // Compute unit direction vectors for the zenith, the view direction omega and + // and the sun direction omega_s, such that the cosine of the view-zenith + // angle is mu, the cosine of the sun-zenith angle is mu_s, and the cosine of + // the view-sun angle is nu. The goal is to simplify computations below. + vec3 zenith_direction = vec3(0.0, 0.0, 1.0); + vec3 omega = vec3(sqrt(1.0 - mu * mu), 0.0, mu); + Number sun_dir_x = omega.x == 0.0 ? 0.0 : (nu - mu * mu_s) / omega.x; + Number sun_dir_y = sqrt(max(1.0 - sun_dir_x * sun_dir_x - mu_s * mu_s, 0.0)); + vec3 omega_s = vec3(sun_dir_x, sun_dir_y, mu_s); + + const int SAMPLE_COUNT = 16; + const Angle dphi = pi / Number(SAMPLE_COUNT); + const Angle dtheta = pi / Number(SAMPLE_COUNT); + RadianceDensitySpectrum rayleigh_mie = + RadianceDensitySpectrum(0.0 * watt_per_cubic_meter_per_sr_per_nm); + + // Nested loops for the integral over all the incident directions omega_i. + for (int l = 0; l < SAMPLE_COUNT; ++l) { + Angle theta = (Number(l) + 0.5) * dtheta; + Number cos_theta = cos(theta); + Number sin_theta = sin(theta); + bool ray_r_theta_intersects_ground = + RayIntersectsGround(atmosphere, r, cos_theta); + + // The distance and transmittance to the ground only depend on theta, so we + // can compute them in the outer loop for efficiency. + Length distance_to_ground = 0.0 * m; + DimensionlessSpectrum transmittance_to_ground = DimensionlessSpectrum(0.0); + DimensionlessSpectrum ground_albedo = DimensionlessSpectrum(0.0); + if (ray_r_theta_intersects_ground) { + distance_to_ground = + DistanceToBottomAtmosphereBoundary(atmosphere, r, cos_theta); + transmittance_to_ground = + GetTransmittance(atmosphere, transmittance_texture, r, cos_theta, + distance_to_ground, true /* ray_intersects_ground */); + ground_albedo = atmosphere.ground_albedo; + } + + for (int m = 0; m < 2 * SAMPLE_COUNT; ++m) { + Angle phi = (Number(m) + 0.5) * dphi; + vec3 omega_i = + vec3(cos(phi) * sin_theta, sin(phi) * sin_theta, cos_theta); + SolidAngle domega_i = (dtheta / rad) * (dphi / rad) * sin(theta) * sr; + + // The radiance L_i arriving from direction omega_i after n-1 bounces is + // the sum of a term given by the precomputed scattering texture for the + // (n-1)-th order: + Number nu1 = dot(omega_s, omega_i); + RadianceSpectrum incident_radiance = GetScattering(atmosphere, + single_rayleigh_scattering_texture, single_mie_scattering_texture, + multiple_scattering_texture, r, omega_i.z, mu_s, nu1, + ray_r_theta_intersects_ground, scattering_order - 1); + + // and of the contribution from the light paths with n-1 bounces and whose + // last bounce is on the ground. This contribution is the product of the + // transmittance to the ground, the ground albedo, the ground BRDF, and + // the irradiance received on the ground after n-2 bounces. + vec3 ground_normal = + normalize(zenith_direction * r + omega_i * distance_to_ground); + IrradianceSpectrum ground_irradiance = GetIrradiance( + atmosphere, irradiance_texture, atmosphere.bottom_radius, + dot(ground_normal, omega_s)); + incident_radiance += transmittance_to_ground * + ground_albedo * (1.0 / (PI * sr)) * ground_irradiance; + + // The radiance finally scattered from direction omega_i towards direction + // -omega is the product of the incident radiance, the scattering + // coefficient, and the phase function for directions omega and omega_i + // (all this summed over all particle types, i.e. Rayleigh and Mie). + Number nu2 = dot(omega, omega_i); + Number rayleigh_density = GetProfileDensity( + atmosphere.rayleigh_density, r - atmosphere.bottom_radius); + Number mie_density = GetProfileDensity( + atmosphere.mie_density, r - atmosphere.bottom_radius); + rayleigh_mie += incident_radiance * ( + atmosphere.rayleigh_scattering * rayleigh_density * + RayleighPhaseFunction(nu2) + + atmosphere.mie_scattering * mie_density * + MiePhaseFunction(atmosphere.mie_phase_function_g, nu2)) * + domega_i; + } + } + return rayleigh_mie; +} + +RadianceSpectrum ComputeMultipleScattering( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const ScatteringDensityTexture scattering_density_texture, + const Length r, const Number mu, const Number mu_s, const Number nu, + const bool ray_r_mu_intersects_ground) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu >= -1.0 && mu <= 1.0); + assert(mu_s >= -1.0 && mu_s <= 1.0); + assert(nu >= -1.0 && nu <= 1.0); + + // Number of intervals for the numerical integration. + const int SAMPLE_COUNT = 50; + // The integration step, i.e. the length of each integration interval. + Length dx = + DistanceToNearestAtmosphereBoundary( + atmosphere, r, mu, ray_r_mu_intersects_ground) / + Number(SAMPLE_COUNT); + // Integration loop. + RadianceSpectrum rayleigh_mie_sum = + RadianceSpectrum(0.0 * watt_per_square_meter_per_sr_per_nm); + for (int i = 0; i <= SAMPLE_COUNT; ++i) { + Length d_i = Number(i) * dx; + + // The r, mu and mu_s parameters at the current integration point (see the + // single scattering section for a detailed explanation). + Length r_i = + ClampRadius(atmosphere, sqrt(d_i * d_i + 2.0 * r * mu * d_i + r * r)); + Number mu_i = ClampCosine((r * mu + d_i) / r_i); + Number mu_s_i = ClampCosine((r * mu_s + d_i * nu) / r_i); + + // The Rayleigh and Mie multiple scattering at the current sample point. + RadianceSpectrum rayleigh_mie_i = + GetScattering( + atmosphere, scattering_density_texture, r_i, mu_i, mu_s_i, nu, + ray_r_mu_intersects_ground) * + GetTransmittance( + atmosphere, transmittance_texture, r, mu, d_i, + ray_r_mu_intersects_ground) * + dx; + // Sample weight (from the trapezoidal rule). + Number weight_i = (i == 0 || i == SAMPLE_COUNT) ? 0.5 : 1.0; + rayleigh_mie_sum += rayleigh_mie_i * weight_i; + } + return rayleigh_mie_sum; +} + +RadianceDensitySpectrum ComputeScatteringDensityTexture( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const ReducedScatteringTexture single_rayleigh_scattering_texture, + const ReducedScatteringTexture single_mie_scattering_texture, + const ScatteringTexture multiple_scattering_texture, + const IrradianceTexture irradiance_texture, + const vec3 frag_coord, const int scattering_order) { + Length r; + Number mu; + Number mu_s; + Number nu; + bool ray_r_mu_intersects_ground; + GetRMuMuSNuFromScatteringTextureFragCoord(atmosphere, frag_coord, + r, mu, mu_s, nu, ray_r_mu_intersects_ground); + return ComputeScatteringDensity(atmosphere, transmittance_texture, + single_rayleigh_scattering_texture, single_mie_scattering_texture, + multiple_scattering_texture, irradiance_texture, r, mu, mu_s, nu, + scattering_order); +} + +RadianceSpectrum ComputeMultipleScatteringTexture( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const ScatteringDensityTexture scattering_density_texture, + const vec3 frag_coord, out Number nu) { + Length r; + Number mu; + Number mu_s; + bool ray_r_mu_intersects_ground; + GetRMuMuSNuFromScatteringTextureFragCoord(atmosphere, frag_coord, + r, mu, mu_s, nu, ray_r_mu_intersects_ground); + return ComputeMultipleScattering(atmosphere, transmittance_texture, + scattering_density_texture, r, mu, mu_s, nu, + ray_r_mu_intersects_ground); +} + +IrradianceSpectrum ComputeDirectIrradiance( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const Length r, const Number mu_s) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu_s >= -1.0 && mu_s <= 1.0); + + Number alpha_s = atmosphere.sun_angular_radius / rad; + // Approximate average of the cosine factor mu_s over the visible fraction of + // the Sun disc. + Number average_cosine_factor = + mu_s < -alpha_s ? 0.0 : (mu_s > alpha_s ? mu_s : + (mu_s + alpha_s) * (mu_s + alpha_s) / (4.0 * alpha_s)); + + return atmosphere.solar_irradiance * + GetTransmittanceToTopAtmosphereBoundary( + atmosphere, transmittance_texture, r, mu_s) * average_cosine_factor; + +} + +IrradianceSpectrum ComputeIndirectIrradiance( + const AtmosphereParameters atmosphere, + const ReducedScatteringTexture single_rayleigh_scattering_texture, + const ReducedScatteringTexture single_mie_scattering_texture, + const ScatteringTexture multiple_scattering_texture, + const Length r, const Number mu_s, const int scattering_order) { + assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); + assert(mu_s >= -1.0 && mu_s <= 1.0); + assert(scattering_order >= 1); + + const int SAMPLE_COUNT = 32; + const Angle dphi = pi / Number(SAMPLE_COUNT); + const Angle dtheta = pi / Number(SAMPLE_COUNT); + + IrradianceSpectrum result = + IrradianceSpectrum(0.0 * watt_per_square_meter_per_nm); + vec3 omega_s = vec3(sqrt(1.0 - mu_s * mu_s), 0.0, mu_s); + for (int j = 0; j < SAMPLE_COUNT / 2; ++j) { + Angle theta = (Number(j) + 0.5) * dtheta; + for (int i = 0; i < 2 * SAMPLE_COUNT; ++i) { + Angle phi = (Number(i) + 0.5) * dphi; + vec3 omega = + vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); + SolidAngle domega = (dtheta / rad) * (dphi / rad) * sin(theta) * sr; + + Number nu = dot(omega, omega_s); + result += GetScattering(atmosphere, single_rayleigh_scattering_texture, + single_mie_scattering_texture, multiple_scattering_texture, + r, omega.z, mu_s, nu, false /* ray_r_theta_intersects_ground */, + scattering_order) * + omega.z * domega; + } + } + return result; +} + +void GetRMuSFromIrradianceTextureUv(const AtmosphereParameters atmosphere, + const vec2 uv, out Length r, out Number mu_s) { + assert(uv.x >= 0.0 && uv.x <= 1.0); + assert(uv.y >= 0.0 && uv.y <= 1.0); + Number x_mu_s = GetUnitRangeFromTextureCoord(uv.x, IRRADIANCE_TEXTURE_WIDTH); + Number x_r = GetUnitRangeFromTextureCoord(uv.y, IRRADIANCE_TEXTURE_HEIGHT); + r = atmosphere.bottom_radius + + x_r * (atmosphere.top_radius - atmosphere.bottom_radius); + mu_s = ClampCosine(2.0 * x_mu_s - 1.0); +} + +const vec2 IRRADIANCE_TEXTURE_SIZE = + vec2(IRRADIANCE_TEXTURE_WIDTH, IRRADIANCE_TEXTURE_HEIGHT); + +IrradianceSpectrum ComputeDirectIrradianceTexture( + const AtmosphereParameters atmosphere, + const TransmittanceTexture transmittance_texture, + const vec2 frag_coord) { + Length r; + Number mu_s; + GetRMuSFromIrradianceTextureUv( + atmosphere, frag_coord / IRRADIANCE_TEXTURE_SIZE, r, mu_s); + return ComputeDirectIrradiance(atmosphere, transmittance_texture, r, mu_s); +} + +IrradianceSpectrum ComputeIndirectIrradianceTexture( + const AtmosphereParameters atmosphere, + const ReducedScatteringTexture single_rayleigh_scattering_texture, + const ReducedScatteringTexture single_mie_scattering_texture, + const ScatteringTexture multiple_scattering_texture, + const vec2 frag_coord, const int scattering_order) { + Length r; + Number mu_s; + GetRMuSFromIrradianceTextureUv( + atmosphere, frag_coord / IRRADIANCE_TEXTURE_SIZE, r, mu_s); + return ComputeIndirectIrradiance(atmosphere, + single_rayleigh_scattering_texture, single_mie_scattering_texture, + multiple_scattering_texture, r, mu_s, scattering_order); +} +`,Fse=new D(.2126,.7152,.0722),Hse=["solarIrradiance","sunAngularRadius","bottomRadius","topRadius","rayleighDensity","rayleighScattering","mieDensity","mieScattering","mieExtinction","miePhaseFunctionG","absorptionDensity","absorptionExtinction","groundAlbedo","muSMin","skyRadianceToLuminance","sunRadianceToLuminance"];function Vse(n,e){if(e!=null)for(const t of Hse){const i=e[t];i!=null&&(n[t]instanceof D?n[t].copy(i):n[t]=i)}}class df{constructor(e,t,i,r,a){this.width=e,this.expTerm=t,this.expScale=i,this.linearTerm=r,this.constantTerm=a}toUniform(){return new $({width:this.width,exp_term:this.expTerm,exp_scale:this.expScale,linear_term:this.linearTerm,constant_term:this.constantTerm})}}const EA=class{constructor(e){this.solarIrradiance=new D(1.474,1.8504,1.91198),this.sunAngularRadius=.004675,this.bottomRadius=636e4,this.topRadius=642e4,this.rayleighDensity=[new df(0,0,0,0,0),new df(0,1,-.125,0,0)],this.rayleighScattering=new D(.005802,.013558,.0331),this.mieDensity=[new df(0,0,0,0,0),new df(0,1,-.833333,0,0)],this.mieScattering=new D(.003996,.003996,.003996),this.mieExtinction=new D(.00444,.00444,.00444),this.miePhaseFunctionG=.8,this.absorptionDensity=[new df(25,0,0,1/15,-2/3),new df(0,0,0,-1/15,8/3)],this.absorptionExtinction=new D(65e-5,.001881,85e-6),this.groundAlbedo=new Ye().setScalar(.1),this.muSMin=Math.cos(oh(120)),this.sunRadianceToLuminance=new D(98242.786222,69954.398112,66475.012354),this.skyRadianceToLuminance=new D(114974.916437,71305.954816,65310.548555),this.sunRadianceToRelativeLuminance=new D,this.skyRadianceToRelativeLuminance=new D,Vse(this,e);const t=Fse.dot(this.sunRadianceToLuminance);this.sunRadianceToRelativeLuminance.copy(this.sunRadianceToLuminance).divideScalar(t),this.skyRadianceToRelativeLuminance.copy(this.skyRadianceToLuminance).divideScalar(t)}toUniform(){return new $({solar_irradiance:this.solarIrradiance,sun_angular_radius:this.sunAngularRadius,bottom_radius:this.bottomRadius*Ky,top_radius:this.topRadius*Ky,rayleigh_density:{layers:this.rayleighDensity.map(e=>e.toUniform().value)},rayleigh_scattering:this.rayleighScattering,mie_density:{layers:this.mieDensity.map(e=>e.toUniform().value)},mie_scattering:this.mieScattering,mie_extinction:this.mieExtinction,mie_phase_function_g:this.miePhaseFunctionG,absorption_density:{layers:this.absorptionDensity.map(e=>e.toUniform().value)},absorption_extinction:this.absorptionExtinction,ground_albedo:this.groundAlbedo,mu_s_min:this.muSMin})}};EA.DEFAULT=new EA;let mv=EA;const Gse=`precision highp sampler2DArray; + +#include "core/depth" +#include "core/math" +#include "core/packing" +#include "core/transform" +#ifdef HAS_SHADOW +#include "core/raySphereIntersection" +#include "core/cascadedShadowMaps" +#include "core/interleavedGradientNoise" +#include "core/vogelDisk" +#endif // HAS_SHADOW + +#include "bruneton/definitions" + +uniform AtmosphereParameters ATMOSPHERE; +uniform vec3 SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; +uniform vec3 SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; + +uniform sampler2D transmittance_texture; +uniform sampler3D scattering_texture; +uniform sampler2D irradiance_texture; +uniform sampler3D single_mie_scattering_texture; +uniform sampler3D higher_order_scattering_texture; + +#include "bruneton/common" +#include "bruneton/runtime" + +#include "sky" + +uniform sampler2D normalBuffer; + +uniform mat4 projectionMatrix; +uniform mat4 viewMatrix; +uniform mat4 inverseProjectionMatrix; +uniform mat4 inverseViewMatrix; +uniform float bottomRadius; +uniform mat4 worldToECEFMatrix; +uniform float geometricErrorCorrectionAmount; +uniform vec3 sunDirection; +uniform vec3 moonDirection; +uniform float moonAngularRadius; +uniform float lunarRadianceScale; +uniform float albedoScale; + +#ifdef HAS_LIGHTING_MASK +uniform sampler2D lightingMaskBuffer; +#endif // HAS_LIGHTING_MASK + +// prettier-ignore +#define LIGHTING_MASK_CHANNEL_ LIGHTING_MASK_CHANNEL + +#ifdef HAS_OVERLAY +uniform sampler2D overlayBuffer; +#endif // HAS_OVERLAY + +#ifdef HAS_SHADOW +uniform sampler2DArray shadowBuffer; +uniform vec2 shadowIntervals[SHADOW_CASCADE_COUNT]; +uniform mat4 shadowMatrices[SHADOW_CASCADE_COUNT]; +uniform mat4 inverseShadowMatrices[SHADOW_CASCADE_COUNT]; +uniform float shadowFar; +uniform float shadowTopHeight; +uniform float shadowRadius; +uniform sampler3D stbnTexture; +uniform int frame; +#endif // HAS_SHADOW + +#ifdef HAS_SHADOW_LENGTH +uniform sampler2D shadowLengthBuffer; +#endif // HAS_SHADOW_LENGTH + +varying vec3 vCameraPosition; +varying vec3 vRayDirection; +varying vec3 vGeometryAltitudeCorrection; +varying vec3 vEllipsoidRadiiSquared; + +vec3 readNormal(const vec2 uv) { + #ifdef OCT_ENCODED_NORMAL + return unpackVec2ToNormal(texture(normalBuffer, uv).xy); + #else // OCT_ENCODED_NORMAL + return 2.0 * texture(normalBuffer, uv).xyz - 1.0; + #endif // OCT_ENCODED_NORMAL +} + +void correctGeometricError(inout vec3 positionECEF, inout vec3 normalECEF) { + // TODO: The error is pronounced at the edge of the ellipsoid due to the + // large difference between the sphere position and the unprojected position + // at the current fragment. Calculating the sphere position from the fragment + // UV may resolve this. + + // Correct way is slerp, but this will be small-angle interpolation anyways. + vec3 sphereNormal = normalize(positionECEF / vEllipsoidRadiiSquared); + vec3 spherePosition = ATMOSPHERE.bottom_radius * sphereNormal; + normalECEF = mix(normalECEF, sphereNormal, geometricErrorCorrectionAmount); + positionECEF = mix(positionECEF, spherePosition, geometricErrorCorrectionAmount); +} + +#if defined(SUN_LIGHT) || defined(SKY_LIGHT) + +vec3 getSunSkyIrradiance( + const vec3 positionECEF, + const vec3 normal, + const vec3 inputColor, + const float sunTransmittance +) { + // Assume lambertian BRDF. If both SUN_LIGHT and SKY_LIGHT are not defined, + // regard the inputColor as radiance at the texel. + vec3 diffuse = inputColor * albedoScale * RECIPROCAL_PI; + vec3 skyIrradiance; + vec3 sunIrradiance = GetSunAndSkyIrradiance(positionECEF, normal, sunDirection, skyIrradiance); + + #ifdef HAS_SHADOW + sunIrradiance *= sunTransmittance; + #endif // HAS_SHADOW + + #if defined(SUN_LIGHT) && defined(SKY_LIGHT) + return diffuse * (sunIrradiance + skyIrradiance); + #elif defined(SUN_LIGHT) + return diffuse * sunIrradiance; + #elif defined(SKY_LIGHT) + return diffuse * skyIrradiance; + #endif // defined(SUN_LIGHT) && defined(SKY_LIGHT) +} + +#endif // defined(SUN_LIGHT) || defined(SKY_LIGHT) + +#if defined(TRANSMITTANCE) || defined(INSCATTER) + +void applyTransmittanceInscatter(const vec3 positionECEF, float shadowLength, inout vec3 radiance) { + vec3 transmittance; + vec3 inscatter = GetSkyRadianceToPoint( + vCameraPosition, + positionECEF, + shadowLength, + sunDirection, + transmittance + ); + #ifdef TRANSMITTANCE + radiance = radiance * transmittance; + #endif // TRANSMITTANCE + #ifdef INSCATTER + radiance = radiance + inscatter; + #endif // INSCATTER +} + +#endif // defined(TRANSMITTANCE) || defined(INSCATTER) + +#ifdef HAS_SHADOW + +float getSTBN() { + ivec3 size = textureSize(stbnTexture, 0); + vec3 scale = 1.0 / vec3(size); + return texture(stbnTexture, vec3(gl_FragCoord.xy, float(frame % size.z)) * scale).r; +} + +vec2 getShadowUv(const vec3 worldPosition, const int cascadeIndex) { + vec4 clip = shadowMatrices[cascadeIndex] * vec4(worldPosition, 1.0); + clip /= clip.w; + return clip.xy * 0.5 + 0.5; +} + +float getDistanceToShadowTop(const vec3 positionECEF) { + // Distance to the top of the shadows along the sun direction, which matches + // the ray origin of BSM. + return raySphereSecondIntersection( + positionECEF / METER_TO_LENGTH_UNIT, // TODO: Make units consistent + sunDirection, + vec3(0.0), + bottomRadius + shadowTopHeight + ); +} + +float readShadowOpticalDepth(const vec2 uv, const float distanceToTop, const int cascadeIndex) { + // r: frontDepth, g: meanExtinction, b: maxOpticalDepth, a: maxOpticalDepthTail + vec4 shadow = texture(shadowBuffer, vec3(uv, float(cascadeIndex))); + // Omit adding maxOpticalDepthTail to avoid pronounced aliasing. Ground + // shadow will be attenuated by inscatter anyways. + return min(shadow.b, shadow.g * max(0.0, distanceToTop - shadow.r)); +} + +float sampleShadowOpticalDepthPCF( + const vec3 worldPosition, + const float distanceToTop, + const float radius, + const int cascadeIndex +) { + vec2 uv = getShadowUv(worldPosition, cascadeIndex); + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { + return 0.0; + } + + vec2 texelSize = vec2(1.0) / vec2(textureSize(shadowBuffer, 0).xy); + float sum = 0.0; + vec2 offset; + #pragma unroll_loop_start + for (int i = 0; i < 16; ++i) { + #if UNROLLED_LOOP_INDEX < SHADOW_SAMPLE_COUNT + offset = vogelDisk( + UNROLLED_LOOP_INDEX, + SHADOW_SAMPLE_COUNT, + interleavedGradientNoise(gl_FragCoord.xy) * PI2 + ); + sum += readShadowOpticalDepth(uv + offset * radius * texelSize, distanceToTop, cascadeIndex); + #endif // UNROLLED_LOOP_INDEX < SHADOW_SAMPLE_COUNT + } + #pragma unroll_loop_end + return sum / float(SHADOW_SAMPLE_COUNT); +} + +float sampleShadowOpticalDepth( + const vec3 worldPosition, + const vec3 positionECEF, + const float radius, + const float jitter +) { + float distanceToTop = getDistanceToShadowTop(positionECEF); + if (distanceToTop <= 0.0) { + return 0.0; + } + int cascadeIndex = getFadedCascadeIndex( + viewMatrix, + worldPosition, + shadowIntervals, + cameraNear, + shadowFar, + jitter + ); + return cascadeIndex >= 0 + ? sampleShadowOpticalDepthPCF(worldPosition, distanceToTop, radius, cascadeIndex) + : 0.0; +} + +float getShadowRadius(const vec3 worldPosition) { + vec4 clip = shadowMatrices[0] * vec4(worldPosition, 1.0); + clip /= clip.w; + + // Offset by 1px in each direction in shadow's clip coordinates. + vec2 shadowSize = vec2(textureSize(shadowBuffer, 0)); + vec3 offset = vec3(2.0 / shadowSize, 0.0); + vec4 clipX = clip + offset.xzzz; + vec4 clipY = clip + offset.zyzz; + + // Convert back to world space. + vec4 worldX = inverseShadowMatrices[0] * clipX; + vec4 worldY = inverseShadowMatrices[0] * clipY; + + // Project into the main camera's clip space. + mat4 viewProjectionMatrix = projectionMatrix * viewMatrix; + vec4 projected = viewProjectionMatrix * vec4(worldPosition, 1.0); + vec4 projectedX = viewProjectionMatrix * worldX; + vec4 projectedY = viewProjectionMatrix * worldY; + projected /= projected.w; + projectedX /= projectedX.w; + projectedY /= projectedY.w; + + // Take the mean of pixel sizes. + vec2 center = (projected.xy * 0.5 + 0.5) * resolution; + vec2 offsetX = (projectedX.xy * 0.5 + 0.5) * resolution; + vec2 offsetY = (projectedY.xy * 0.5 + 0.5) * resolution; + float size = max(length(offsetX - center), length(offsetY - center)); + + return remapClamped(size, 10.0, 50.0, 0.0, shadowRadius); +} + +#endif // HAS_SHADOW + +void mainImage(const vec4 inputColor, const vec2 uv, out vec4 outputColor) { + #if defined(HAS_LIGHTING_MASK) && defined(DEBUG_SHOW_LIGHTING_MASK) + outputColor.rgb = vec3(texture(lightingMaskBuffer, uv).LIGHTING_MASK_CHANNEL_); + outputColor.a = 1.0; + return; + #endif // defined(HAS_LIGHTING_MASK) && defined(DEBUG_SHOW_LIGHTING_MASK) + + float shadowLength = 0.0; + #ifdef HAS_SHADOW_LENGTH + shadowLength = texture(shadowLengthBuffer, uv).r; + #endif // HAS_SHADOW_LENGTH + + #ifdef HAS_OVERLAY + vec4 overlay = texture(overlayBuffer, uv); + if (overlay.a == 1.0) { + outputColor = overlay; + return; + } + #endif // HAS_OVERLAY + + float depth = readDepth(uv); + if (depth >= 1.0 - 1e-8) { + #ifdef SKY + vec3 rayDirection = normalize(vRayDirection); + outputColor.rgb = getSkyRadiance( + vCameraPosition, + rayDirection, + shadowLength, + sunDirection, + moonDirection, + moonAngularRadius, + lunarRadianceScale + ); + outputColor.a = 1.0; + #else // SKY + outputColor = inputColor; + #endif // SKY + + #ifdef HAS_OVERLAY + outputColor.rgb = outputColor.rgb * (1.0 - overlay.a) + overlay.rgb; + #endif // HAS_OVERLAY + return; + } + depth = reverseLogDepth(depth, cameraNear, cameraFar); + + // Reconstruct position and normal in world space. + vec3 viewPosition = screenToView( + uv, + depth, + getViewZ(depth), + projectionMatrix, + inverseProjectionMatrix + ); + vec3 viewNormal; + #ifdef RECONSTRUCT_NORMAL + vec3 dx = dFdx(viewPosition); + vec3 dy = dFdy(viewPosition); + viewNormal = normalize(cross(dx, dy)); + #else // RECONSTRUCT_NORMAL + viewNormal = readNormal(uv); + #endif // RECONSTRUCT_NORMAL + + vec3 worldPosition = (inverseViewMatrix * vec4(viewPosition, 1.0)).xyz; + vec3 worldNormal = (inverseViewMatrix * vec4(viewNormal, 0.0)).xyz; + vec3 positionECEF = (worldToECEFMatrix * vec4(worldPosition, 1.0)).xyz; + positionECEF = positionECEF * METER_TO_LENGTH_UNIT + vGeometryAltitudeCorrection; + vec3 normalECEF = (worldToECEFMatrix * vec4(worldNormal, 0.0)).xyz; + + #ifdef CORRECT_GEOMETRIC_ERROR + correctGeometricError(positionECEF, normalECEF); + #endif // CORRECT_GEOMETRIC_ERROR + + #ifdef HAS_SHADOW + float stbn = getSTBN(); + float radius = getShadowRadius(worldPosition); + float opticalDepth = sampleShadowOpticalDepth(worldPosition, positionECEF, radius, stbn); + float sunTransmittance = exp(-opticalDepth); + #else // HAS_SHADOW + float sunTransmittance = 1.0; + #endif // HAS_SHADOW + + vec3 radiance; + #if defined(SUN_LIGHT) || defined(SKY_LIGHT) + radiance = getSunSkyIrradiance(positionECEF, normalECEF, inputColor.rgb, sunTransmittance); + #ifdef HAS_LIGHTING_MASK + float lightingMask = texture(lightingMaskBuffer, uv).LIGHTING_MASK_CHANNEL_; + radiance = mix(inputColor.rgb, radiance, lightingMask); + #endif // HAS_LIGHTING_MASK + #else // defined(SUN_LIGHT) || defined(SKY_LIGHT) + radiance = inputColor.rgb; + #endif // defined(SUN_LIGHT) || defined(SKY_LIGHT) + + #if defined(TRANSMITTANCE) || defined(INSCATTER) + applyTransmittanceInscatter(positionECEF, shadowLength, radiance); + #endif // defined(TRANSMITTANCE) || defined(INSCATTER) + + outputColor = vec4(radiance, inputColor.a); + + #ifdef HAS_OVERLAY + outputColor.rgb = outputColor.rgb * (1.0 - overlay.a) + overlay.rgb; + #endif // HAS_OVERLAY +} +`,kse=`uniform mat4 inverseViewMatrix; +uniform mat4 inverseProjectionMatrix; +uniform vec3 cameraPosition; +uniform mat4 worldToECEFMatrix; +uniform vec3 altitudeCorrection; +uniform float geometricErrorCorrectionAmount; +uniform vec3 ellipsoidRadii; + +varying vec3 vCameraPosition; +varying vec3 vRayDirection; +varying vec3 vGeometryAltitudeCorrection; +varying vec3 vEllipsoidRadiiSquared; + +void getCameraRay(out vec3 origin, out vec3 direction) { + bool isPerspective = inverseProjectionMatrix[2][3] != 0.0; // 4th entry in the 3rd column + + if (isPerspective) { + // Calculate the camera ray for a perspective camera. + vec4 viewPosition = inverseProjectionMatrix * vec4(position, 1.0); + vec4 worldDirection = inverseViewMatrix * vec4(viewPosition.xyz, 0.0); + origin = cameraPosition; + direction = worldDirection.xyz; + } else { + // Unprojected points to calculate direction. + vec4 nearPoint = inverseProjectionMatrix * vec4(position.xy, -1.0, 1.0); + vec4 farPoint = inverseProjectionMatrix * vec4(position.xy, -0.9, 1.0); + nearPoint /= nearPoint.w; + farPoint /= farPoint.w; + + // Calculate world values. + vec4 worldDirection = inverseViewMatrix * vec4(farPoint.xyz - nearPoint.xyz, 0.0); + vec4 worldOrigin = inverseViewMatrix * nearPoint; + + // Outputs + direction = worldDirection.xyz; + origin = worldOrigin.xyz; + } +} + +void mainSupport() { + vec3 direction, origin; + getCameraRay(origin, direction); + + vec3 cameraPositionECEF = (worldToECEFMatrix * vec4(origin, 1.0)).xyz; + vCameraPosition = (cameraPositionECEF + altitudeCorrection) * METER_TO_LENGTH_UNIT; + vRayDirection = (worldToECEFMatrix * vec4(direction, 0.0)).xyz; + + vGeometryAltitudeCorrection = altitudeCorrection * METER_TO_LENGTH_UNIT; + // Gradually turn off the altitude correction on geometries as the geometric + // error correction takes effect, because that on the ideal sphere will be + // over corrected. + // See: https://github.com/takram-design-engineering/three-geospatial/pull/23#issuecomment-2542914656 + #ifdef CORRECT_GEOMETRIC_ERROR + vGeometryAltitudeCorrection *= 1.0 - geometricErrorCorrectionAmount; + #endif // CORRECT_GEOMETRIC_ERROR + + vec3 radii = ellipsoidRadii * METER_TO_LENGTH_UNIT; + vEllipsoidRadiiSquared = radii * radii; +} +`,NB=`vec3 getLunarRadiance(const float moonAngularRadius) { + // Not a physical number but the order of 10^-6 relative to the sun may fit. + vec3 radiance = + ATMOSPHERE.solar_irradiance * + 0.000002 / + (PI * moonAngularRadius * moonAngularRadius) * + SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; + return radiance; +} + +float intersectSphere(const vec3 ray, const vec3 point, const float radius) { + vec3 P = -point; + float PoR = dot(P, ray); + float D = dot(P, P) - radius * radius; + return -PoR - sqrt(PoR * PoR - D); +} + +float orenNayarDiffuse(const vec3 L, const vec3 V, const vec3 N) { + float NoL = dot(N, L); + float NoV = dot(N, V); + float s = dot(L, V) - NoL * NoV; + float t = mix(1.0, max(NoL, NoV), step(0.0, s)); + return max(0.0, NoL) * (0.62406015 + 0.41284404 * s / t); +} + +vec3 getSkyRadiance( + const vec3 cameraPosition, + const vec3 rayDirection, + const float shadowLength, + const vec3 sunDirection, + const vec3 moonDirection, + const float moonAngularRadius, + const float lunarRadianceScale +) { + vec3 transmittance; + vec3 radiance = GetSkyRadiance( + cameraPosition, + rayDirection, + shadowLength, + sunDirection, + transmittance + ); + + // Rendering celestial objects without perspective doesn't make sense. + #ifdef PERSPECTIVE_CAMERA + + #if defined(SUN) || defined(MOON) + vec3 ddx = dFdx(rayDirection); + vec3 ddy = dFdy(rayDirection); + float fragmentAngle = length(ddx + ddy) / length(rayDirection); + #endif // defined(SUN) || defined(MOON) + + #ifdef SUN + float viewDotSun = dot(rayDirection, sunDirection); + if (viewDotSun > cos(ATMOSPHERE.sun_angular_radius)) { + float angle = acos(clamp(viewDotSun, -1.0, 1.0)); + float antialias = smoothstep( + ATMOSPHERE.sun_angular_radius, + ATMOSPHERE.sun_angular_radius - fragmentAngle, + angle + ); + radiance += transmittance * GetSolarRadiance() * antialias; + } + #endif // SUN + + #ifdef MOON + float intersection = intersectSphere(rayDirection, moonDirection, moonAngularRadius); + if (intersection > 0.0) { + vec3 normal = normalize(moonDirection - rayDirection * intersection); + float diffuse = orenNayarDiffuse(-sunDirection, rayDirection, normal); + float viewDotMoon = dot(rayDirection, moonDirection); + float angle = acos(clamp(viewDotMoon, -1.0, 1.0)); + float antialias = smoothstep(moonAngularRadius, moonAngularRadius - fragmentAngle, angle); + radiance += + transmittance * + getLunarRadiance(moonAngularRadius) * + lunarRadianceScale * + diffuse * + antialias; + } + #endif // MOON + + #endif // PERSPECTIVE_CAMERA + + return radiance; +} +`;var Wse=Object.defineProperty,xa=(n,e,t,i)=>{for(var r=void 0,a=n.length-1,s;a>=0;a--)(s=n[a])&&(r=s(e,t,r)||r);return r&&Wse(e,t,r),r};const Xse=new D,qse=new D,Yse=new Pg,OB={blendFunction:cn.NORMAL,octEncodedNormal:!1,reconstructNormal:!1,ellipsoid:kh.WGS84,correctAltitude:!0,correctGeometricError:!0,sunLight:!1,skyLight:!1,transmittance:!0,inscatter:!0,albedoScale:1,sky:!1,sun:!0,moon:!0,moonAngularRadius:.0045,lunarRadianceScale:1,ground:!0};let Kr=class extends Ug{constructor(e=new ou,t,i=mv.DEFAULT){const{blendFunction:r,normalBuffer:a=null,octEncodedNormal:s,reconstructNormal:o,irradianceTexture:l=null,scatteringTexture:u=null,transmittanceTexture:d=null,singleMieScatteringTexture:f=null,higherOrderScatteringTexture:p=null,ellipsoid:m,correctAltitude:v,correctGeometricError:x,sunDirection:S,sunIrradiance:_,sunLight:T,skyIrradiance:E,skyLight:b,transmittance:R,inscatter:w,irradianceScale:L,albedoScale:U,sky:N,sun:C,moon:z,moonDirection:W,moonAngularRadius:K,lunarRadianceScale:oe,ground:ae}={...OB,...t};super("AerialPerspectiveEffect",pv(Wr(Gse,{core:{depth:wB,packing:Ise,math:QR,transform:Use,raySphereIntersection:_T,cascadedShadowMaps:AB,interleavedGradientNoise:RB,vogelDisk:DB},bruneton:{common:To,definitions:Eo,runtime:ET},sky:NB})),{blendFunction:r,vertexShader:kse,attributes:Dl.DEPTH,uniforms:new Map(Object.entries({normalBuffer:new $(a),projectionMatrix:new $(new Me),viewMatrix:new $(new Me),inverseProjectionMatrix:new $(new Me),inverseViewMatrix:new $(new Me),cameraPosition:new $(new D),bottomRadius:new $(i.bottomRadius),ellipsoidRadii:new $(new D),worldToECEFMatrix:new $(new Me),altitudeCorrection:new $(new D),geometricErrorCorrectionAmount:new $(0),sunDirection:new $((S==null?void 0:S.clone())??new D),albedoScale:new $(L??U),moonDirection:new $((W==null?void 0:W.clone())??new D),moonAngularRadius:new $(K),lunarRadianceScale:new $(oe),overlayBuffer:new $(null),shadowBuffer:new $(null),shadowMapSize:new $(new re),shadowIntervals:new $([]),shadowMatrices:new $([]),inverseShadowMatrices:new $([]),shadowFar:new $(0),shadowTopHeight:new $(0),shadowRadius:new $(3),stbnTexture:new $(null),frame:new $(0),shadowLengthBuffer:new $(null),lightingMaskBuffer:new $(null),ATMOSPHERE:i.toUniform(),SUN_SPECTRAL_RADIANCE_TO_LUMINANCE:new $(i.sunRadianceToRelativeLuminance),SKY_SPECTRAL_RADIANCE_TO_LUMINANCE:new $(i.skyRadianceToRelativeLuminance),irradiance_texture:new $(l),scattering_texture:new $(u),transmittance_texture:new $(d),single_mie_scattering_texture:new $(null),higher_order_scattering_texture:new $(null)})),defines:new Map([["TRANSMITTANCE_TEXTURE_WIDTH",rm.toFixed(0)],["TRANSMITTANCE_TEXTURE_HEIGHT",am.toFixed(0)],["SCATTERING_TEXTURE_R_SIZE",xT.toFixed(0)],["SCATTERING_TEXTURE_MU_SIZE",yT.toFixed(0)],["SCATTERING_TEXTURE_MU_S_SIZE",ST.toFixed(0)],["SCATTERING_TEXTURE_NU_SIZE",TT.toFixed(0)],["IRRADIANCE_TEXTURE_WIDTH",nm.toFixed(0)],["IRRADIANCE_TEXTURE_HEIGHT",im.toFixed(0)],["METER_TO_LENGTH_UNIT",Ky.toFixed(7)]])}),this.camera=e,this.atmosphere=i,this.overlay=null,this.shadow=null,this.shadowLength=null,this.lightingMask=null,this.combinedScatteringTextures=!1,this.hasHigherOrderScatteringTexture=!1,this.shadowSampleCount=8,this.octEncodedNormal=s,this.reconstructNormal=o,this.singleMieScatteringTexture=f,this.higherOrderScatteringTexture=p,this.ellipsoid=m,this.correctAltitude=v,this.correctGeometricError=x,this.sunLight=_??T,this.skyLight=E??b,this.transmittance=R,this.inscatter=w,this.sky=N,this.sun=C,this.moon=z,this.ground=ae}get mainCamera(){return this.camera}set mainCamera(e){this.camera=e}copyCameraSettings(e){const{projectionMatrix:t,matrixWorldInverse:i,projectionMatrixInverse:r,matrixWorld:a}=e,s=this.uniforms;s.get("projectionMatrix").value.copy(t),s.get("viewMatrix").value.copy(i),s.get("inverseProjectionMatrix").value.copy(r),s.get("inverseViewMatrix").value.copy(a);const o=e.getWorldPosition(s.get("cameraPosition").value),l=s.get("worldToECEFMatrix").value,u=Xse.copy(o).applyMatrix4(l);try{const f=Yse.setFromECEF(u).height,p=qse.set(0,this.ellipsoid.maximumRadius,-Math.max(0,f)).applyMatrix4(t);s.get("geometricErrorCorrectionAmount").value=dse(hse(p.y,41.5,13.8,0,1))}catch{return}const d=s.get("altitudeCorrection");this.correctAltitude?KR(u,this.atmosphere.bottomRadius,this.ellipsoid,d.value):d.value.setScalar(0)}updateOverlay(){let e=!1;const{uniforms:t,defines:i,overlay:r}=this,a=i.has("HAS_OVERLAY"),s=r!=null;return s!==a&&(s?i.set("HAS_OVERLAY","1"):(i.delete("HAS_OVERLAY"),t.get("overlayBuffer").value=null),e=!0),s&&(t.get("overlayBuffer").value=r.map),e}updateShadow(){let e=!1;const{uniforms:t,defines:i,shadow:r}=this,a=i.has("HAS_SHADOW"),s=r!=null;if(s!==a&&(s?i.set("HAS_SHADOW","1"):(i.delete("HAS_SHADOW"),t.get("shadowBuffer").value=null),e=!0),s){const o=i.get("SHADOW_CASCADE_COUNT"),l=`${r.cascadeCount}`;o!==l&&(i.set("SHADOW_CASCADE_COUNT",r.cascadeCount.toFixed(0)),e=!0),t.get("shadowBuffer").value=r.map,t.get("shadowMapSize").value=r.mapSize,t.get("shadowIntervals").value=r.intervals,t.get("shadowMatrices").value=r.matrices,t.get("inverseShadowMatrices").value=r.inverseMatrices,t.get("shadowFar").value=r.far,t.get("shadowTopHeight").value=r.topHeight}return e}updateShadowLength(){let e=!1;const{uniforms:t,defines:i,shadowLength:r}=this,a=i.has("HAS_SHADOW_LENGTH"),s=r!=null;return s!==a&&(s?i.set("HAS_SHADOW_LENGTH","1"):(i.delete("HAS_SHADOW_LENGTH"),t.get("shadowLengthBuffer").value=null),e=!0),s&&(t.get("shadowLengthBuffer").value=r.map),e}updateLightingMask(){let e=!1;const{uniforms:t,defines:i,lightingMask:r}=this,a=i.has("HAS_LIGHTING_MASK"),s=r!=null;if(s!==a&&(s?i.set("HAS_LIGHTING_MASK","1"):(i.delete("HAS_LIGHTING_MASK"),t.get("lightingMaskBuffer").value=null),e=!0),s){t.get("lightingMaskBuffer").value=r.map;const o=i.get("LIGHTING_MASK_CHANNEL"),l=r.channel;l!==o&&(/^[rgba]$/.test(l)?(i.set("LIGHTING_MASK_CHANNEL",l),e=!0):console.error(`Expression validation failed: ${l}`))}return e}update(e,t,i){this.copyCameraSettings(this.camera);let r=!1;r||(r=this.updateOverlay()),r||(r=this.updateShadow()),r||(r=this.updateShadowLength()),r||(r=this.updateLightingMask()),r&&this.setChanged(),++this.uniforms.get("frame").value}get normalBuffer(){return this.uniforms.get("normalBuffer").value}set normalBuffer(e){this.uniforms.get("normalBuffer").value=e}get irradianceTexture(){return this.uniforms.get("irradiance_texture").value}set irradianceTexture(e){this.uniforms.get("irradiance_texture").value=e}get scatteringTexture(){return this.uniforms.get("scattering_texture").value}set scatteringTexture(e){this.uniforms.get("scattering_texture").value=e}get transmittanceTexture(){return this.uniforms.get("transmittance_texture").value}set transmittanceTexture(e){this.uniforms.get("transmittance_texture").value=e}get singleMieScatteringTexture(){return this.uniforms.get("single_mie_scattering_texture").value}set singleMieScatteringTexture(e){this.uniforms.get("single_mie_scattering_texture").value=e,this.combinedScatteringTextures=e==null}get higherOrderScatteringTexture(){return this.uniforms.get("higher_order_scattering_texture").value}set higherOrderScatteringTexture(e){this.uniforms.get("higher_order_scattering_texture").value=e,this.hasHigherOrderScatteringTexture=e!=null}get ellipsoid(){return this._ellipsoid}set ellipsoid(e){this._ellipsoid=e,this.uniforms.get("ellipsoidRadii").value.copy(e.radii)}get worldToECEFMatrix(){return this.uniforms.get("worldToECEFMatrix").value}get sunDirection(){return this.uniforms.get("sunDirection").value}get sunIrradiance(){return this.sunLight}set sunIrradiance(e){this.sunLight=e}get skyIrradiance(){return this.skyLight}set skyIrradiance(e){this.skyLight=e}get irradianceScale(){return this.albedoScale}set irradianceScale(e){this.albedoScale=e}get albedoScale(){return this.uniforms.get("albedoScale").value}set albedoScale(e){this.uniforms.get("albedoScale").value=e}get moonDirection(){return this.uniforms.get("moonDirection").value}get moonAngularRadius(){return this.uniforms.get("moonAngularRadius").value}set moonAngularRadius(e){this.uniforms.get("moonAngularRadius").value=e}get lunarRadianceScale(){return this.uniforms.get("lunarRadianceScale").value}set lunarRadianceScale(e){this.uniforms.get("lunarRadianceScale").value=e}get stbnTexture(){return this.uniforms.get("stbnTexture").value}set stbnTexture(e){this.uniforms.get("stbnTexture").value=e}get shadowRadius(){return this.uniforms.get("shadowRadius").value}set shadowRadius(e){this.uniforms.get("shadowRadius").value=e}};xa([gn("OCT_ENCODED_NORMAL")],Kr.prototype,"octEncodedNormal");xa([gn("RECONSTRUCT_NORMAL")],Kr.prototype,"reconstructNormal");xa([gn("COMBINED_SCATTERING_TEXTURES")],Kr.prototype,"combinedScatteringTextures");xa([gn("HAS_HIGHER_ORDER_SCATTERING_TEXTURE")],Kr.prototype,"hasHigherOrderScatteringTexture");xa([gn("CORRECT_GEOMETRIC_ERROR")],Kr.prototype,"correctGeometricError");xa([gn("SUN_LIGHT")],Kr.prototype,"sunLight");xa([gn("SKY_LIGHT")],Kr.prototype,"skyLight");xa([gn("TRANSMITTANCE")],Kr.prototype,"transmittance");xa([gn("INSCATTER")],Kr.prototype,"inscatter");xa([gn("SKY")],Kr.prototype,"sky");xa([gn("SUN")],Kr.prototype,"sun");xa([gn("MOON")],Kr.prototype,"moon");xa([gn("GROUND")],Kr.prototype,"ground");xa([ad("SHADOW_SAMPLE_COUNT",{min:1,max:16})],Kr.prototype,"shadowSampleCount");var jse=Object.defineProperty,LB=(n,e,t,i)=>{for(var r=void 0,a=n.length-1,s;a>=0;a--)(s=n[a])&&(r=s(e,t,r)||r);return r&&jse(e,t,r),r};const Zse=new D;function Qse(n,e){let t="",i="";for(let r=1;r",t).replace("#include ",i)}const JR={ellipsoid:kh.WGS84,correctAltitude:!0,renderTargetCount:1};let gv=class extends td{constructor(e,t=mv.DEFAULT){const{irradianceTexture:i=null,scatteringTexture:r=null,transmittanceTexture:a=null,singleMieScatteringTexture:s=null,higherOrderScatteringTexture:o=null,ellipsoid:l,correctAltitude:u,sunDirection:d,sunAngularRadius:f,renderTargetCount:p,...m}={...JR,...e};super({toneMapped:!1,depthWrite:!1,depthTest:!1,...m,uniforms:{cameraPosition:new $(new D),worldToECEFMatrix:new $(new Me),altitudeCorrection:new $(new D),sunDirection:new $((d==null?void 0:d.clone())??new D),ATMOSPHERE:t.toUniform(),SUN_SPECTRAL_RADIANCE_TO_LUMINANCE:new $(t.sunRadianceToRelativeLuminance),SKY_SPECTRAL_RADIANCE_TO_LUMINANCE:new $(t.skyRadianceToRelativeLuminance),irradiance_texture:new $(i),scattering_texture:new $(r),transmittance_texture:new $(a),single_mie_scattering_texture:new $(null),higher_order_scattering_texture:new $(null),...m.uniforms},defines:{PI:`${Math.PI}`,TRANSMITTANCE_TEXTURE_WIDTH:rm.toFixed(0),TRANSMITTANCE_TEXTURE_HEIGHT:am.toFixed(0),SCATTERING_TEXTURE_R_SIZE:xT.toFixed(0),SCATTERING_TEXTURE_MU_SIZE:yT.toFixed(0),SCATTERING_TEXTURE_MU_S_SIZE:ST.toFixed(0),SCATTERING_TEXTURE_NU_SIZE:TT.toFixed(0),IRRADIANCE_TEXTURE_WIDTH:nm.toFixed(0),IRRADIANCE_TEXTURE_HEIGHT:im.toFixed(0),METER_TO_LENGTH_UNIT:Ky.toFixed(7),...m.defines}}),this.atmosphere=t,this.combinedScatteringTextures=!1,this.hasHigherOrderScatteringTexture=!1,this.singleMieScatteringTexture=s,this.higherOrderScatteringTexture=o,this.ellipsoid=l,this.correctAltitude=u,f!=null&&(this.sunAngularRadius=f),this.renderTargetCount=p}copyCameraSettings(e){const t=this.uniforms,i=e.getWorldPosition(t.cameraPosition.value),r=Zse.copy(i).applyMatrix4(t.worldToECEFMatrix.value),a=t.altitudeCorrection.value;this.correctAltitude?KR(r,this.atmosphere.bottomRadius,this.ellipsoid,a):a.setScalar(0)}onBeforeCompile(e,t){e.fragmentShader=Qse(e.fragmentShader,this.renderTargetCount)}onBeforeRender(e,t,i,r,a,s){this.copyCameraSettings(i)}get irradianceTexture(){return this.uniforms.irradiance_texture.value}set irradianceTexture(e){this.uniforms.irradiance_texture.value=e}get scatteringTexture(){return this.uniforms.scattering_texture.value}set scatteringTexture(e){this.uniforms.scattering_texture.value=e}get transmittanceTexture(){return this.uniforms.transmittance_texture.value}set transmittanceTexture(e){this.uniforms.transmittance_texture.value=e}get singleMieScatteringTexture(){return this.uniforms.single_mie_scattering_texture.value}set singleMieScatteringTexture(e){this.uniforms.single_mie_scattering_texture.value=e,this.combinedScatteringTextures=e==null}get higherOrderScatteringTexture(){return this.uniforms.higher_order_scattering_texture.value}set higherOrderScatteringTexture(e){this.uniforms.higher_order_scattering_texture.value=e,this.hasHigherOrderScatteringTexture=e!=null}get worldToECEFMatrix(){return this.uniforms.worldToECEFMatrix.value}get sunDirection(){return this.uniforms.sunDirection.value}get sunAngularRadius(){return this.uniforms.ATMOSPHERE.value.sun_angular_radius}set sunAngularRadius(e){this.uniforms.ATMOSPHERE.value.sun_angular_radius=e}get renderTargetCount(){return this._renderTargetCount}set renderTargetCount(e){e!==this.renderTargetCount&&(this._renderTargetCount=e,this.needsUpdate=!0)}};LB([gn("COMBINED_SCATTERING_TEXTURES")],gv.prototype,"combinedScatteringTextures");LB([gn("HAS_HIGHER_ORDER_SCATTERING_TEXTURE")],gv.prototype,"hasHigherOrderScatteringTexture");/** + @preserve + + Astronomy library for JavaScript (browser and Node.js). + https://github.com/cosinekitty/astronomy + + MIT License + + Copyright (c) 2019-2023 Don Cross + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*//** + * @fileoverview Astronomy calculation library for browser scripting and Node.js. + * @author Don Cross + * @license MIT + */const Kse=173.1446326846693,Jse=14959787069098932e-8,Xh=.017453292519943295,$se=365.24217,c5=new Date("2000-01-01T12:00:00Z"),gl=2*Math.PI,mc=3600*(180/Math.PI),Wf=484813681109536e-20,eoe=10800*60,toe=2*eoe,noe=6378.1366,ioe=noe/Jse,roe=81.30056,$R=.0002959122082855911,bA=2825345909524226e-22,MA=8459715185680659e-23,AA=1292024916781969e-23,wA=1524358900784276e-23;function m1(n){if(!Number.isFinite(n))throw console.trace(),`Value is not a finite number: ${n}`;return n}function ff(n){return n-Math.floor(n)}var kn;(function(n){n.Sun="Sun",n.Moon="Moon",n.Mercury="Mercury",n.Venus="Venus",n.Earth="Earth",n.Mars="Mars",n.Jupiter="Jupiter",n.Saturn="Saturn",n.Uranus="Uranus",n.Neptune="Neptune",n.Pluto="Pluto",n.SSB="SSB",n.EMB="EMB",n.Star1="Star1",n.Star2="Star2",n.Star3="Star3",n.Star4="Star4",n.Star5="Star5",n.Star6="Star6",n.Star7="Star7",n.Star8="Star8"})(kn||(kn={}));const aoe=[kn.Star1,kn.Star2,kn.Star3,kn.Star4,kn.Star5,kn.Star6,kn.Star7,kn.Star8],soe=[{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0}];function ooe(n){const e=aoe.indexOf(n);return e>=0?soe[e]:null}function IB(n){const e=ooe(n);return e&&e.dist>0?e:null}var Bl;(function(n){n[n.From2000=0]="From2000",n[n.Into2000=1]="Into2000"})(Bl||(Bl={}));const Xf={Mercury:[[[[4.40250710144,0,0],[.40989414977,1.48302034195,26087.9031415742],[.050462942,4.47785489551,52175.8062831484],[.00855346844,1.16520322459,78263.70942472259],[.00165590362,4.11969163423,104351.61256629678],[.00034561897,.77930768443,130439.51570787099],[7583476e-11,3.71348404924,156527.41884944518]],[[26087.90313685529,0,0],[.01131199811,6.21874197797,26087.9031415742],[.00292242298,3.04449355541,52175.8062831484],[.00075775081,6.08568821653,78263.70942472259],[.00019676525,2.80965111777,104351.61256629678]]],[[[.11737528961,1.98357498767,26087.9031415742],[.02388076996,5.03738959686,52175.8062831484],[.01222839532,3.14159265359,0],[.0054325181,1.79644363964,78263.70942472259],[.0012977877,4.83232503958,104351.61256629678],[.00031866927,1.58088495658,130439.51570787099],[7963301e-11,4.60972126127,156527.41884944518]],[[.00274646065,3.95008450011,26087.9031415742],[.00099737713,3.14159265359,0]]],[[[.39528271651,0,0],[.07834131818,6.19233722598,26087.9031415742],[.00795525558,2.95989690104,52175.8062831484],[.00121281764,6.01064153797,78263.70942472259],[.00021921969,2.77820093972,104351.61256629678],[4354065e-11,5.82894543774,130439.51570787099]],[[.0021734774,4.65617158665,26087.9031415742],[.00044141826,1.42385544001,52175.8062831484]]]],Venus:[[[[3.17614666774,0,0],[.01353968419,5.59313319619,10213.285546211],[.00089891645,5.30650047764,20426.571092422],[5477194e-11,4.41630661466,7860.4193924392],[3455741e-11,2.6996444782,11790.6290886588],[2372061e-11,2.99377542079,3930.2096962196],[1317168e-11,5.18668228402,26.2983197998],[1664146e-11,4.25018630147,1577.3435424478],[1438387e-11,4.15745084182,9683.5945811164],[1200521e-11,6.15357116043,30639.856638633]],[[10213.28554621638,0,0],[.00095617813,2.4640651111,10213.285546211],[7787201e-11,.6247848222,20426.571092422]]],[[[.05923638472,.26702775812,10213.285546211],[.00040107978,1.14737178112,20426.571092422],[.00032814918,3.14159265359,0]],[[.00287821243,1.88964962838,10213.285546211]]],[[[.72334820891,0,0],[.00489824182,4.02151831717,10213.285546211],[1658058e-11,4.90206728031,20426.571092422],[1378043e-11,1.12846591367,11790.6290886588],[1632096e-11,2.84548795207,7860.4193924392],[498395e-11,2.58682193892,9683.5945811164],[221985e-11,2.01346696541,19367.1891622328],[237454e-11,2.55136053886,15720.8387848784]],[[.00034551041,.89198706276,10213.285546211]]]],Earth:[[[[1.75347045673,0,0],[.03341656453,4.66925680415,6283.0758499914],[.00034894275,4.62610242189,12566.1516999828],[3417572e-11,2.82886579754,3.523118349],[3497056e-11,2.74411783405,5753.3848848968],[3135899e-11,3.62767041756,77713.7714681205],[2676218e-11,4.41808345438,7860.4193924392],[2342691e-11,6.13516214446,3930.2096962196],[1273165e-11,2.03709657878,529.6909650946],[1324294e-11,.74246341673,11506.7697697936],[901854e-11,2.04505446477,26.2983197998],[1199167e-11,1.10962946234,1577.3435424478],[857223e-11,3.50849152283,398.1490034082],[779786e-11,1.17882681962,5223.6939198022],[99025e-10,5.23268072088,5884.9268465832],[753141e-11,2.53339052847,5507.5532386674],[505267e-11,4.58292599973,18849.2275499742],[492392e-11,4.20505711826,775.522611324],[356672e-11,2.91954114478,.0673103028],[284125e-11,1.89869240932,796.2980068164],[242879e-11,.34481445893,5486.777843175],[317087e-11,5.84901948512,11790.6290886588],[271112e-11,.31486255375,10977.078804699],[206217e-11,4.80646631478,2544.3144198834],[205478e-11,1.86953770281,5573.1428014331],[202318e-11,2.45767790232,6069.7767545534],[126225e-11,1.08295459501,20.7753954924],[155516e-11,.83306084617,213.299095438]],[[6283.0758499914,0,0],[.00206058863,2.67823455808,6283.0758499914],[4303419e-11,2.63512233481,12566.1516999828]],[[8721859e-11,1.07253635559,6283.0758499914]]],[[],[[.00227777722,3.4137662053,6283.0758499914],[3805678e-11,3.37063423795,12566.1516999828]]],[[[1.00013988784,0,0],[.01670699632,3.09846350258,6283.0758499914],[.00013956024,3.05524609456,12566.1516999828],[308372e-10,5.19846674381,77713.7714681205],[1628463e-11,1.17387558054,5753.3848848968],[1575572e-11,2.84685214877,7860.4193924392],[924799e-11,5.45292236722,11506.7697697936],[542439e-11,4.56409151453,3930.2096962196],[47211e-10,3.66100022149,5884.9268465832],[85831e-11,1.27079125277,161000.6857376741],[57056e-11,2.01374292245,83996.84731811189],[55736e-11,5.2415979917,71430.69561812909],[174844e-11,3.01193636733,18849.2275499742],[243181e-11,4.2734953079,11790.6290886588]],[[.00103018607,1.10748968172,6283.0758499914],[1721238e-11,1.06442300386,12566.1516999828]],[[4359385e-11,5.78455133808,6283.0758499914]]]],Mars:[[[[6.20347711581,0,0],[.18656368093,5.0503710027,3340.6124266998],[.01108216816,5.40099836344,6681.2248533996],[.00091798406,5.75478744667,10021.8372800994],[.00027744987,5.97049513147,3.523118349],[.00010610235,2.93958560338,2281.2304965106],[.00012315897,.84956094002,2810.9214616052],[8926784e-11,4.15697846427,.0172536522],[8715691e-11,6.11005153139,13362.4497067992],[6797556e-11,.36462229657,398.1490034082],[7774872e-11,3.33968761376,5621.8429232104],[3575078e-11,1.6618650571,2544.3144198834],[4161108e-11,.22814971327,2942.4634232916],[3075252e-11,.85696614132,191.4482661116],[2628117e-11,.64806124465,3337.0893083508],[2937546e-11,6.07893711402,.0673103028],[2389414e-11,5.03896442664,796.2980068164],[2579844e-11,.02996736156,3344.1355450488],[1528141e-11,1.14979301996,6151.533888305],[1798806e-11,.65634057445,529.6909650946],[1264357e-11,3.62275122593,5092.1519581158],[1286228e-11,3.06796065034,2146.1654164752],[1546404e-11,2.91579701718,1751.539531416],[1024902e-11,3.69334099279,8962.4553499102],[891566e-11,.18293837498,16703.062133499],[858759e-11,2.4009381194,2914.0142358238],[832715e-11,2.46418619474,3340.5951730476],[83272e-10,4.49495782139,3340.629680352],[712902e-11,3.66335473479,1059.3819301892],[748723e-11,3.82248614017,155.4203994342],[723861e-11,.67497311481,3738.761430108],[635548e-11,2.92182225127,8432.7643848156],[655162e-11,.48864064125,3127.3133312618],[550474e-11,3.81001042328,.9803210682],[55275e-10,4.47479317037,1748.016413067],[425966e-11,.55364317304,6283.0758499914],[415131e-11,.49662285038,213.299095438],[472167e-11,3.62547124025,1194.4470102246],[306551e-11,.38052848348,6684.7479717486],[312141e-11,.99853944405,6677.7017350506],[293198e-11,4.22131299634,20.7753954924],[302375e-11,4.48618007156,3532.0606928114],[274027e-11,.54222167059,3340.545116397],[281079e-11,5.88163521788,1349.8674096588],[231183e-11,1.28242156993,3870.3033917944],[283602e-11,5.7688543494,3149.1641605882],[236117e-11,5.75503217933,3333.498879699],[274033e-11,.13372524985,3340.6797370026],[299395e-11,2.78323740866,6254.6266625236]],[[3340.61242700512,0,0],[.01457554523,3.60433733236,3340.6124266998],[.00168414711,3.92318567804,6681.2248533996],[.00020622975,4.26108844583,10021.8372800994],[3452392e-11,4.7321039319,3.523118349],[2586332e-11,4.60670058555,13362.4497067992],[841535e-11,4.45864030426,2281.2304965106]],[[.00058152577,2.04961712429,3340.6124266998],[.00013459579,2.45738706163,6681.2248533996]]],[[[.03197134986,3.76832042431,3340.6124266998],[.00298033234,4.10616996305,6681.2248533996],[.00289104742,0,0],[.00031365539,4.4465105309,10021.8372800994],[34841e-9,4.7881254926,13362.4497067992]],[[.00217310991,6.04472194776,3340.6124266998],[.00020976948,3.14159265359,0],[.00012834709,1.60810667915,6681.2248533996]]],[[[1.53033488271,0,0],[.1418495316,3.47971283528,3340.6124266998],[.00660776362,3.81783443019,6681.2248533996],[.00046179117,4.15595316782,10021.8372800994],[8109733e-11,5.55958416318,2810.9214616052],[7485318e-11,1.77239078402,5621.8429232104],[5523191e-11,1.3643630377,2281.2304965106],[382516e-10,4.49407183687,13362.4497067992],[2306537e-11,.09081579001,2544.3144198834],[1999396e-11,5.36059617709,3337.0893083508],[2484394e-11,4.9254563992,2942.4634232916],[1960195e-11,4.74249437639,3344.1355450488],[1167119e-11,2.11260868341,5092.1519581158],[1102816e-11,5.00908403998,398.1490034082],[899066e-11,4.40791133207,529.6909650946],[992252e-11,5.83861961952,6151.533888305],[807354e-11,2.10217065501,1059.3819301892],[797915e-11,3.44839203899,796.2980068164],[740975e-11,1.49906336885,2146.1654164752]],[[.01107433345,2.03250524857,3340.6124266998],[.00103175887,2.37071847807,6681.2248533996],[128772e-9,0,0],[.0001081588,2.70888095665,10021.8372800994]],[[.00044242249,.47930604954,3340.6124266998],[8138042e-11,.86998389204,6681.2248533996]]]],Jupiter:[[[[.59954691494,0,0],[.09695898719,5.06191793158,529.6909650946],[.00573610142,1.44406205629,7.1135470008],[.00306389205,5.41734730184,1059.3819301892],[.00097178296,4.14264726552,632.7837393132],[.00072903078,3.64042916389,522.5774180938],[.00064263975,3.41145165351,103.0927742186],[.00039806064,2.29376740788,419.4846438752],[.00038857767,1.27231755835,316.3918696566],[.00027964629,1.7845459182,536.8045120954],[.0001358973,5.7748104079,1589.0728952838],[8246349e-11,3.5822792584,206.1855484372],[8768704e-11,3.63000308199,949.1756089698],[7368042e-11,5.0810119427,735.8765135318],[626315e-10,.02497628807,213.299095438],[6114062e-11,4.51319998626,1162.4747044078],[4905396e-11,1.32084470588,110.2063212194],[5305285e-11,1.30671216791,14.2270940016],[5305441e-11,4.18625634012,1052.2683831884],[4647248e-11,4.69958103684,3.9321532631],[3045023e-11,4.31676431084,426.598190876],[2609999e-11,1.56667394063,846.0828347512],[2028191e-11,1.06376530715,3.1813937377],[1764763e-11,2.14148655117,1066.49547719],[1722972e-11,3.88036268267,1265.5674786264],[1920945e-11,.97168196472,639.897286314],[1633223e-11,3.58201833555,515.463871093],[1431999e-11,4.29685556046,625.6701923124],[973272e-11,4.09764549134,95.9792272178]],[[529.69096508814,0,0],[.00489503243,4.2208293947,529.6909650946],[.00228917222,6.02646855621,7.1135470008],[.00030099479,4.54540782858,1059.3819301892],[.0002072092,5.45943156902,522.5774180938],[.00012103653,.16994816098,536.8045120954],[6067987e-11,4.42422292017,103.0927742186],[5433968e-11,3.98480737746,419.4846438752],[4237744e-11,5.89008707199,14.2270940016]],[[.00047233601,4.32148536482,7.1135470008],[.00030649436,2.929777887,529.6909650946],[.00014837605,3.14159265359,0]]],[[[.02268615702,3.55852606721,529.6909650946],[.00109971634,3.90809347197,1059.3819301892],[.00110090358,0,0],[8101428e-11,3.60509572885,522.5774180938],[6043996e-11,4.25883108339,1589.0728952838],[6437782e-11,.30627119215,536.8045120954]],[[.00078203446,1.52377859742,529.6909650946]]],[[[5.20887429326,0,0],[.25209327119,3.49108639871,529.6909650946],[.00610599976,3.84115365948,1059.3819301892],[.00282029458,2.57419881293,632.7837393132],[.00187647346,2.07590383214,522.5774180938],[.00086792905,.71001145545,419.4846438752],[.00072062974,.21465724607,536.8045120954],[.00065517248,5.9799588479,316.3918696566],[.00029134542,1.67759379655,103.0927742186],[.00030135335,2.16132003734,949.1756089698],[.00023453271,3.54023522184,735.8765135318],[.00022283743,4.19362594399,1589.0728952838],[.00023947298,.2745803748,7.1135470008],[.00013032614,2.96042965363,1162.4747044078],[970336e-10,1.90669633585,206.1855484372],[.00012749023,2.71550286592,1052.2683831884],[7057931e-11,2.18184839926,1265.5674786264],[6137703e-11,6.26418240033,846.0828347512],[2616976e-11,2.00994012876,1581.959348283]],[[.0127180152,2.64937512894,529.6909650946],[.00061661816,3.00076460387,1059.3819301892],[.00053443713,3.89717383175,522.5774180938],[.00031185171,4.88276958012,536.8045120954],[.00041390269,0,0]]]],Saturn:[[[[.87401354025,0,0],[.11107659762,3.96205090159,213.299095438],[.01414150957,4.58581516874,7.1135470008],[.00398379389,.52112032699,206.1855484372],[.00350769243,3.30329907896,426.598190876],[.00206816305,.24658372002,103.0927742186],[792713e-9,3.84007056878,220.4126424388],[.00023990355,4.66976924553,110.2063212194],[.00016573588,.43719228296,419.4846438752],[.00014906995,5.76903183869,316.3918696566],[.0001582029,.93809155235,632.7837393132],[.00014609559,1.56518472,3.9321532631],[.00013160301,4.44891291899,14.2270940016],[.00015053543,2.71669915667,639.897286314],[.00013005299,5.98119023644,11.0457002639],[.00010725067,3.12939523827,202.2533951741],[5863206e-11,.23656938524,529.6909650946],[5227757e-11,4.20783365759,3.1813937377],[6126317e-11,1.76328667907,277.0349937414],[5019687e-11,3.17787728405,433.7117378768],[459255e-10,.61977744975,199.0720014364],[4005867e-11,2.24479718502,63.7358983034],[2953796e-11,.98280366998,95.9792272178],[387367e-10,3.22283226966,138.5174968707],[2461186e-11,2.03163875071,735.8765135318],[3269484e-11,.77492638211,949.1756089698],[1758145e-11,3.2658010994,522.5774180938],[1640172e-11,5.5050445305,846.0828347512],[1391327e-11,4.02333150505,323.5054166574],[1580648e-11,4.37265307169,309.2783226558],[1123498e-11,2.83726798446,415.5524906121],[1017275e-11,3.71700135395,227.5261894396],[848642e-11,3.1915017083,209.3669421749]],[[213.2990952169,0,0],[.01297370862,1.82834923978,213.299095438],[.00564345393,2.88499717272,7.1135470008],[.00093734369,1.06311793502,426.598190876],[.00107674962,2.27769131009,206.1855484372],[.00040244455,2.04108104671,220.4126424388],[.00019941774,1.2795439047,103.0927742186],[.00010511678,2.7488034213,14.2270940016],[6416106e-11,.38238295041,639.897286314],[4848994e-11,2.43037610229,419.4846438752],[4056892e-11,2.92133209468,110.2063212194],[3768635e-11,3.6496533078,3.9321532631]],[[.0011644133,1.17988132879,7.1135470008],[.00091841837,.0732519584,213.299095438],[.00036661728,0,0],[.00015274496,4.06493179167,206.1855484372]]],[[[.04330678039,3.60284428399,213.299095438],[.00240348302,2.85238489373,426.598190876],[.00084745939,0,0],[.00030863357,3.48441504555,220.4126424388],[.00034116062,.57297307557,206.1855484372],[.0001473407,2.11846596715,639.897286314],[9916667e-11,5.79003188904,419.4846438752],[6993564e-11,4.7360468972,7.1135470008],[4807588e-11,5.43305312061,316.3918696566]],[[.00198927992,4.93901017903,213.299095438],[.00036947916,3.14159265359,0],[.00017966989,.5197943111,426.598190876]]],[[[9.55758135486,0,0],[.52921382865,2.39226219573,213.299095438],[.01873679867,5.2354960466,206.1855484372],[.01464663929,1.64763042902,426.598190876],[.00821891141,5.93520042303,316.3918696566],[.00547506923,5.0153261898,103.0927742186],[.0037168465,2.27114821115,220.4126424388],[.00361778765,3.13904301847,7.1135470008],[.00140617506,5.70406606781,632.7837393132],[.00108974848,3.29313390175,110.2063212194],[.00069006962,5.94099540992,419.4846438752],[.00061053367,.94037691801,639.897286314],[.00048913294,1.55733638681,202.2533951741],[.00034143772,.19519102597,277.0349937414],[.00032401773,5.47084567016,949.1756089698],[.00020936596,.46349251129,735.8765135318],[9796004e-11,5.20477537945,1265.5674786264],[.00011993338,5.98050967385,846.0828347512],[208393e-9,1.52102476129,433.7117378768],[.00015298404,3.0594381494,529.6909650946],[6465823e-11,.17732249942,1052.2683831884],[.00011380257,1.7310542704,522.5774180938],[3419618e-11,4.94550542171,1581.959348283]],[[.0618298134,.2584351148,213.299095438],[.00506577242,.71114625261,206.1855484372],[.00341394029,5.79635741658,426.598190876],[.00188491195,.47215589652,220.4126424388],[.00186261486,3.14159265359,0],[.00143891146,1.40744822888,7.1135470008]],[[.00436902572,4.78671677509,213.299095438]]]],Uranus:[[[[5.48129294297,0,0],[.09260408234,.89106421507,74.7815985673],[.01504247898,3.6271926092,1.4844727083],[.00365981674,1.89962179044,73.297125859],[.00272328168,3.35823706307,149.5631971346],[.00070328461,5.39254450063,63.7358983034],[.00068892678,6.09292483287,76.2660712756],[.00061998615,2.26952066061,2.9689454166],[.00061950719,2.85098872691,11.0457002639],[.0002646877,3.14152083966,71.8126531507],[.00025710476,6.11379840493,454.9093665273],[.0002107885,4.36059339067,148.0787244263],[.00017818647,1.74436930289,36.6485629295],[.00014613507,4.73732166022,3.9321532631],[.00011162509,5.8268179635,224.3447957019],[.0001099791,.48865004018,138.5174968707],[9527478e-11,2.95516862826,35.1640902212],[7545601e-11,5.236265824,109.9456887885],[4220241e-11,3.23328220918,70.8494453042],[40519e-9,2.277550173,151.0476698429],[3354596e-11,1.0654900738,4.4534181249],[2926718e-11,4.62903718891,9.5612275556],[349034e-10,5.48306144511,146.594251718],[3144069e-11,4.75199570434,77.7505439839],[2922333e-11,5.35235361027,85.8272988312],[2272788e-11,4.36600400036,70.3281804424],[2051219e-11,1.51773566586,.1118745846],[2148602e-11,.60745949945,38.1330356378],[1991643e-11,4.92437588682,277.0349937414],[1376226e-11,2.04283539351,65.2203710117],[1666902e-11,3.62744066769,380.12776796],[1284107e-11,3.11347961505,202.2533951741],[1150429e-11,.93343589092,3.1813937377],[1533221e-11,2.58594681212,52.6901980395],[1281604e-11,.54271272721,222.8603229936],[1372139e-11,4.19641530878,111.4301614968],[1221029e-11,.1990065003,108.4612160802],[946181e-11,1.19253165736,127.4717966068],[1150989e-11,4.17898916639,33.6796175129]],[[74.7815986091,0,0],[.00154332863,5.24158770553,74.7815985673],[.00024456474,1.71260334156,1.4844727083],[9258442e-11,.4282973235,11.0457002639],[8265977e-11,1.50218091379,63.7358983034],[915016e-10,1.41213765216,149.5631971346]]],[[[.01346277648,2.61877810547,74.7815985673],[623414e-9,5.08111189648,149.5631971346],[.00061601196,3.14159265359,0],[9963722e-11,1.61603805646,76.2660712756],[992616e-10,.57630380333,73.297125859]],[[.00034101978,.01321929936,74.7815985673]]],[[[19.21264847206,0,0],[.88784984413,5.60377527014,74.7815985673],[.03440836062,.32836099706,73.297125859],[.0205565386,1.7829515933,149.5631971346],[.0064932241,4.52247285911,76.2660712756],[.00602247865,3.86003823674,63.7358983034],[.00496404167,1.40139935333,454.9093665273],[.00338525369,1.58002770318,138.5174968707],[.00243509114,1.57086606044,71.8126531507],[.00190522303,1.99809394714,1.4844727083],[.00161858838,2.79137786799,148.0787244263],[.00143706183,1.38368544947,11.0457002639],[.00093192405,.17437220467,36.6485629295],[.00071424548,4.24509236074,224.3447957019],[.00089806014,3.66105364565,109.9456887885],[.00039009723,1.66971401684,70.8494453042],[.00046677296,1.39976401694,35.1640902212],[.00039025624,3.36234773834,277.0349937414],[.00036755274,3.88649278513,146.594251718],[.00030348723,.70100838798,151.0476698429],[.00029156413,3.180563367,77.7505439839],[.00022637073,.72518687029,529.6909650946],[.00011959076,1.7504339214,984.6003316219],[.00025620756,5.25656086672,380.12776796]],[[.01479896629,3.67205697578,74.7815985673]]]],Neptune:[[[[5.31188633046,0,0],[.0179847553,2.9010127389,38.1330356378],[.01019727652,.48580922867,1.4844727083],[.00124531845,4.83008090676,36.6485629295],[.00042064466,5.41054993053,2.9689454166],[.00037714584,6.09221808686,35.1640902212],[.00033784738,1.24488874087,76.2660712756],[.00016482741,7727998e-11,491.5579294568],[9198584e-11,4.93747051954,39.6175083461],[899425e-10,.27462171806,175.1660598002]],[[38.13303563957,0,0],[.00016604172,4.86323329249,1.4844727083],[.00015744045,2.27887427527,38.1330356378]]],[[[.03088622933,1.44104372644,38.1330356378],[.00027780087,5.91271884599,76.2660712756],[.00027623609,0,0],[.00015355489,2.52123799551,36.6485629295],[.00015448133,3.50877079215,39.6175083461]]],[[[30.07013205828,0,0],[.27062259632,1.32999459377,38.1330356378],[.01691764014,3.25186135653,36.6485629295],[.00807830553,5.18592878704,1.4844727083],[.0053776051,4.52113935896,35.1640902212],[.00495725141,1.5710564165,491.5579294568],[.00274571975,1.84552258866,175.1660598002],[.0001201232,1.92059384991,1021.2488945514],[.00121801746,5.79754470298,76.2660712756],[.00100896068,.3770272493,73.297125859],[.00135134092,3.37220609835,39.6175083461],[7571796e-11,1.07149207335,388.4651552382]]]]};function loe(n){var e,t,i,r,a,s,o;const l=2e3+(n-14)/$se;return l<-500?(e=(l-1820)/100,-20+32*e*e):l<500?(e=l/100,t=e*e,i=e*t,r=t*t,a=t*i,s=i*i,10583.6-1014.41*e+33.78311*t-5.952053*i-.1798452*r+.022174192*a+.0090316521*s):l<1600?(e=(l-1e3)/100,t=e*e,i=e*t,r=t*t,a=t*i,s=i*i,1574.2-556.01*e+71.23472*t+.319781*i-.8503463*r-.005050998*a+.0083572073*s):l<1700?(e=l-1600,t=e*e,i=e*t,120-.9808*e-.01532*t+i/7129):l<1800?(e=l-1700,t=e*e,i=e*t,r=t*t,8.83+.1603*e-.0059285*t+13336e-8*i-r/1174e3):l<1860?(e=l-1800,t=e*e,i=e*t,r=t*t,a=t*i,s=i*i,o=i*r,13.72-.332447*e+.0068612*t+.0041116*i-37436e-8*r+121272e-10*a-1699e-10*s+875e-12*o):l<1900?(e=l-1860,t=e*e,i=e*t,r=t*t,a=t*i,7.62+.5737*e-.251754*t+.01680668*i-.0004473624*r+a/233174):l<1920?(e=l-1900,t=e*e,i=e*t,r=t*t,-2.79+1.494119*e-.0598939*t+.0061966*i-197e-6*r):l<1941?(e=l-1920,t=e*e,i=e*t,21.2+.84493*e-.0761*t+.0020936*i):l<1961?(e=l-1950,t=e*e,i=e*t,29.07+.407*e-t/233+i/2547):l<1986?(e=l-1975,t=e*e,i=e*t,45.45+1.067*e-t/260-i/718):l<2005?(e=l-2e3,t=e*e,i=e*t,r=t*t,a=t*i,63.86+.3345*e-.060374*t+.0017275*i+651814e-9*r+2373599e-11*a):l<2050?(e=l-2e3,62.92+.32217*e+.005589*e*e):l<2150?(e=(l-1820)/100,-20+32*e*e-.5628*(2150-l)):(e=(l-1820)/100,-20+32*e*e)}let coe=loe;function u5(n){return n+coe(n)/86400}class Yc{constructor(e){if(e instanceof Yc){this.date=e.date,this.ut=e.ut,this.tt=e.tt;return}const t=1e3*3600*24;if(e instanceof Date&&Number.isFinite(e.getTime())){this.date=e,this.ut=(e.getTime()-c5.getTime())/t,this.tt=u5(this.ut);return}if(Number.isFinite(e)){this.date=new Date(c5.getTime()+e*t),this.ut=e,this.tt=u5(this.ut);return}throw"Argument must be a Date object, an AstroTime object, or a numeric UTC Julian date."}static FromTerrestrialTime(e){let t=new Yc(e);for(;;){const i=e-t.tt;if(Math.abs(i)<1e-12)return t;t=t.AddDays(i)}}toString(){return this.date.toISOString()}AddDays(e){return new Yc(this.ut+e)}}function sd(n){return n instanceof Yc?n:new Yc(n)}function uoe(n){function e(p){return p%toe*Wf}const t=n.tt/36525,i=e(128710479305e-5+t*1295965810481e-4),r=e(335779.526232+t*17395272628478e-4),a=e(107226070369e-5+t*1602961601209e-3),s=e(450160.398036-t*69628905431e-4);let o=Math.sin(s),l=Math.cos(s),u=(-172064161-174666*t)*o+33386*l,d=(92052331+9086*t)*l+15377*o,f=2*(r-a+s);return o=Math.sin(f),l=Math.cos(f),u+=(-13170906-1675*t)*o-13696*l,d+=(5730336-3015*t)*l-4587*o,f=2*(r+s),o=Math.sin(f),l=Math.cos(f),u+=(-2276413-234*t)*o+2796*l,d+=(978459-485*t)*l+1374*o,f=2*s,o=Math.sin(f),l=Math.cos(f),u+=(2074554+207*t)*o-698*l,d+=(-897492+470*t)*l-291*o,o=Math.sin(i),l=Math.cos(i),u+=(1475877-3633*t)*o+11817*l,d+=(73871-184*t)*l-1924*o,{dpsi:-135e-6+u*1e-7,deps:388e-6+d*1e-7}}function UB(n){var e=n.tt/36525,t=((((-434e-10*e-576e-9)*e+.0020034)*e-1831e-7)*e-46.836769)*e+84381.406;return t/3600}var Tx;function PB(n){if(!Tx||Math.abs(Tx.tt-n.tt)>1e-6){const e=uoe(n),t=UB(n),i=t+e.deps/3600;Tx={tt:n.tt,dpsi:e.dpsi,deps:e.deps,ee:e.dpsi*Math.cos(t*Xh)/15,mobl:t,tobl:i}}return Tx}function hoe(n,e){const t=n*Xh,i=Math.cos(t),r=Math.sin(t);return[e[0],e[1]*i-e[2]*r,e[1]*r+e[2]*i]}function doe(n,e){return hoe(UB(n),e)}function foe(n){const e=n.tt/36525;function t(ct,Qe){const Ee=[];let V;for(V=0;V<=Qe-ct;++V)Ee.push(0);return{min:ct,array:Ee}}function i(ct,Qe,Ee,V){const Ae=[];for(let Oe=0;Oe<=Qe-ct;++Oe)Ae.push(t(Ee,V));return{min:ct,array:Ae}}function r(ct,Qe,Ee){const V=ct.array[Qe-ct.min];return V.array[Ee-V.min]}function a(ct,Qe,Ee,V){const Ae=ct.array[Qe-ct.min];Ae.array[Ee-Ae.min]=V}let s,o,l,u,d,f,p,m,v,x,S,_,T,E,b,R,w,L,U,N,C,z,W,K=i(-6,6,1,4),oe=i(-6,6,1,4);function ae(ct,Qe){return r(K,ct,Qe)}function X(ct,Qe){return r(oe,ct,Qe)}function te(ct,Qe,Ee){return a(K,ct,Qe,Ee)}function Q(ct,Qe,Ee){return a(oe,ct,Qe,Ee)}function ce(ct,Qe,Ee,V,Ae){Ae(ct*Ee-Qe*V,Qe*Ee+ct*V)}function se(ct){return Math.sin(gl*ct)}p=e*e,v=0,W=0,S=0,_=3422.7;var De=se(.19833+.05611*e),Xe=se(.27869+.04508*e),nt=se(.16827-.36903*e),tt=se(.34734-5.37261*e),xt=se(.10498-5.37899*e),ve=se(.42681-.41855*e),we=se(.14943-5.37511*e);for(L=.84*De+.31*Xe+14.27*nt+7.26*tt+.28*xt+.24*ve,U=2.94*De+.31*Xe+14.27*nt+9.34*tt+1.12*xt+.83*ve,N=-6.4*De-1.89*ve,C=.21*De+.31*Xe+14.27*nt-88.7*tt-15.3*xt+.24*ve-1.86*we,z=L-N,m=-3332e-9*se(.59734-5.37261*e)-539e-9*se(.35498-5.37899*e)-64e-9*se(.39943-5.37511*e),T=gl*ff(.60643382+1336.85522467*e-313e-8*p)+L/mc,E=gl*ff(.37489701+1325.55240982*e+2565e-8*p)+U/mc,b=gl*ff(.99312619+99.99735956*e-44e-8*p)+N/mc,R=gl*ff(.25909118+1342.2278298*e-892e-8*p)+C/mc,w=gl*ff(.82736186+1236.85308708*e-397e-8*p)+z/mc,d=1;d<=4;++d){switch(d){case 1:l=E,o=4,u=1.000002208;break;case 2:l=b,o=3,u=.997504612-.002495388*e;break;case 3:l=R,o=4,u=1.000002708+139.978*m;break;case 4:l=w,o=6,u=1;break;default:throw`Internal error: I = ${d}`}for(te(0,d,1),te(1,d,Math.cos(l)*u),Q(0,d,0),Q(1,d,Math.sin(l)*u),f=2;f<=o;++f)ce(ae(f-1,d),X(f-1,d),ae(1,d),X(1,d),(ct,Qe)=>(te(f,d,ct),Q(f,d,Qe)));for(f=1;f<=o;++f)te(-f,d,ae(f,d)),Q(-f,d,-X(f,d))}function Ze(ct,Qe,Ee,V){for(var Ae={x:1,y:0},Oe=[0,ct,Qe,Ee,V],Ve=1;Ve<=4;++Ve)Oe[Ve]!==0&&ce(Ae.x,Ae.y,ae(Oe[Ve],Ve),X(Oe[Ve],Ve),(Fe,$e)=>(Ae.x=Fe,Ae.y=$e));return Ae}function de(ct,Qe,Ee,V,Ae,Oe,Ve,Fe){var $e=Ze(Ae,Oe,Ve,Fe);v+=ct*$e.y,W+=Qe*$e.y,S+=Ee*$e.x,_+=V*$e.x}de(13.902,14.06,-.001,.2607,0,0,0,4),de(.403,-4.01,.394,.0023,0,0,0,3),de(2369.912,2373.36,.601,28.2333,0,0,0,2),de(-125.154,-112.79,-.725,-.9781,0,0,0,1),de(1.979,6.98,-.445,.0433,1,0,0,4),de(191.953,192.72,.029,3.0861,1,0,0,2),de(-8.466,-13.51,.455,-.1093,1,0,0,1),de(22639.5,22609.07,.079,186.5398,1,0,0,0),de(18.609,3.59,-.094,.0118,1,0,0,-1),de(-4586.465,-4578.13,-.077,34.3117,1,0,0,-2),de(3.215,5.44,.192,-.0386,1,0,0,-3),de(-38.428,-38.64,.001,.6008,1,0,0,-4),de(-.393,-1.43,-.092,.0086,1,0,0,-6),de(-.289,-1.59,.123,-.0053,0,1,0,4),de(-24.42,-25.1,.04,-.3,0,1,0,2),de(18.023,17.93,.007,.1494,0,1,0,1),de(-668.146,-126.98,-1.302,-.3997,0,1,0,0),de(.56,.32,-.001,-.0037,0,1,0,-1),de(-165.145,-165.06,.054,1.9178,0,1,0,-2),de(-1.877,-6.46,-.416,.0339,0,1,0,-4),de(.213,1.02,-.074,.0054,2,0,0,4),de(14.387,14.78,-.017,.2833,2,0,0,2),de(-.586,-1.2,.054,-.01,2,0,0,1),de(769.016,767.96,.107,10.1657,2,0,0,0),de(1.75,2.01,-.018,.0155,2,0,0,-1),de(-211.656,-152.53,5.679,-.3039,2,0,0,-2),de(1.225,.91,-.03,-.0088,2,0,0,-3),de(-30.773,-34.07,-.308,.3722,2,0,0,-4),de(-.57,-1.4,-.074,.0109,2,0,0,-6),de(-2.921,-11.75,.787,-.0484,1,1,0,2),de(1.267,1.52,-.022,.0164,1,1,0,1),de(-109.673,-115.18,.461,-.949,1,1,0,0),de(-205.962,-182.36,2.056,1.4437,1,1,0,-2),de(.233,.36,.012,-.0025,1,1,0,-3),de(-4.391,-9.66,-.471,.0673,1,1,0,-4),de(.283,1.53,-.111,.006,1,-1,0,4),de(14.577,31.7,-1.54,.2302,1,-1,0,2),de(147.687,138.76,.679,1.1528,1,-1,0,0),de(-1.089,.55,.021,0,1,-1,0,-1),de(28.475,23.59,-.443,-.2257,1,-1,0,-2),de(-.276,-.38,-.006,-.0036,1,-1,0,-3),de(.636,2.27,.146,-.0102,1,-1,0,-4),de(-.189,-1.68,.131,-.0028,0,2,0,2),de(-7.486,-.66,-.037,-.0086,0,2,0,0),de(-8.096,-16.35,-.74,.0918,0,2,0,-2),de(-5.741,-.04,0,-9e-4,0,0,2,2),de(.255,0,0,0,0,0,2,1),de(-411.608,-.2,0,-.0124,0,0,2,0),de(.584,.84,0,.0071,0,0,2,-1),de(-55.173,-52.14,0,-.1052,0,0,2,-2),de(.254,.25,0,-.0017,0,0,2,-3),de(.025,-1.67,0,.0031,0,0,2,-4),de(1.06,2.96,-.166,.0243,3,0,0,2),de(36.124,50.64,-1.3,.6215,3,0,0,0),de(-13.193,-16.4,.258,-.1187,3,0,0,-2),de(-1.187,-.74,.042,.0074,3,0,0,-4),de(-.293,-.31,-.002,.0046,3,0,0,-6),de(-.29,-1.45,.116,-.0051,2,1,0,2),de(-7.649,-10.56,.259,-.1038,2,1,0,0),de(-8.627,-7.59,.078,-.0192,2,1,0,-2),de(-2.74,-2.54,.022,.0324,2,1,0,-4),de(1.181,3.32,-.212,.0213,2,-1,0,2),de(9.703,11.67,-.151,.1268,2,-1,0,0),de(-.352,-.37,.001,-.0028,2,-1,0,-1),de(-2.494,-1.17,-.003,-.0017,2,-1,0,-2),de(.36,.2,-.012,-.0043,2,-1,0,-4),de(-1.167,-1.25,.008,-.0106,1,2,0,0),de(-7.412,-6.12,.117,.0484,1,2,0,-2),de(-.311,-.65,-.032,.0044,1,2,0,-4),de(.757,1.82,-.105,.0112,1,-2,0,2),de(2.58,2.32,.027,.0196,1,-2,0,0),de(2.533,2.4,-.014,-.0212,1,-2,0,-2),de(-.344,-.57,-.025,.0036,0,3,0,-2),de(-.992,-.02,0,0,1,0,2,2),de(-45.099,-.02,0,-.001,1,0,2,0),de(-.179,-9.52,0,-.0833,1,0,2,-2),de(-.301,-.33,0,.0014,1,0,2,-4),de(-6.382,-3.37,0,-.0481,1,0,-2,2),de(39.528,85.13,0,-.7136,1,0,-2,0),de(9.366,.71,0,-.0112,1,0,-2,-2),de(.202,.02,0,0,1,0,-2,-4),de(.415,.1,0,.0013,0,1,2,0),de(-2.152,-2.26,0,-.0066,0,1,2,-2),de(-1.44,-1.3,0,.0014,0,1,-2,2),de(.384,-.04,0,0,0,1,-2,-2),de(1.938,3.6,-.145,.0401,4,0,0,0),de(-.952,-1.58,.052,-.013,4,0,0,-2),de(-.551,-.94,.032,-.0097,3,1,0,0),de(-.482,-.57,.005,-.0045,3,1,0,-2),de(.681,.96,-.026,.0115,3,-1,0,0),de(-.297,-.27,.002,-9e-4,2,2,0,-2),de(.254,.21,-.003,0,2,-2,0,-2),de(-.25,-.22,.004,.0014,1,3,0,-2),de(-3.996,0,0,4e-4,2,0,2,0),de(.557,-.75,0,-.009,2,0,2,-2),de(-.459,-.38,0,-.0053,2,0,-2,2),de(-1.298,.74,0,4e-4,2,0,-2,0),de(.538,1.14,0,-.0141,2,0,-2,-2),de(.263,.02,0,0,1,1,2,0),de(.426,.07,0,-6e-4,1,1,-2,-2),de(-.304,.03,0,3e-4,1,-1,2,0),de(-.372,-.19,0,-.0027,1,-1,-2,2),de(.418,0,0,0,0,0,4,0),de(-.33,-.04,0,0,3,0,2,0);function it(ct,Qe,Ee,V,Ae){return ct*Ze(Qe,Ee,V,Ae).y}x=0,x+=it(-526.069,0,0,1,-2),x+=it(-3.352,0,0,1,-4),x+=it(44.297,1,0,1,-2),x+=it(-6,1,0,1,-4),x+=it(20.599,-1,0,1,0),x+=it(-30.598,-1,0,1,-2),x+=it(-24.649,-2,0,1,0),x+=it(-2,-2,0,1,-2),x+=it(-22.571,0,1,1,-2),x+=it(10.985,0,-1,1,-2),v+=.82*se(.7736-62.5512*e)+.31*se(.0466-125.1025*e)+.35*se(.5785-25.1042*e)+.66*se(.4591+1335.8075*e)+.64*se(.313-91.568*e)+1.14*se(.148+1331.2898*e)+.21*se(.5918+1056.5859*e)+.44*se(.5784+1322.8595*e)+.24*se(.2275-5.7374*e)+.28*se(.2965+2.6929*e)+.33*se(.3132+6.3368*e),s=R+W/mc;let wt=(1.000002708+139.978*m)*(18518.511+1.189+S)*Math.sin(s)-6.24*Math.sin(3*s)+x;return{geo_eclip_lon:gl*ff((T+v/mc)/gl),geo_eclip_lat:Math.PI/(180*3600)*wt,distance_au:mc*ioe/(.999953253*_)}}function poe(n,e){return[n.rot[0][0]*e[0]+n.rot[1][0]*e[1]+n.rot[2][0]*e[2],n.rot[0][1]*e[0]+n.rot[1][1]*e[1]+n.rot[2][1]*e[2],n.rot[0][2]*e[0]+n.rot[1][2]*e[1]+n.rot[2][2]*e[2]]}function moe(n,e,t){const i=zB(e,t);return poe(i,n)}function zB(n,e){const t=n.tt/36525;let i=84381.406,r=((((-951e-10*t+132851e-9)*t-.00114045)*t-1.0790069)*t+5038.481507)*t,a=((((3337e-10*t-467e-9)*t-.00772503)*t+.0512623)*t-.025754)*t+i,s=((((-56e-9*t+170663e-9)*t-.00121197)*t-2.3814292)*t+10.556403)*t;i*=Wf,r*=Wf,a*=Wf,s*=Wf;const o=Math.sin(i),l=Math.cos(i),u=Math.sin(-r),d=Math.cos(-r),f=Math.sin(-a),p=Math.cos(-a),m=Math.sin(s),v=Math.cos(s),x=v*d-u*m*p,S=v*u*l+m*p*d*l-o*m*f,_=v*u*o+m*p*d*o+l*m*f,T=-m*d-u*v*p,E=-m*u*l+v*p*d*l-o*v*f,b=-m*u*o+v*p*d*o+l*v*f,R=u*f,w=-f*d*l-o*p,L=-f*d*o+p*l;if(e===Bl.Into2000)return new zp([[x,S,_],[T,E,b],[R,w,L]]);if(e===Bl.From2000)return new zp([[x,T,R],[S,E,w],[_,b,L]]);throw"Invalid precess direction"}function goe(n){const e=.779057273264+.00273781191135448*n.ut,t=n.ut%1;let i=360*((e+t)%1);return i<0&&(i+=360),i}let Ex;function voe(n){if(!Ex||Ex.tt!==n.tt){const e=n.tt/36525;let t=15*PB(n).ee;const i=goe(n);let r=((t+.014506+((((-368e-10*e-29956e-9)*e-44e-8)*e+1.3915817)*e+4612.156534)*e)/3600+i)%360/15;r<0&&(r+=24),Ex={tt:n.tt,st:r}}return Ex.st}function _oe(n){const e=sd(n);return voe(e)}function xoe(n,e){const t=PB(n),i=t.mobl*Xh,r=t.tobl*Xh,a=t.dpsi*Wf,s=Math.cos(i),o=Math.sin(i),l=Math.cos(r),u=Math.sin(r),d=Math.cos(a),f=Math.sin(a),p=d,m=-f*s,v=-f*o,x=f*l,S=d*s*l+o*u,_=d*o*l-s*u,T=f*u,E=d*s*u-o*l,b=d*o*u+s*l;if(e===Bl.From2000)return new zp([[p,x,T],[m,S,E],[v,_,b]]);if(e===Bl.Into2000)return new zp([[p,m,v],[x,S,_],[T,E,b]]);throw"Invalid precess direction"}let Js=class{constructor(e,t,i,r){this.x=e,this.y=t,this.z=i,this.t=r}Length(){return Math.hypot(this.x,this.y,this.z)}};class yoe{constructor(e,t,i,r,a,s,o){this.x=e,this.y=t,this.z=i,this.vx=r,this.vy=a,this.vz=s,this.t=o}}let Soe=class{constructor(e,t,i){this.lat=m1(e),this.lon=m1(t),this.dist=m1(i)}};class zp{constructor(e){this.rot=e}}function RA(n){const e=sd(n),t=foe(e),i=t.distance_au*Math.cos(t.geo_eclip_lat),r=[i*Math.cos(t.geo_eclip_lon),i*Math.sin(t.geo_eclip_lon),t.distance_au*Math.sin(t.geo_eclip_lat)],a=doe(e,r),s=moe(a,e,Bl.Into2000);return new Js(s[0],s[1],s[2],e)}function ap(n,e,t){let i=1,r=0;for(let a of n){let s=0;for(let[l,u,d]of a)s+=l*Math.cos(u+e*d);let o=i*s;t&&(o%=gl),r+=o,i*=e}return r}function cM(n,e){let t=1,i=0,r=0,a=0;for(let s of n){let o=0,l=0;for(let[u,d,f]of s){let p=d+e*f;o+=u*f*Math.sin(p),a>0&&(l+=u*Math.cos(p))}r+=a*i*l-t*o,i=t,t*=e,++a}return r}const L0=365250,CA=0,DA=1,NA=2;function OA(n){return new qh(n[0]+44036e-11*n[1]-190919e-12*n[2],-479966e-12*n[0]+.917482137087*n[1]-.397776982902*n[2],.397776982902*n[1]+.917482137087*n[2])}function BB(n,e,t){const i=t*Math.cos(e),r=Math.cos(n),a=Math.sin(n);return[i*r,i*a,t*Math.sin(e)]}function g1(n,e){const t=e.tt/L0,i=ap(n[CA],t,!0),r=ap(n[DA],t,!1),a=ap(n[NA],t,!1),s=BB(i,r,a);return OA(s).ToAstroVector(e)}function Toe(n,e){const t=e/L0,i=ap(n[CA],t,!0),r=ap(n[DA],t,!1),a=ap(n[NA],t,!1),s=cM(n[CA],t),o=cM(n[DA],t),l=cM(n[NA],t),u=Math.cos(i),d=Math.sin(i),f=Math.cos(r),p=Math.sin(r),m=+(l*f*u)-a*p*u*o-a*f*d*s,v=+(l*f*d)-a*p*d*o+a*f*u*s,x=+(l*p)+a*f*o,S=BB(i,r,a),_=[m/L0,v/L0,x/L0],T=OA(S),E=OA(_);return new Yh(e,T,E)}function bx(n,e,t,i){const r=i/(i+$R),a=g1(Xf[t],e);n.x+=r*a.x,n.y+=r*a.y,n.z+=r*a.z}function Eoe(n){const e=new Js(0,0,0,n);return bx(e,n,kn.Jupiter,bA),bx(e,n,kn.Saturn,MA),bx(e,n,kn.Uranus,AA),bx(e,n,kn.Neptune,wA),e}const LA=51,boe=29200,qf=146,vl=201,vh=[[-73e4,[-26.118207232108,-14.376168177825,3.384402515299],[.0016339372163656,-.0027861699588508,-.0013585880229445]],[-700800,[41.974905202127,-.448502952929,-12.770351505989],[.00073458569351457,.0022785014891658,.00048619778602049]],[-671600,[14.706930780744,44.269110540027,9.353698474772],[-.00210001479998,.00022295915939915,.00070143443551414]],[-642400,[-29.441003929957,-6.43016153057,6.858481011305],[.00084495803960544,-.0030783914758711,-.0012106305981192]],[-613200,[39.444396946234,-6.557989760571,-13.913760296463],[.0011480029005873,.0022400006880665,.00035168075922288]],[-584e3,[20.2303809507,43.266966657189,7.382966091923],[-.0019754081700585,.00053457141292226,.00075929169129793]],[-554800,[-30.65832536462,2.093818874552,9.880531138071],[61010603013347e-18,-.0031326500935382,-.00099346125151067]],[-525600,[35.737703251673,-12.587706024764,-14.677847247563],[.0015802939375649,.0021347678412429,.00019074436384343]],[-496400,[25.466295188546,41.367478338417,5.216476873382],[-.0018054401046468,.0008328308359951,.00080260156912107]],[-467200,[-29.847174904071,10.636426313081,12.297904180106],[-.00063257063052907,-.0029969577578221,-.00074476074151596]],[-438e3,[30.774692107687,-18.236637015304,-14.945535879896],[.0020113162005465,.0019353827024189,-20937793168297e-19]],[-408800,[30.243153324028,38.656267888503,2.938501750218],[-.0016052508674468,.0011183495337525,.00083333973416824]],[-379600,[-27.288984772533,18.643162147874,14.023633623329],[-.0011856388898191,-.0027170609282181,-.00049015526126399]],[-350400,[24.519605196774,-23.245756064727,-14.626862367368],[.0024322321483154,.0016062008146048,-.00023369181613312]],[-321200,[34.505274805875,35.125338586954,.557361475637],[-.0013824391637782,.0013833397561817,.00084823598806262]],[-292e3,[-23.275363915119,25.818514298769,15.055381588598],[-.0016062295460975,-.0023395961498533,-.00024377362639479]],[-262800,[17.050384798092,-27.180376290126,-13.608963321694],[.0028175521080578,.0011358749093955,-.00049548725258825]],[-233600,[38.093671910285,30.880588383337,-1.843688067413],[-.0011317697153459,.0016128814698472,.00084177586176055]],[-204400,[-18.197852930878,31.932869934309,15.438294826279],[-.0019117272501813,-.0019146495909842,-19657304369835e-18]],[-175200,[8.528924039997,-29.618422200048,-11.805400994258],[.0031034370787005,.0005139363329243,-.00077293066202546]],[-146e3,[40.94685725864,25.904973592021,-4.256336240499],[-.00083652705194051,.0018129497136404,.0008156422827306]],[-116800,[-12.326958895325,36.881883446292,15.217158258711],[-.0021166103705038,-.001481442003599,.00017401209844705]],[-87600,[-.633258375909,-30.018759794709,-9.17193287495],[.0032016994581737,-.00025279858672148,-.0010411088271861]],[-58400,[42.936048423883,20.344685584452,-6.588027007912],[-.00050525450073192,.0019910074335507,.00077440196540269]],[-29200,[-5.975910552974,40.61180995846,14.470131723673],[-.0022184202156107,-.0010562361130164,.00033652250216211]],[0,[-9.875369580774,-27.978926224737,-5.753711824704],[.0030287533248818,-.0011276087003636,-.0012651326732361]],[29200,[43.958831986165,14.214147973292,-8.808306227163],[-.00014717608981871,.0021404187242141,.00071486567806614]],[58400,[.67813676352,43.094461639362,13.243238780721],[-.0022358226110718,-.00063233636090933,.00047664798895648]],[87600,[-18.282602096834,-23.30503958666,-1.766620508028],[.0025567245263557,-.0019902940754171,-.0013943491701082]],[116800,[43.873338744526,7.700705617215,-10.814273666425],[.00023174803055677,.0022402163127924,.00062988756452032]],[146e3,[7.392949027906,44.382678951534,11.629500214854],[-.002193281545383,-.00021751799585364,.00059556516201114]],[175200,[-24.981690229261,-16.204012851426,2.466457544298],[.001819398914958,-.0026765419531201,-.0013848283502247]],[204400,[42.530187039511,.845935508021,-12.554907527683],[.00065059779150669,.0022725657282262,.00051133743202822]],[233600,[13.999526486822,44.462363044894,9.669418486465],[-.0021079296569252,.00017533423831993,.00069128485798076]],[262800,[-29.184024803031,-7.371243995762,6.493275957928],[.00093581363109681,-.0030610357109184,-.0012364201089345]],[292e3,[39.831980671753,-6.078405766765,-13.909815358656],[.0011117769689167,.0022362097830152,.00036230548231153]],[321200,[20.294955108476,43.417190420251,7.450091985932],[-.0019742157451535,.00053102050468554,.00075938408813008]],[350400,[-30.66999230216,2.318743558955,9.973480913858],[45605107450676e-18,-.0031308219926928,-.00099066533301924]],[379600,[35.626122155983,-12.897647509224,-14.777586508444],[.0016015684949743,.0021171931182284,.00018002516202204]],[408800,[26.133186148561,41.232139187599,5.00640132622],[-.0017857704419579,.00086046232702817,.00080614690298954]],[438e3,[-29.57674022923,11.863535943587,12.631323039872],[-.00072292830060955,-.0029587820140709,-.000708242964503]],[467200,[29.910805787391,-19.159019294,-15.013363865194],[.0020871080437997,.0018848372554514,-38528655083926e-18]],[496400,[31.375957451819,38.050372720763,2.433138343754],[-.0015546055556611,.0011699815465629,.00083565439266001]],[525600,[-26.360071336928,20.662505904952,14.414696258958],[-.0013142373118349,-.0026236647854842,-.00042542017598193]],[554800,[22.599441488648,-24.508879898306,-14.484045731468],[.0025454108304806,.0014917058755191,-.00030243665086079]],[584e3,[35.877864013014,33.894226366071,-.224524636277],[-.0012941245730845,.0014560427668319,.00084762160640137]],[613200,[-21.538149762417,28.204068269761,15.321973799534],[-.001731211740901,-.0021939631314577,-.0001631691327518]],[642400,[13.971521374415,-28.339941764789,-13.083792871886],[.0029334630526035,.00091860931752944,-.00059939422488627]],[671600,[39.526942044143,28.93989736011,-2.872799527539],[-.0010068481658095,.001702113288809,.00083578230511981]],[700800,[-15.576200701394,34.399412961275,15.466033737854],[-.0020098814612884,-.0017191109825989,70414782780416e-18]],[73e4,[4.24325283709,-30.118201690825,-10.707441231349],[.0031725847067411,.0001609846120227,-.00090672150593868]]];let qh=class _l{constructor(e,t,i){this.x=e,this.y=t,this.z=i}clone(){return new _l(this.x,this.y,this.z)}ToAstroVector(e){return new Js(this.x,this.y,this.z,e)}static zero(){return new _l(0,0,0)}quadrature(){return this.x*this.x+this.y*this.y+this.z*this.z}add(e){return new _l(this.x+e.x,this.y+e.y,this.z+e.z)}sub(e){return new _l(this.x-e.x,this.y-e.y,this.z-e.z)}incr(e){this.x+=e.x,this.y+=e.y,this.z+=e.z}decr(e){this.x-=e.x,this.y-=e.y,this.z-=e.z}mul(e){return new _l(e*this.x,e*this.y,e*this.z)}div(e){return new _l(this.x/e,this.y/e,this.z/e)}mean(e){return new _l((this.x+e.x)/2,(this.y+e.y)/2,(this.z+e.z)/2)}neg(){return new _l(-this.x,-this.y,-this.z)}};class Yh{constructor(e,t,i){this.tt=e,this.r=t,this.v=i}clone(){return new Yh(this.tt,this.r,this.v)}sub(e){return new Yh(this.tt,this.r.sub(e.r),this.v.sub(e.v))}}function Moe(n){let[e,[t,i,r],[a,s,o]]=n;return new Yh(e,new qh(t,i,r),new qh(a,s,o))}function Mx(n,e,t,i){const r=i/(i+$R),a=Toe(Xf[t],e);return n.r.incr(a.r.mul(r)),n.v.incr(a.v.mul(r)),a}function s0(n,e,t){const i=t.sub(n),r=i.quadrature();return i.mul(e/(r*Math.sqrt(r)))}class eC{constructor(e){let t=new Yh(e,new qh(0,0,0),new qh(0,0,0));this.Jupiter=Mx(t,e,kn.Jupiter,bA),this.Saturn=Mx(t,e,kn.Saturn,MA),this.Uranus=Mx(t,e,kn.Uranus,AA),this.Neptune=Mx(t,e,kn.Neptune,wA),this.Jupiter.r.decr(t.r),this.Jupiter.v.decr(t.v),this.Saturn.r.decr(t.r),this.Saturn.v.decr(t.v),this.Uranus.r.decr(t.r),this.Uranus.v.decr(t.v),this.Neptune.r.decr(t.r),this.Neptune.v.decr(t.v),this.Sun=new Yh(e,t.r.mul(-1),t.v.mul(-1))}Acceleration(e){let t=s0(e,$R,this.Sun.r);return t.incr(s0(e,bA,this.Jupiter.r)),t.incr(s0(e,MA,this.Saturn.r)),t.incr(s0(e,AA,this.Uranus.r)),t.incr(s0(e,wA,this.Neptune.r)),t}}let FB=class HB{constructor(e,t,i,r){this.tt=e,this.r=t,this.v=i,this.a=r}clone(){return new HB(this.tt,this.r.clone(),this.v.clone(),this.a.clone())}},VB=class{constructor(e,t){this.bary=e,this.grav=t}};function Jy(n,e,t,i){return new qh(e.x+n*(t.x+n*i.x/2),e.y+n*(t.y+n*i.y/2),e.z+n*(t.z+n*i.z/2))}function h5(n,e,t){return new qh(e.x+n*t.x,e.y+n*t.y,e.z+n*t.z)}function IA(n,e){const t=n-e.tt,i=new eC(n),r=Jy(t,e.r,e.v,e.a),a=i.Acceleration(r).mean(e.a),s=Jy(t,e.r,e.v,a),o=e.v.add(a.mul(t)),l=i.Acceleration(s),u=new FB(n,s,o,l);return new VB(i,u)}const Aoe=[];function GB(n,e){const t=Math.floor(n);return t<0?0:t>=e?e-1:t}function UA(n){const e=Moe(n),t=new eC(e.tt),i=e.r.add(t.Sun.r),r=e.v.add(t.Sun.v),a=t.Acceleration(i),s=new FB(e.tt,i,r,a);return new VB(t,s)}function woe(n,e){const t=vh[0][0];if(evh[LA-1][0])return null;const i=GB((e-t)/boe,LA-1);if(!n[i]){const a=n[i]=[];a[0]=UA(vh[i]).grav,a[vl-1]=UA(vh[i+1]).grav;let s,o=a[0].tt;for(s=1;s0;--s)r[s]=IA(o-=qf,r[s+1]).grav;for(s=vl-2;s>0;--s){const l=s/(vl-1);a[s].r=a[s].r.mul(1-l).add(r[s].r.mul(l)),a[s].v=a[s].v.mul(1-l).add(r[s].v.mul(l)),a[s].a=a[s].a.mul(1-l).add(r[s].a.mul(l))}}return n[i]}function d5(n,e,t){let i=UA(n);const r=Math.ceil((e-i.grav.tt)/t);for(let a=0;a1)throw"Object is too distant for light-travel solver.";const o=e.AddDays(-s);if(i=Math.abs(o.tt-t.tt),i<1e-9)return a;t=o}throw`Light-travel time solver did not converge: dt = ${i}`}class Doe{constructor(e,t,i,r){this.observerBody=e,this.targetBody=t,this.aberration=i,this.observerPos=r}Position(e){this.aberration&&(this.observerPos=lg(this.observerBody,e));const t=lg(this.targetBody,e);return new Js(t.x-this.observerPos.x,t.y-this.observerPos.y,t.z-this.observerPos.z,e)}}function Noe(n,e,t,i){const r=sd(n);if(IB(t)){const o=lg(t,r),l=lg(e,r);return new Js(o.x-l.x,o.y-l.y,o.z-l.z,r)}let a;a=lg(e,r);const s=new Doe(e,t,i,a);return Coe(o=>s.Position(o),r)}function Ooe(n,e,t){const i=sd(e);switch(n){case kn.Earth:return new Js(0,0,0,i);case kn.Moon:return RA(i);default:const r=Noe(i,kn.Earth,n,t);return r.t=i,r}}var f5;(function(n){n[n.Pericenter=0]="Pericenter",n[n.Apocenter=1]="Apocenter"})(f5||(f5={}));function Loe(n,e){return new zp([[e.rot[0][0]*n.rot[0][0]+e.rot[1][0]*n.rot[0][1]+e.rot[2][0]*n.rot[0][2],e.rot[0][1]*n.rot[0][0]+e.rot[1][1]*n.rot[0][1]+e.rot[2][1]*n.rot[0][2],e.rot[0][2]*n.rot[0][0]+e.rot[1][2]*n.rot[0][1]+e.rot[2][2]*n.rot[0][2]],[e.rot[0][0]*n.rot[1][0]+e.rot[1][0]*n.rot[1][1]+e.rot[2][0]*n.rot[1][2],e.rot[0][1]*n.rot[1][0]+e.rot[1][1]*n.rot[1][1]+e.rot[2][1]*n.rot[1][2],e.rot[0][2]*n.rot[1][0]+e.rot[1][2]*n.rot[1][1]+e.rot[2][2]*n.rot[1][2]],[e.rot[0][0]*n.rot[2][0]+e.rot[1][0]*n.rot[2][1]+e.rot[2][0]*n.rot[2][2],e.rot[0][1]*n.rot[2][0]+e.rot[1][1]*n.rot[2][1]+e.rot[2][1]*n.rot[2][2],e.rot[0][2]*n.rot[2][0]+e.rot[1][2]*n.rot[2][1]+e.rot[2][2]*n.rot[2][2]]])}function Ioe(n,e,t){const i=m1(t)*Xh,r=Math.cos(i),a=Math.sin(i),s=(e+1)%3,o=(e+2)%3,l=e;let u=[[0,0,0],[0,0,0],[0,0,0]];return u[s][s]=r*n.rot[s][s]-a*n.rot[s][o],u[s][o]=a*n.rot[s][s]+r*n.rot[s][o],u[s][l]=n.rot[s][l],u[o][s]=r*n.rot[o][s]-a*n.rot[o][o],u[o][o]=a*n.rot[o][s]+r*n.rot[o][o],u[o][l]=n.rot[o][l],u[l][s]=r*n.rot[l][s]-a*n.rot[l][o],u[l][o]=a*n.rot[l][s]+r*n.rot[l][o],u[l][l]=n.rot[l][l],new zp(u)}function Uoe(n,e){e=sd(e);const t=n.lat*Xh,i=n.lon*Xh,r=n.dist*Math.cos(t);return new Js(r*Math.cos(i),r*Math.sin(i),n.dist*Math.sin(t),e)}function Poe(n){n=sd(n);const e=zB(n,Bl.From2000),t=xoe(n,Bl.From2000);return Loe(e,t)}var p5;(function(n){n.Penumbral="penumbral",n.Partial="partial",n.Annular="annular",n.Total="total"})(p5||(p5={}));var m5;(function(n){n[n.Invalid=0]="Invalid",n[n.Ascending=1]="Ascending",n[n.Descending=-1]="Descending"})(m5||(m5={}));function tC(n){return n instanceof Yc?n:new Yc(n instanceof Date?n:new Date(n))}function zoe(n,e=new D){const{x:t,y:i,z:r}=n;return e.set(t,i,r)}function Boe(n,e=new Me){const[t,i,r]=n.rot;return e.set(t[0],i[0],r[0],0,t[1],i[1],r[1],0,t[2],i[2],r[2],0,0,0,0,1)}function Foe(n,e=new Me){const t=tC(n),i=Ioe(Poe(t),2,-15*_oe(t));return Boe(i,e)}function kB(n,e,t,i,r){const a=Ooe(n,e,!1);return zoe(a,t),i!=null,t.normalize()}function Hoe(n,e=new D,t){return kB(kn.Sun,tC(n),e,t)}function Voe(n,e=new D,t){return kB(kn.Moon,tC(n),e,t)}const Goe=`precision highp float; +precision highp sampler3D; + +#include "bruneton/definitions" +#include "bruneton/common" +#include "bruneton/precompute" + +uniform AtmosphereParameters ATMOSPHERE; + +uniform sampler2D transmittanceTexture; + +layout(location = 0) out vec4 outputColor; + +void main() { + vec3 deltaIrradiance; + vec3 irradiance; + deltaIrradiance = ComputeDirectIrradianceTexture( + ATMOSPHERE, + transmittanceTexture, + gl_FragCoord.xy + ); + irradiance = vec3(0.0); + outputColor = vec4(OUTPUT, 1.0); +} +`,koe=`precision highp float; +precision highp sampler3D; + +#include "bruneton/definitions" +#include "bruneton/common" +#include "bruneton/precompute" + +uniform AtmosphereParameters ATMOSPHERE; + +uniform mat3 luminanceFromRadiance; +uniform sampler3D singleRayleighScatteringTexture; +uniform sampler3D singleMieScatteringTexture; +uniform sampler3D multipleScatteringTexture; +uniform int scatteringOrder; + +layout(location = 0) out vec4 outputColor; + +void main() { + vec3 deltaIrradiance; + vec3 irradiance; + deltaIrradiance = ComputeIndirectIrradianceTexture( + ATMOSPHERE, + singleRayleighScatteringTexture, + singleMieScatteringTexture, + multipleScatteringTexture, + gl_FragCoord.xy, + scatteringOrder + ); + irradiance = luminanceFromRadiance * deltaIrradiance; + outputColor = vec4(OUTPUT, 1.0); +} +`,Woe=`precision highp float; +precision highp sampler3D; + +#include "bruneton/definitions" +#include "bruneton/common" +#include "bruneton/precompute" + +uniform AtmosphereParameters ATMOSPHERE; + +uniform mat3 luminanceFromRadiance; +uniform sampler2D transmittanceTexture; +uniform sampler3D scatteringDensityTexture; +uniform int layer; + +layout(location = 0) out vec4 outputColor; + +void main() { + vec4 deltaMultipleScattering; + vec4 scattering; + float nu; + deltaMultipleScattering.rgb = ComputeMultipleScatteringTexture( + ATMOSPHERE, + transmittanceTexture, + scatteringDensityTexture, + vec3(gl_FragCoord.xy, float(layer) + 0.5), + nu + ); + deltaMultipleScattering.a = 1.0; + scattering = vec4( + luminanceFromRadiance * deltaMultipleScattering.rgb / RayleighPhaseFunction(nu), + 0.0 + ); + outputColor = OUTPUT; +} +`,Xoe=`precision highp float; +precision highp sampler3D; + +#include "bruneton/definitions" +#include "bruneton/common" +#include "bruneton/precompute" + +uniform AtmosphereParameters ATMOSPHERE; + +uniform sampler2D transmittanceTexture; +uniform sampler3D singleRayleighScatteringTexture; +uniform sampler3D singleMieScatteringTexture; +uniform sampler3D multipleScatteringTexture; +uniform sampler2D irradianceTexture; +uniform int scatteringOrder; +uniform int layer; + +layout(location = 0) out vec4 scatteringDensity; + +void main() { + scatteringDensity.rgb = ComputeScatteringDensityTexture( + ATMOSPHERE, + transmittanceTexture, + singleRayleighScatteringTexture, + singleMieScatteringTexture, + multipleScatteringTexture, + irradianceTexture, + vec3(gl_FragCoord.xy, float(layer) + 0.5), + scatteringOrder + ); + scatteringDensity.a = 1.0; +} +`,qoe=`precision highp float; +precision highp sampler3D; + +#include "bruneton/definitions" +#include "bruneton/common" +#include "bruneton/precompute" + +uniform AtmosphereParameters ATMOSPHERE; + +uniform mat3 luminanceFromRadiance; +uniform sampler2D transmittanceTexture; +uniform int layer; + +layout(location = 0) out vec4 outputColor; + +void main() { + vec4 deltaRayleigh; + vec4 deltaMie; + vec4 scattering; + vec4 singleMieScattering; + ComputeSingleScatteringTexture( + ATMOSPHERE, + transmittanceTexture, + vec3(gl_FragCoord.xy, float(layer) + 0.5), + deltaRayleigh.rgb, + deltaMie.rgb + ); + deltaRayleigh.a = 1.0; + deltaMie.a = 1.0; + scattering = vec4( + luminanceFromRadiance * deltaRayleigh.rgb, + (luminanceFromRadiance * deltaMie.rgb).r + ); + singleMieScattering.rgb = luminanceFromRadiance * deltaMie.rgb; + singleMieScattering.a = 1.0; + outputColor = OUTPUT; +} +`,Yoe=`precision highp float; +precision highp sampler3D; + +#include "bruneton/definitions" +#include "bruneton/common" +#include "bruneton/precompute" + +uniform AtmosphereParameters ATMOSPHERE; + +layout(location = 0) out vec4 transmittance; + +void main() { + transmittance.rgb = ComputeTransmittanceToTopAtmosphereBoundaryTexture( + ATMOSPHERE, + gl_FragCoord.xy + ); + transmittance.a = 1.0; +} +`,joe=` + precision highp float; + in vec2 position; + void main() { + gl_Position = vec4(position, 1.0, 1.0); + } +`;function $y(n,e,t){const i=new pi(e,t,{depthBuffer:!1,type:n,format:ai}),r=i.texture;return r.minFilter=Bt,r.magFilter=Bt,r.wrapS=Wi,r.wrapT=Wi,r.colorSpace=Xr,i}function sp(n,e,t,i){const r=new L9(e,t,i,{depthBuffer:!1,type:n,format:ai}),a=r.texture;return a.minFilter=Bt,a.magFilter=Bt,a.wrapS=Wi,a.wrapT=Wi,a.wrapR=Wi,a.colorSpace=Xr,r}function Zoe(n){const e=n[Symbol.iterator]();return new Promise((t,i)=>{const r=()=>{try{const{value:a,done:s}=e.next();s===!0?t(a):l5(r)}catch(a){i(a instanceof Error?a:new Error)}};l5(r)})}async function g5(n,e,t){const{width:i,height:r}=e,a=t.type===Jn?new Uint16Array(i*r*4):new Float32Array(i*r*4);await n.readRenderTargetPixelsAsync(e,0,0,e.width,e.height,a),t.userData.imageData=a}let Qoe=class{constructor(e){this.lambdas=new D,this.luminanceFromRadiance=new Mt,e===Jn&&(this.opticalDepth=$y(e,rm,am)),this.deltaIrradiance=$y(e,nm,im),this.deltaRayleighScattering=sp(e,Ah,wh,Rh),this.deltaMieScattering=sp(e,Ah,wh,Rh),this.deltaScatteringDensity=sp(e,Ah,wh,Rh),this.deltaMultipleScattering=this.deltaRayleighScattering}dispose(){var e;(e=this.opticalDepth)==null||e.dispose(),this.deltaIrradiance.dispose(),this.deltaRayleighScattering.dispose(),this.deltaMieScattering.dispose(),this.deltaScatteringDensity.dispose()}};class pf extends td{constructor(e){super({glslVersion:No,vertexShader:joe,...e,defines:{TRANSMITTANCE_TEXTURE_WIDTH:rm.toFixed(0),TRANSMITTANCE_TEXTURE_HEIGHT:am.toFixed(0),SCATTERING_TEXTURE_R_SIZE:xT.toFixed(0),SCATTERING_TEXTURE_MU_SIZE:yT.toFixed(0),SCATTERING_TEXTURE_MU_S_SIZE:ST.toFixed(0),SCATTERING_TEXTURE_NU_SIZE:TT.toFixed(0),IRRADIANCE_TEXTURE_WIDTH:nm.toFixed(0),IRRADIANCE_TEXTURE_HEIGHT:im.toFixed(0),...e.defines}})}set additive(e){this.transparent=e,this.blending=e?AS:Lr,this.blendEquation=bo,this.blendEquationAlpha=bo,this.blendSrc=uh,this.blendDst=uh,this.blendSrcAlpha=uh,this.blendDstAlpha=uh}setUniforms(e){const t=this.uniforms;t.luminanceFromRadiance!=null&&t.luminanceFromRadiance.value.copy(e.luminanceFromRadiance),t.singleRayleighScatteringTexture!=null&&(t.singleRayleighScatteringTexture.value=e.deltaRayleighScattering.texture),t.singleMieScatteringTexture!=null&&(t.singleMieScatteringTexture.value=e.deltaMieScattering.texture),t.multipleScatteringTexture!=null&&(t.multipleScatteringTexture.value=e.deltaMultipleScattering.texture),t.scatteringDensityTexture!=null&&(t.scatteringDensityTexture.value=e.deltaScatteringDensity.texture),t.irradianceTexture!=null&&(t.irradianceTexture.value=e.deltaIrradiance.texture)}}let Koe=class{constructor(e,{type:t=Kz(e)?fi:Jn,combinedScattering:i=!0,higherOrderScattering:r=!0}={}){var a,s;this.transmittanceMaterial=new pf({fragmentShader:Wr(Yoe,{bruneton:{common:To,definitions:Eo,precompute:hf}})}),this.directIrradianceMaterial=new pf({fragmentShader:Wr(Goe,{bruneton:{common:To,definitions:Eo,precompute:hf}}),uniforms:{transmittanceTexture:new $(null)}}),this.singleScatteringMaterial=new pf({fragmentShader:Wr(qoe,{bruneton:{common:To,definitions:Eo,precompute:hf}}),uniforms:{luminanceFromRadiance:new $(new Mt),transmittanceTexture:new $(null),layer:new $(0)}}),this.scatteringDensityMaterial=new pf({fragmentShader:Wr(Xoe,{bruneton:{common:To,definitions:Eo,precompute:hf}}),uniforms:{transmittanceTexture:new $(null),singleRayleighScatteringTexture:new $(null),singleMieScatteringTexture:new $(null),multipleScatteringTexture:new $(null),irradianceTexture:new $(null),scatteringOrder:new $(0),layer:new $(0)}}),this.indirectIrradianceMaterial=new pf({fragmentShader:Wr(koe,{bruneton:{common:To,definitions:Eo,precompute:hf}}),uniforms:{luminanceFromRadiance:new $(new Mt),singleRayleighScatteringTexture:new $(null),singleMieScatteringTexture:new $(null),multipleScatteringTexture:new $(null),scatteringOrder:new $(0)}}),this.multipleScatteringMaterial=new pf({fragmentShader:Wr(Woe,{bruneton:{common:To,definitions:Eo,precompute:hf}}),uniforms:{luminanceFromRadiance:new $(new Mt),transmittanceTexture:new $(null),scatteringDensityTexture:new $(null),layer:new $(0)}}),this.mesh=new jn(new uu(2,2)),this.scene=new Rp().add(this.mesh),this.camera=new ou,this.updating=!1,this.renderer=e,this.type=t,this.transmittanceRenderTarget=$y(t,rm,am),this.scatteringRenderTarget=sp(t,Ah,wh,Rh),this.irradianceRenderTarget=$y(t,nm,im),i||(this.singleMieScatteringRenderTarget=sp(t,Ah,wh,Rh)),r&&(this.higherOrderScatteringRenderTarget=sp(t,Ah,wh,Rh)),this.textures={transmittanceTexture:this.transmittanceRenderTarget.texture,scatteringTexture:this.scatteringRenderTarget.texture,irradianceTexture:this.irradianceRenderTarget.texture,singleMieScatteringTexture:(a=this.singleMieScatteringRenderTarget)==null?void 0:a.texture,higherOrderScatteringTexture:(s=this.higherOrderScatteringRenderTarget)==null?void 0:s.texture}}render3DRenderTarget(e,t){for(let i=0;i{this.dispose(e),this.disposeQueue=void 0};return}const{textures:t=!0}=e;t||(this.transmittanceRenderTarget.textures.splice(0,1),this.scatteringRenderTarget.textures.splice(0,1),this.irradianceRenderTarget.textures.splice(0,1),(i=this.singleMieScatteringRenderTarget)==null||i.textures.splice(0,1),(r=this.higherOrderScatteringRenderTarget)==null||r.textures.splice(0,1)),this.transmittanceRenderTarget.dispose(),this.scatteringRenderTarget.dispose(),this.irradianceRenderTarget.dispose(),(a=this.singleMieScatteringRenderTarget)==null||a.dispose(),(s=this.higherOrderScatteringRenderTarget)==null||s.dispose(),this.transmittanceMaterial.dispose(),this.directIrradianceMaterial.dispose(),this.singleScatteringMaterial.dispose(),this.scatteringDensityMaterial.dispose(),this.indirectIrradianceMaterial.dispose(),this.multipleScatteringMaterial.dispose(),this.mesh.geometry.dispose()}};function Joe(n){var e=[];if(n.length===0)return"";if(typeof n[0]!="string")throw new TypeError("Url must be a string. Received "+n[0]);if(n[0].match(/^[^/:]+:\/*$/)&&n.length>1){var t=n.shift();n[0]=t+n[0]}n[0].match(/^file:\/\/\//)?n[0]=n[0].replace(/^([^/:]+):\/*/,"$1:///"):n[0]=n[0].replace(/^([^/:]+):\/*/,"$1://");for(var i=0;i0&&(r=r.replace(/^[\/]+/,"")),i0?"?":"")+s.join("&"),a}function $oe(){var n;return typeof arguments[0]=="object"?n=arguments[0]:n=[].slice.call(arguments),Joe(n)}const v5={width:rm,height:am},mf={width:Ah,height:wh,depth:Rh},_5={width:nm,height:im};class WB extends wi{constructor({format:e="exr",type:t=Jn,combinedScattering:i=!0,higherOrderScattering:r=!0}={},a){super(a),this.format=e,this.type=t,this.combinedScattering=i,this.higherOrderScattering=r}setType(e){return this.type=Kz(e)?fi:Jn,this}setTypeFromRenderer(e){return this.setType(e)}load(e,t,i,r){const a={},s=({key:o,loader:l,path:u})=>(l.setRequestHeader(this.requestHeader),l.setPath(this.path),l.setWithCredentials(this.withCredentials),l.load($oe(e,u),d=>{d.type=this.type,this.type===fi&&(d.image.data=new Float32Array(new Vl(d.image.data.buffer))),d.minFilter=Bt,d.magFilter=Bt,a[`${o}Texture`]=d,a.irradianceTexture!=null&&a.scatteringTexture!=null&&a.transmittanceTexture!=null&&(this.combinedScattering||a.singleMieScatteringTexture!=null)&&(!this.higherOrderScattering||a.higherOrderScatteringTexture!=null)&&(t==null||t(a))},i,r));return this.format==="exr"?{transmittanceTexture:s({key:"transmittance",loader:new o5(v5,this.manager),path:"transmittance.exr"}),scatteringTexture:s({key:"scattering",loader:new sM(mf,this.manager),path:"scattering.exr"}),irradianceTexture:s({key:"irradiance",loader:new o5(_5,this.manager),path:"irradiance.exr"}),singleMieScatteringTexture:this.combinedScattering?void 0:s({key:"singleMieScattering",loader:new sM(mf,this.manager),path:"single_mie_scattering.exr"}),higherOrderScatteringTexture:this.higherOrderScattering?s({key:"higherOrderScattering",loader:new sM(mf,this.manager),path:"higher_order_scattering.exr"}):void 0}:{transmittanceTexture:s({key:"transmittance",loader:new ch(Ur,a0,v5,this.manager),path:"transmittance.bin"}),scatteringTexture:s({key:"scattering",loader:new ch(ws,a0,mf,this.manager),path:"scattering.bin"}),irradianceTexture:s({key:"irradiance",loader:new ch(Ur,a0,_5,this.manager),path:"irradiance.bin"}),singleMieScatteringTexture:this.combinedScattering?void 0:s({key:"singleMieScattering",loader:new ch(ws,a0,mf,this.manager),path:"single_mie_scattering.bin"}),higherOrderScatteringTexture:this.higherOrderScattering?s({key:"higherOrderScattering",loader:new ch(ws,a0,mf,this.manager),path:"higher_order_scattering.bin"}):void 0}}}const ele=`precision highp float; +precision highp sampler3D; + +#define RECIPROCAL_PI 0.3183098861837907 + +#include "core/raySphereIntersection" + +#include "bruneton/definitions" + +uniform AtmosphereParameters ATMOSPHERE; +uniform vec3 SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; +uniform vec3 SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; + +uniform sampler2D transmittance_texture; +uniform sampler3D scattering_texture; +uniform sampler2D irradiance_texture; +uniform sampler3D single_mie_scattering_texture; +uniform sampler3D higher_order_scattering_texture; + +#include "bruneton/common" +#include "bruneton/runtime" + +#include "sky" + +uniform vec3 sunDirection; +uniform vec3 moonDirection; +uniform float moonAngularRadius; +uniform float lunarRadianceScale; +uniform vec3 groundAlbedo; + +#ifdef HAS_SHADOW_LENGTH +uniform sampler2D shadowLengthBuffer; +#endif // HAS_SHADOW_LENGTH + +in vec2 vUv; +in vec3 vCameraPosition; +in vec3 vRayDirection; + +layout(location = 0) out vec4 outputColor; + +#include + +void main() { + float shadowLength = 0.0; + #ifdef HAS_SHADOW_LENGTH + shadowLength = texture(shadowLengthBuffer, vUv).r; + #endif // HAS_SHADOW_LENGTH + + vec3 cameraPosition = vCameraPosition; + vec3 rayDirection = normalize(vRayDirection); + + #ifdef GROUND_ALBEDO + + float r = length(cameraPosition); + float mu = dot(cameraPosition, rayDirection) / r; + bool intersectsGround = RayIntersectsGround(ATMOSPHERE, r, mu); + if (intersectsGround) { + float distanceToGround = raySphereFirstIntersection( + cameraPosition, + rayDirection, + ATMOSPHERE.bottom_radius + ); + vec3 groundPosition = rayDirection * distanceToGround + cameraPosition; + vec3 surfaceNormal = normalize(groundPosition); + vec3 skyIrradiance; + vec3 sunIrradiance = GetSunAndSkyIrradiance( + cameraPosition, + surfaceNormal, + sunDirection, + skyIrradiance + ); + vec3 transmittance; + vec3 inscatter = GetSkyRadianceToPoint( + cameraPosition, + ATMOSPHERE.bottom_radius * surfaceNormal, + shadowLength, + sunDirection, + transmittance + ); + vec3 radiance = groundAlbedo * RECIPROCAL_PI * (sunIrradiance + skyIrradiance); + outputColor.rgb = radiance * transmittance + inscatter; + } else { + outputColor.rgb = getSkyRadiance( + cameraPosition, + rayDirection, + shadowLength, + sunDirection, + moonDirection, + moonAngularRadius, + lunarRadianceScale + ); + } + + #else // GROUND_ALBEDO + + outputColor.rgb = getSkyRadiance( + cameraPosition, + rayDirection, + shadowLength, + sunDirection, + moonDirection, + moonAngularRadius, + lunarRadianceScale + ); + + #endif // GROUND_ALBEDO + + outputColor.a = 1.0; + + #include +} +`,tle=`precision highp float; +precision highp sampler3D; + +uniform mat4 inverseProjectionMatrix; +uniform mat4 inverseViewMatrix; +uniform vec3 cameraPosition; +uniform mat4 worldToECEFMatrix; +uniform vec3 altitudeCorrection; + +layout(location = 0) in vec3 position; + +out vec2 vUv; +out vec3 vCameraPosition; +out vec3 vRayDirection; + +void getCameraRay(out vec3 origin, out vec3 direction) { + bool isPerspective = inverseProjectionMatrix[2][3] != 0.0; // 4th entry in the 3rd column + + if (isPerspective) { + // Calculate the camera ray for a perspective camera. + vec4 viewPosition = inverseProjectionMatrix * vec4(position, 1.0); + vec4 worldDirection = inverseViewMatrix * vec4(viewPosition.xyz, 0.0); + origin = cameraPosition; + direction = worldDirection.xyz; + } else { + // Unprojected points to calculate direction. + vec4 nearPoint = inverseProjectionMatrix * vec4(position.xy, -1.0, 1.0); + vec4 farPoint = inverseProjectionMatrix * vec4(position.xy, -0.9, 1.0); + nearPoint /= nearPoint.w; + farPoint /= farPoint.w; + + // Calculate world values + vec4 worldDirection = inverseViewMatrix * vec4(farPoint.xyz - nearPoint.xyz, 0.0); + vec4 worldOrigin = inverseViewMatrix * nearPoint; + + // Outputs + direction = worldDirection.xyz; + origin = worldOrigin.xyz; + } +} + +void main() { + vUv = position.xy * 0.5 + 0.5; + + vec3 direction, origin; + getCameraRay(origin, direction); + + vec3 cameraPositionECEF = (worldToECEFMatrix * vec4(origin, 1.0)).xyz; + vCameraPosition = (cameraPositionECEF + altitudeCorrection) * METER_TO_LENGTH_UNIT; + vRayDirection = (worldToECEFMatrix * vec4(direction, 0.0)).xyz; + + gl_Position = vec4(position.xy, 1.0, 1.0); +} +`;var nle=Object.defineProperty,nC=(n,e,t,i)=>{for(var r=void 0,a=n.length-1,s;a>=0;a--)(s=n[a])&&(r=s(e,t,r)||r);return r&&nle(e,t,r),r};const ile={...JR,sun:!0,moon:!0,moonAngularRadius:.0045,lunarRadianceScale:1,ground:!0,groundAlbedo:new Ye(0)};let iC=class extends gv{constructor(e){const{sun:t,moon:i,moonDirection:r,moonAngularRadius:a,lunarRadianceScale:s,ground:o,groundAlbedo:l,...u}={...ile,...e};super({name:"SkyMaterial",glslVersion:No,vertexShader:tle,fragmentShader:Wr(ele,{core:{raySphereIntersection:_T},bruneton:{common:To,definitions:Eo,runtime:ET},sky:NB}),...u,uniforms:{inverseProjectionMatrix:new $(new Me),inverseViewMatrix:new $(new Me),moonDirection:new $((r==null?void 0:r.clone())??new D),moonAngularRadius:new $(a),lunarRadianceScale:new $(s),groundAlbedo:new $(l.clone()),shadowLengthBuffer:new $(null),...u.uniforms},defines:{PERSPECTIVE_CAMERA:"1"},depthTest:!0}),this.shadowLength=null,this.sun=t,this.moon=i,this.ground=o}onBeforeRender(e,t,i,r,a,s){super.onBeforeRender(e,t,i,r,a,s);const{uniforms:o,defines:l}=this;o.inverseProjectionMatrix.value.copy(i.projectionMatrixInverse),o.inverseViewMatrix.value.copy(i.matrixWorld);const u=l.PERSPECTIVE_CAMERA!=null,d=i.isPerspectiveCamera===!0;d!==u&&(d?l.PERSPECTIVE_CAMERA="1":delete l.PERSPECTIVE_CAMERA,this.needsUpdate=!0);const f=this.groundAlbedo,p=l.GROUND_ALBEDO!=null,m=f.r!==0||f.g!==0||f.b!==0;m!==p&&(m?this.defines.GROUND_ALBEDO="1":delete this.defines.GROUND_ALBEDO,this.needsUpdate=!0);const v=this.shadowLength,x=l.HAS_SHADOW_LENGTH!=null,S=v!=null;S!==x&&(S?l.HAS_SHADOW_LENGTH="1":(delete l.HAS_SHADOW_LENGTH,o.shadowLengthBuffer.value=null),this.needsUpdate=!0),S&&(o.shadowLengthBuffer.value=v.map)}get moonDirection(){return this.uniforms.moonDirection.value}get moonAngularRadius(){return this.uniforms.moonAngularRadius.value}set moonAngularRadius(e){this.uniforms.moonAngularRadius.value=e}get lunarRadianceScale(){return this.uniforms.lunarRadianceScale.value}set lunarRadianceScale(e){this.uniforms.lunarRadianceScale.value=e}get groundAlbedo(){return this.uniforms.groundAlbedo.value}};nC([gn("SUN")],iC.prototype,"sun");nC([gn("MOON")],iC.prototype,"moon");nC([gn("GROUND")],iC.prototype,"ground");const rle=`precision highp float; +precision highp sampler3D; + +#include "bruneton/definitions" + +uniform AtmosphereParameters ATMOSPHERE; +uniform vec3 SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; +uniform vec3 SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; + +uniform sampler2D transmittance_texture; +uniform sampler3D scattering_texture; +uniform sampler2D irradiance_texture; +uniform sampler3D single_mie_scattering_texture; +uniform sampler3D higher_order_scattering_texture; + +#include "bruneton/common" +#include "bruneton/runtime" + +uniform vec3 sunDirection; + +in vec3 vCameraPosition; +in vec3 vRayDirection; + +layout(location = 0) out vec4 outputColor; + +#include + +in vec3 vColor; + +void main() { + #if !defined(PERSPECTIVE_CAMERA) + outputColor = vec4(0.0); + discard; // Rendering celestial objects without perspective doesn't make sense. + #endif // !defined(PERSPECTIVE_CAMERA) + + #ifdef BACKGROUND + vec3 rayDirection = normalize(vRayDirection); + float r = length(vCameraPosition); + float mu = dot(vCameraPosition, rayDirection) / r; + + if (RayIntersectsGround(ATMOSPHERE, r, mu)) { + discard; + } + + vec3 transmittance; + vec3 radiance = GetSkyRadiance( + vCameraPosition, + normalize(vRayDirection), + 0.0, // Shadow length + sunDirection, + transmittance + ); + radiance += transmittance * vColor; + outputColor = vec4(radiance, 1.0); + #else // BACKGROUND + outputColor = vec4(vColor, 1.0); + #endif // BACKGROUND + + #include +} +`,ale=`precision highp float; +precision highp sampler3D; + +#define saturate(x) clamp(x, 0.0, 1.0) + +uniform mat4 projectionMatrix; +uniform mat4 modelViewMatrix; +uniform mat4 viewMatrix; +uniform mat4 matrixWorld; +uniform vec3 cameraPosition; +uniform float cameraFar; +uniform mat4 worldToECEFMatrix; +uniform vec3 altitudeCorrection; +uniform float pointSize; +uniform vec2 magnitudeRange; +uniform float intensity; + +layout(location = 0) in vec3 position; +layout(location = 1) in float magnitude; +layout(location = 2) in vec3 color; + +out vec3 vCameraPosition; +out vec3 vRayDirection; +out vec3 vEllipsoidCenter; +out vec3 vColor; + +void main() { + // Magnitude is stored between 0 to 1 within the given range. + float m = mix(magnitudeRange.x, magnitudeRange.y, magnitude); + vec3 v = pow(vec3(10.0), -vec3(magnitudeRange, m) / 2.5); + vColor = vec3(intensity * color); + vColor *= saturate((v.z - v.y) / (v.x - v.y)); + + #ifdef BACKGROUND + vec3 worldDirection = normalize(matrixWorld * vec4(position, 1.0)).xyz; + vec3 cameraPositionECEF = (worldToECEFMatrix * vec4(cameraPosition, 1.0)).xyz; + vCameraPosition = (cameraPositionECEF + altitudeCorrection) * METER_TO_LENGTH_UNIT; + vRayDirection = (worldToECEFMatrix * vec4(worldDirection, 0.0)).xyz; + gl_Position = + projectionMatrix * viewMatrix * vec4(cameraPosition + worldDirection * cameraFar, 1.0); + #else // BACKGROUND + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + #endif // BACKGROUND + + gl_PointSize = pointSize; +} +`;var sle=Object.defineProperty,XB=(n,e,t,i)=>{for(var r=void 0,a=n.length-1,s;a>=0;a--)(s=n[a])&&(r=s(e,t,r)||r);return r&&sle(e,t,r),r};const ole={...JR,pointSize:1,intensity:1,background:!0,ground:!0};let qB=class extends gv{constructor(e){const{pointSize:t,radianceScale:i,intensity:r,background:a,ground:s,...o}={...ole,...e};super({name:"StarsMaterial",glslVersion:No,vertexShader:ale,fragmentShader:Wr(rle,{bruneton:{common:To,definitions:Eo,runtime:ET}}),...o,uniforms:{projectionMatrix:new $(new Me),modelViewMatrix:new $(new Me),viewMatrix:new $(new Me),matrixWorld:new $(new Me),cameraFar:new $(0),pointSize:new $(0),magnitudeRange:new $(new re(-2,8)),intensity:new $(i??r),...o.uniforms},defines:{PERSPECTIVE_CAMERA:"1"}}),this.pointSize=t,this.background=a,this.ground=s}onBeforeRender(e,t,i,r,a,s){super.onBeforeRender(e,t,i,r,a,s);const o=this.uniforms;o.projectionMatrix.value.copy(i.projectionMatrix),o.modelViewMatrix.value.copy(i.modelViewMatrix),o.viewMatrix.value.copy(i.matrixWorldInverse),o.matrixWorld.value.copy(a.matrixWorld),o.cameraFar.value=i.far,o.pointSize.value=this.pointSize*e.getPixelRatio();const l=i.isPerspectiveCamera===!0;this.defines.PERSPECTIVE_CAMERA!=null!==l&&(l?this.defines.PERSPECTIVE_CAMERA="1":delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0)}get magnitudeRange(){return this.uniforms.magnitudeRange.value}get radianceScale(){return this.intensity}set radianceScale(e){this.intensity=e}get intensity(){return this.uniforms.intensity.value}set intensity(e){this.uniforms.intensity.value=e}};XB([gn("BACKGROUND")],qB.prototype,"background");XB([gn("GROUND")],qB.prototype,"ground");const rC=ie.createContext({}),lle=({ref:n,textures:e,ellipsoid:t=kh.WGS84,correctAltitude:i=!0,ground:r=!0,date:a,children:s})=>{const o=ie.useRef({sunDirection:new D,moonDirection:new D,worldToECEFMatrix:new Me,inertialToECEFMatrix:new Me,overlay:null,shadow:null,shadowLength:null,lightingMask:null}),l=pn(({gl:x})=>x),u=ie.useMemo(()=>typeof e=="string"?new WB().setType(l).load(e):void 0,[e,l]);ie.useEffect(()=>{if(u!=null)return()=>{for(const x of Object.values(u))x==null||x.dispose()}},[u]);const d=ie.useMemo(()=>e==null?new Koe(l):void 0,[e,l]);ie.useEffect(()=>{if(d!=null)return d.update().catch(x=>{console.error(x)}),()=>{d.dispose()}},[d]);const f=(d==null?void 0:d.textures)??(typeof e=="string"?u:e),p=ie.useMemo(()=>({textures:f,ellipsoid:t,correctAltitude:i,ground:r,transientStates:o.current}),[f,t,i,r]),m=ie.useMemo(()=>{const{sunDirection:x,moonDirection:S,inertialToECEFMatrix:_}=o.current;return T=>{Foe(T,_),Hoe(T,x).applyMatrix4(_),Voe(T,S).applyMatrix4(_)}},[]),v=a!=null&&!isNaN(+a)?+a:void 0;return ie.useEffect(()=>{v!=null&&m(v)},[v,m]),ie.useImperativeHandle(n,()=>({...o.current,textures:f,updateByDate:m}),[f,m]),ot.jsx(rC.Provider,{value:p,children:s})};function YB(n){const{irradianceTexture:e,scatteringTexture:t,transmittanceTexture:i,singleMieScatteringTexture:r,higherOrderScatteringTexture:a,ellipsoid:s,correctAltitude:o,sunDirection:l,sunAngularRadius:u,ground:d,renderTargetCount:f,...p}=n;return[{irradianceTexture:e,scatteringTexture:t,transmittanceTexture:i,singleMieScatteringTexture:r,higherOrderScatteringTexture:a,ellipsoid:s,correctAltitude:o,sunDirection:l,sunAngularRadius:u,ground:d,renderTargetCount:f},p]}function cle(n){const e=ie.useMemo(()=>typeof n=="string"?new MB().load(n):void 0,[n]);return ie.useEffect(()=>{if(e!=null)return()=>{e.dispose()}},[e]),(typeof n=="string"?e:n)??null}const ule=({ref:n,stbnTexture:e=Jz,...t})=>{const{textures:i,transientStates:r,...a}=ie.useContext(rC),[s,{blendFunction:o,...l}]=YB({...OB,...a,...i,...t}),u=ie.useContext(HR),{normalPass:d,camera:f}=u,p="geometryPass"in u&&u.geometryPass instanceof FR&&"geometryTexture"in u.geometryPass&&u.geometryPass.geometryTexture instanceof In?u.geometryPass.geometryTexture:void 0,m=ie.useMemo(()=>new Kr(void 0,{blendFunction:o}),[o]);ie.useEffect(()=>()=>{m.dispose()},[m]);const[v,x]=ie.useState(!1);_a(()=>{r!=null&&(m.sunDirection.copy(r.sunDirection),m.moonDirection.copy(r.moonDirection),m.worldToECEFMatrix.copy(r.worldToECEFMatrix),m.overlay=r.overlay,m.shadow=r.shadow,m.shadowLength=r.shadowLength,m.lightingMask=r.lightingMask,!v&&m.shadow!=null&&x(!0))});const S=cle(v?e:void 0);return ot.jsx("primitive",{ref:n,object:m,mainCamera:f,normalBuffer:p??(d==null?void 0:d.texture)??null,...s,...l,stbnTexture:S,octEncodedNormal:p!=null})};function hle(n){return e=>{for(const t of n)PA(t,e)}}function dle(n){return e=>{const t=[];for(const i of n){const r=PA(i,e),a=typeof r=="function";t.push(a?r:()=>PA(i,null))}return()=>{for(const i of t)i()}}}function PA(n,e){if(typeof n=="function")return n(e);n&&(n.current=e)}parseInt(ie.version.split(".")[0],10)>=19;new WB;const x5=ET,y5=To,S5=Eo;let jB=class ZB{constructor(e=0,t=0,i=0,r=0){this.expTerm=e,this.exponent=t,this.linearTerm=i,this.constantTerm=r}set(e=0,t=0,i=0,r=0){return this.expTerm=e,this.exponent=t,this.linearTerm=i,this.constantTerm=r,this}clone(){return new ZB(this.expTerm,this.exponent,this.linearTerm,this.constantTerm)}copy(e){return this.expTerm=e.expTerm,this.exponent=e.exponent,this.linearTerm=e.linearTerm,this.constantTerm=e.constantTerm,this}};const fle=["channel","altitude","height","densityScale","shapeAmount","shapeDetailAmount","weatherExponent","shapeAlteringBias","coverageFilterWidth","shadow","densityProfile"];function ple(n,e){if(e!=null)for(const t of fle){const i=e[t];i!=null&&(n[t]instanceof jB?n[t].copy(i):n[t]=i)}}const zA=class QB{constructor(e){this.channel="r",this.altitude=0,this.height=0,this.densityScale=.2,this.shapeAmount=1,this.shapeDetailAmount=1,this.weatherExponent=1,this.shapeAlteringBias=.35,this.coverageFilterWidth=.6,this.densityProfile=new jB(0,0,.75,.25),this.shadow=!1,this.set(e)}set(e){return ple(this,e),this}clone(){return new QB(this)}copy(e){return this.channel=e.channel,this.altitude=e.altitude,this.height=e.height,this.densityScale=e.densityScale,this.shapeAmount=e.shapeAmount,this.shapeDetailAmount=e.shapeDetailAmount,this.weatherExponent=e.weatherExponent,this.shapeAlteringBias=e.shapeAlteringBias,this.coverageFilterWidth=e.coverageFilterWidth,this.densityProfile.copy(e.densityProfile),this.shadow=e.shadow,this}};zA.DEFAULT=new zA;let Ys=zA;const gf=Array.from({length:8},()=>({value:0,flag:0})),o0=Array.from({length:3},()=>({min:0,max:0}));function mle(n,e){return n.value!==e.value?n.value-e.value:n.flag-e.flag}const BA=class KB extends Array{constructor(e){super(new Ys(e==null?void 0:e[0]),new Ys(e==null?void 0:e[1]),new Ys(e==null?void 0:e[2]),new Ys(e==null?void 0:e[3]))}set(e){return this[0].set(e==null?void 0:e[0]),this[1].set(e==null?void 0:e[1]),this[2].set(e==null?void 0:e[2]),this[3].set(e==null?void 0:e[3]),this}reset(){return this[0].copy(Ys.DEFAULT),this[1].copy(Ys.DEFAULT),this[2].copy(Ys.DEFAULT),this[3].copy(Ys.DEFAULT),this}clone(){return new KB(this)}copy(e){return this[0].copy(e[0]),this[1].copy(e[1]),this[2].copy(e[2]),this[3].copy(e[3]),this}get localWeatherChannels(){return this[0].channel+this[1].channel+this[2].channel+this[3].channel}packValues(e,t){return t.set(this[0][e],this[1][e],this[2][e],this[3][e])}packSums(e,t,i){return i.set(this[0][e]+this[0][t],this[1][e]+this[1][t],this[2][e]+this[2][t],this[3][e]+this[3][t])}packDensityProfiles(e,t){return t.set(this[0].densityProfile[e],this[1].densityProfile[e],this[2].densityProfile[e],this[3].densityProfile[e])}packIntervalHeights(e,t){for(let s=0;s<4;++s){const o=this[s];let l=gf[s];l.value=o.altitude,l.flag=0,l=gf[s+4],l.value=o.altitude+o.height,l.flag=1}gf.sort(mle);let i=0,r=0;for(let s=0;s0){const u=o0[i++];u.min=gf[s-1].value,u.max=o}r+=l===0?1:-1}for(;i<3;++i){const s=o0[i];s.min=0,s.max=0}let a=o0[0];e.x=a.min,t.x=a.max,a=o0[1],e.y=a.min,t.y=a.max,a=o0[2],e.z=a.min,t.z=a.max}};BA.DEFAULT=new BA([{channel:"r",altitude:750,height:650,densityScale:.2,shapeAmount:1,shapeDetailAmount:1,weatherExponent:1,shapeAlteringBias:.35,coverageFilterWidth:.6,shadow:!0},{channel:"g",altitude:1e3,height:1200,densityScale:.2,shapeAmount:1,shapeDetailAmount:1,weatherExponent:1,shapeAlteringBias:.35,coverageFilterWidth:.6,shadow:!0},{channel:"b",altitude:7500,height:500,densityScale:.003,shapeAmount:.4,shapeDetailAmount:0,weatherExponent:1,shapeAlteringBias:.35,coverageFilterWidth:.5},{channel:"a"}]);let eS=BA;var gle="Invariant failed";function Uc(n,e){if(!n)throw new Error(gle)}let JB=class FA{constructor(e,t){this.near=[new D,new D,new D,new D],this.far=[new D,new D,new D,new D],e!=null&&t!=null&&this.setFromCamera(e,t)}clone(){return new FA().copy(this)}copy(e){for(let t=0;t<4;++t)this.near[t].copy(e.near[t]),this.far[t].copy(e.far[t]);return this}setFromCamera(e,t){const i=e.isOrthographicCamera===!0,r=e.projectionMatrixInverse;this.near[0].set(1,1,-1),this.near[1].set(1,-1,-1),this.near[2].set(-1,-1,-1),this.near[3].set(-1,1,-1);for(let a=0;a<4;++a)this.near[a].applyMatrix4(r);this.far[0].set(1,1,1),this.far[1].set(1,-1,1),this.far[2].set(-1,-1,1),this.far[3].set(-1,1,1);for(let a=0;a<4;++a){const s=this.far[a];s.applyMatrix4(r);const o=Math.abs(s.z);i?s.z*=Math.min(t/o,1):s.multiplyScalar(Math.min(t/o,1))}return this}split(e,t=[]){for(let i=0;i{for(let a=0;a{for(let a=0;a{for(let a=0;a{const i=new re;for(let r=0;r<16;++r)if(M5[r]===t){i.set((r%4+.5)/4,(Math.floor(r/4)+.5)/4);break}return[...n,i]},[]),ble={resolutionScale:1,lightShafts:!0,shapeDetail:!0,turbulence:!0,haze:!0,clouds:{multiScatteringOctaves:8,accurateSunSkyLight:!0,accuratePhaseFunction:!1,maxIterationCount:500,minStepSize:50,maxStepSize:1e3,maxRayDistance:2e5,perspectiveStepScale:1.01,minDensity:1e-5,minExtinction:1e-5,minTransmittance:.01,maxIterationCountToGround:3,maxIterationCountToSun:2,minSecondaryStepSize:100,secondaryStepScale:2,maxShadowLengthIterationCount:500,minShadowLengthStepSize:50,maxShadowLengthRayDistance:2e5},shadow:{cascadeCount:3,mapSize:new re(512,512),maxIterationCount:50,minStepSize:100,maxStepSize:1e3,minDensity:1e-5,minExtinction:1e-5,minTransmittance:1e-4}},Ut=ble,Mle={low:{...Ut,lightShafts:!1,shapeDetail:!1,turbulence:!1,clouds:{...Ut.clouds,accurateSunSkyLight:!1,maxIterationCount:200,minStepSize:100,maxRayDistance:1e5,minDensity:1e-4,minExtinction:1e-4,minTransmittance:.1,maxIterationCountToGround:0,maxIterationCountToSun:1},shadow:{...Ut.shadow,maxIterationCount:25,minDensity:1e-4,minExtinction:1e-4,minTransmittance:.01,cascadeCount:2,mapSize:new re(256,256)}},medium:{...Ut,lightShafts:!1,turbulence:!1,clouds:{...Ut.clouds,minDensity:1e-4,minExtinction:1e-4,accurateSunSkyLight:!1,maxIterationCountToSun:2,maxIterationCountToGround:1},shadow:{...Ut.shadow,minDensity:1e-4,minExtinction:1e-4,mapSize:new re(256,256)}},high:Ut,ultra:{...Ut,clouds:{...Ut.clouds,minStepSize:10},shadow:{...Ut.shadow,mapSize:new re(1024,1024)}}},Ale=`precision highp float; +precision highp sampler3D; +precision highp sampler2DArray; + +#include +#include + +#include "core/depth" +#include "core/math" +#include "core/turbo" +#include "core/generators" +#include "core/raySphereIntersection" +#include "core/cascadedShadowMaps" +#include "core/interleavedGradientNoise" +#include "core/vogelDisk" + +#include "atmosphere/bruneton/definitions" + +uniform AtmosphereParameters ATMOSPHERE; +uniform vec3 SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; +uniform vec3 SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; + +uniform sampler2D transmittance_texture; +uniform sampler3D scattering_texture; +uniform sampler2D irradiance_texture; +uniform sampler3D single_mie_scattering_texture; +uniform sampler3D higher_order_scattering_texture; + +#include "atmosphere/bruneton/common" +#include "atmosphere/bruneton/runtime" + +#include "types" +#include "parameters" +#include "clouds" + +#if !defined(RECIPROCAL_PI4) +#define RECIPROCAL_PI4 0.07957747154594767 +#endif // !defined(RECIPROCAL_PI4) + +uniform sampler2D depthBuffer; +uniform mat4 viewMatrix; +uniform mat4 reprojectionMatrix; +uniform mat4 viewReprojectionMatrix; +uniform float cameraNear; +uniform float cameraFar; +uniform float cameraHeight; +uniform vec2 temporalJitter; +uniform vec2 targetUvScale; +uniform float mipLevelScale; + +// Scattering +const vec2 scatterAnisotropy = vec2(SCATTER_ANISOTROPY_1, SCATTER_ANISOTROPY_2); +const float scatterAnisotropyMix = SCATTER_ANISOTROPY_MIX; +uniform float skyLightScale; +uniform float groundBounceScale; +uniform float powderScale; +uniform float powderExponent; + +// Primary raymarch +uniform int maxIterationCount; +uniform float minStepSize; +uniform float maxStepSize; +uniform float maxRayDistance; +uniform float perspectiveStepScale; + +// Secondary raymarch +uniform int maxIterationCountToSun; +uniform int maxIterationCountToGround; +uniform float minSecondaryStepSize; +uniform float secondaryStepScale; + +// Beer shadow map +uniform sampler2DArray shadowBuffer; +uniform vec2 shadowTexelSize; +uniform vec2 shadowIntervals[SHADOW_CASCADE_COUNT]; +uniform mat4 shadowMatrices[SHADOW_CASCADE_COUNT]; +uniform float shadowFar; +uniform float maxShadowFilterRadius; + +// Shadow length +#ifdef SHADOW_LENGTH +uniform int maxShadowLengthIterationCount; +uniform float minShadowLengthStepSize; +uniform float maxShadowLengthRayDistance; +#endif // SHADOW_LENGTH + +in vec2 vUv; +in vec3 vCameraPosition; +in vec3 vCameraDirection; // Direction to the center of screen +in vec3 vRayDirection; // Direction to the texel +in vec3 vViewPosition; +in GroundIrradiance vGroundIrradiance; +in CloudsIrradiance vCloudsIrradiance; + +layout(location = 0) out vec4 outputColor; +layout(location = 1) out vec3 outputDepthVelocity; +#ifdef SHADOW_LENGTH +layout(location = 2) out float outputShadowLength; +#endif // SHADOW_LENGTH + +float readDepth(const vec2 uv) { + #if DEPTH_PACKING == 3201 + return unpackRGBAToDepth(texture(depthBuffer, uv)); + #else // DEPTH_PACKING == 3201 + return texture(depthBuffer, uv).r; + #endif // DEPTH_PACKING == 3201 +} + +float getViewZ(const float depth) { + #ifdef PERSPECTIVE_CAMERA + return perspectiveDepthToViewZ(depth, cameraNear, cameraFar); + #else // PERSPECTIVE_CAMERA + return orthographicDepthToViewZ(depth, cameraNear, cameraFar); + #endif // PERSPECTIVE_CAMERA +} + +vec3 ecefToWorld(const vec3 positionECEF) { + return (ecefToWorldMatrix * vec4(positionECEF - altitudeCorrection, 1.0)).xyz; +} + +vec2 getShadowUv(const vec3 worldPosition, const int cascadeIndex) { + vec4 clip = shadowMatrices[cascadeIndex] * vec4(worldPosition, 1.0); + clip /= clip.w; + return clip.xy * 0.5 + 0.5; +} + +float getDistanceToShadowTop(const vec3 rayPosition) { + // Distance to the top of the shadows along the sun direction, which matches + // the ray origin of BSM. + return raySphereSecondIntersection( + rayPosition, + sunDirection, + vec3(0.0), + bottomRadius + shadowTopHeight + ); +} + +#ifdef DEBUG_SHOW_CASCADES + +const vec3 cascadeColors[4] = vec3[4]( + vec3(1.0, 0.0, 0.0), + vec3(0.0, 1.0, 0.0), + vec3(0.0, 0.0, 1.0), + vec3(1.0, 1.0, 0.0) +); + +vec3 getCascadeColor(const vec3 rayPosition) { + vec3 worldPosition = ecefToWorld(rayPosition); + int cascadeIndex = getCascadeIndex( + viewMatrix, + worldPosition, + shadowIntervals, + cameraNear, + shadowFar + ); + vec2 uv = getShadowUv(worldPosition, cascadeIndex); + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { + return vec3(1.0); + } + return cascadeColors[cascadeIndex]; +} + +vec3 getFadedCascadeColor(const vec3 rayPosition, const float jitter) { + vec3 worldPosition = ecefToWorld(rayPosition); + int cascadeIndex = getFadedCascadeIndex( + viewMatrix, + worldPosition, + shadowIntervals, + cameraNear, + shadowFar, + jitter + ); + return cascadeIndex >= 0 + ? cascadeColors[cascadeIndex] + : vec3(1.0); +} + +#endif // DEBUG_SHOW_CASCADES + +float readShadowOpticalDepth( + const vec2 uv, + const float distanceToTop, + const float distanceOffset, + const int cascadeIndex +) { + // r: frontDepth, g: meanExtinction, b: maxOpticalDepth, a: maxOpticalDepthTail + // Also see the discussion here: https://x.com/shotamatsuda/status/1885322308908442106 + vec4 shadow = texture(shadowBuffer, vec3(uv, float(cascadeIndex))); + float distanceToFront = max(0.0, distanceToTop - distanceOffset - shadow.r); + return min(shadow.b + shadow.a, shadow.g * distanceToFront); +} + +float sampleShadowOpticalDepthPCF( + const vec3 worldPosition, + const float distanceToTop, + const float distanceOffset, + const float radius, + const int cascadeIndex +) { + vec2 uv = getShadowUv(worldPosition, cascadeIndex); + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { + return 0.0; + } + if (radius < 0.1) { + return readShadowOpticalDepth(uv, distanceToTop, distanceOffset, cascadeIndex); + } + float sum = 0.0; + vec2 offset; + #pragma unroll_loop_start + for (int i = 0; i < 16; ++i) { + #if UNROLLED_LOOP_INDEX < SHADOW_SAMPLE_COUNT + offset = vogelDisk( + UNROLLED_LOOP_INDEX, + SHADOW_SAMPLE_COUNT, + interleavedGradientNoise(gl_FragCoord.xy + temporalJitter * resolution) * PI2 + ); + sum += readShadowOpticalDepth( + uv + offset * radius * shadowTexelSize, + distanceToTop, + distanceOffset, + cascadeIndex + ); + #endif // UNROLLED_LOOP_INDEX < SHADOW_SAMPLE_COUNT + } + #pragma unroll_loop_end + return sum / float(SHADOW_SAMPLE_COUNT); +} + +float sampleShadowOpticalDepth( + const vec3 rayPosition, + const float distanceOffset, + const float radius, + const float jitter +) { + float distanceToTop = getDistanceToShadowTop(rayPosition); + if (distanceToTop <= 0.0) { + return 0.0; + } + vec3 worldPosition = ecefToWorld(rayPosition); + int cascadeIndex = getFadedCascadeIndex( + viewMatrix, + worldPosition, + shadowIntervals, + cameraNear, + shadowFar, + jitter + ); + return cascadeIndex >= 0 + ? sampleShadowOpticalDepthPCF( + worldPosition, + distanceToTop, + distanceOffset, + radius, + cascadeIndex + ) + : 0.0; +} + +#ifdef DEBUG_SHOW_SHADOW_MAP +vec4 getCascadedShadowMaps(vec2 uv) { + vec4 coord = vec4(vUv, vUv - 0.5) * 2.0; + vec4 shadow = vec4(0.0); + if (uv.y > 0.5) { + if (uv.x < 0.5) { + shadow = texture(shadowBuffer, vec3(coord.xw, 0.0)); + } else { + #if SHADOW_CASCADE_COUNT > 1 + shadow = texture(shadowBuffer, vec3(coord.zw, 1.0)); + #endif // SHADOW_CASCADE_COUNT > 1 + } + } else { + if (uv.x < 0.5) { + #if SHADOW_CASCADE_COUNT > 2 + shadow = texture(shadowBuffer, vec3(coord.xy, 2.0)); + #endif // SHADOW_CASCADE_COUNT > 2 + } else { + #if SHADOW_CASCADE_COUNT > 3 + shadow = texture(shadowBuffer, vec3(coord.zy, 3.0)); + #endif // SHADOW_CASCADE_COUNT > 3 + } + } + + #if !defined(DEBUG_SHOW_SHADOW_MAP_TYPE) + #define DEBUG_SHOW_SHADOW_MAP_TYPE 0 + #endif // !defined(DEBUG_SHOW_SHADOW_MAP_TYPE + + const float frontDepthScale = 1e-5; + const float meanExtinctionScale = 10.0; + const float maxOpticalDepthScale = 0.01; + vec3 color; + #if DEBUG_SHOW_SHADOW_MAP_TYPE == 1 + color = vec3(shadow.r * frontDepthScale); + #elif DEBUG_SHOW_SHADOW_MAP_TYPE == 2 + color = vec3(shadow.g * meanExtinctionScale); + #elif DEBUG_SHOW_SHADOW_MAP_TYPE == 3 + color = vec3((shadow.b + shadow.a) * maxOpticalDepthScale); + #else // DEBUG_SHOW_SHADOW_MAP_TYPE + color = + (shadow.rgb + vec3(0.0, 0.0, shadow.a)) * + vec3(frontDepthScale, meanExtinctionScale, maxOpticalDepthScale); + #endif // DEBUG_SHOW_SHADOW_MAP_TYPE + return vec4(color, 1.0); +} +#endif // DEBUG_SHOW_SHADOW_MAP + +vec2 henyeyGreenstein(const vec2 g, const float cosTheta) { + vec2 g2 = g * g; + // prettier-ignore + return RECIPROCAL_PI4 * + ((1.0 - g2) / max(vec2(1e-7), pow(1.0 + g2 - 2.0 * g * cosTheta, vec2(1.5)))); +} + +#ifdef ACCURATE_PHASE_FUNCTION + +float draine(float u, float g, float a) { + float g2 = g * g; + // prettier-ignore + return (1.0 - g2) * + (1.0 + a * u * u) / + (4.0 * (1.0 + a * (1.0 + 2.0 * g2) / 3.0) * PI * pow(1.0 + g2 - 2.0 * g * u, 1.5)); +} + +// Numerically-fitted large particles (d=10) phase function It won't be +// plausible without a more precise multiple scattering. +// Reference: https://research.nvidia.com/labs/rtr/approximate-mie/ +float phaseFunction(const float cosTheta, const float attenuation) { + const float gHG = 0.988176691700256; // exp(-0.0990567/(d-1.67154)) + const float gD = 0.5556712547839497; // exp(-2.20679/(d+3.91029) - 0.428934) + const float alpha = 21.995520856274638; // exp(3.62489 - 8.29288/(d+5.52825)) + const float weight = 0.4819554318404214; // exp(-0.599085/(d-0.641583)-0.665888) + return mix( + henyeyGreenstein(vec2(gHG) * attenuation, cosTheta).x, + draine(cosTheta, gD * attenuation, alpha), + weight + ); +} + +#else // ACCURATE_PHASE_FUNCTION + +float phaseFunction(const float cosTheta, const float attenuation) { + const vec2 g = scatterAnisotropy; + const vec2 weights = vec2(1.0 - scatterAnisotropyMix, scatterAnisotropyMix); + // A similar approximation is described in the Frostbite's paper, where phase + // angle is attenuated instead of anisotropy. + return dot(henyeyGreenstein(g * attenuation, cosTheta), weights); +} + +#endif // ACCURATE_PHASE_FUNCTION + +float phaseFunction(const float cosTheta) { + return phaseFunction(cosTheta, 1.0); +} + +float marchOpticalDepth( + const vec3 rayOrigin, + const vec3 rayDirection, + const int maxIterationCount, + const float mipLevel, + const float jitter, + out float rayDistance +) { + int iterationCount = int( + max(0.0, remap(mipLevel, 0.0, 1.0, float(maxIterationCount + 1), 1.0) - jitter) + ); + if (iterationCount == 0) { + // Fudge factor to approximate the mean optical depth. + // TODO: Remove it. + return 0.5; + } + float stepSize = minSecondaryStepSize / float(iterationCount); + float nextDistance = stepSize * jitter; + float opticalDepth = 0.0; + for (int i = 0; i < iterationCount; ++i) { + rayDistance = nextDistance; + vec3 position = rayDistance * rayDirection + rayOrigin; + vec2 uv = getGlobeUv(position); + float height = length(position) - bottomRadius; + WeatherSample weather = sampleWeather(uv, height, mipLevel); + MediaSample media = sampleMedia(weather, position, uv, mipLevel, jitter); + opticalDepth += media.extinction * stepSize; + nextDistance += stepSize; + stepSize *= secondaryStepScale; + } + return opticalDepth; +} + +float marchOpticalDepth( + const vec3 rayOrigin, + const vec3 rayDirection, + const int maxIterationCount, + const float mipLevel, + const float jitter +) { + float rayDistance; + return marchOpticalDepth( + rayOrigin, + rayDirection, + maxIterationCount, + mipLevel, + jitter, + rayDistance + ); +} + +float approximateMultipleScattering(const float opticalDepth, const float cosTheta) { + // Multiple scattering approximation + // See: https://fpsunflower.github.io/ckulla/data/oz_volumes.pdf + // a: attenuation, b: contribution, c: phase attenuation + vec3 coeffs = vec3(1.0); // [a, b, c] + const vec3 attenuation = vec3(0.5, 0.5, 0.5); // Should satisfy a <= b + float scattering = 0.0; + float beerLambert; + #pragma unroll_loop_start + for (int i = 0; i < 12; ++i) { + #if UNROLLED_LOOP_INDEX < MULTI_SCATTERING_OCTAVES + beerLambert = exp(-opticalDepth * coeffs.y); + scattering += coeffs.x * beerLambert * phaseFunction(cosTheta, coeffs.z); + coeffs *= attenuation; + #endif // UNROLLED_LOOP_INDEX < MULTI_SCATTERING_OCTAVES + } + #pragma unroll_loop_end + return scattering; +} + +// TODO: Construct spherical harmonics of degree 2 using 2 sample points +// positioned near the horizon occlusion points on the sun direction plane. +vec3 getGroundSunSkyIrradiance( + const vec3 position, + const vec3 surfaceNormal, + const float height, + out vec3 skyIrradiance +) { + #ifdef ACCURATE_SUN_SKY_LIGHT + return GetSunAndSkyIrradiance( + (position - surfaceNormal * height) * METER_TO_LENGTH_UNIT, + surfaceNormal, + sunDirection, + skyIrradiance + ); + #else // ACCURATE_SUN_SKY_LIGHT + skyIrradiance = vGroundIrradiance.sky; + return vGroundIrradiance.sun; + #endif // ACCURATE_SUN_SKY_LIGHT +} + +vec3 getCloudsSunSkyIrradiance(const vec3 position, const float height, out vec3 skyIrradiance) { + #ifdef ACCURATE_SUN_SKY_LIGHT + return GetSunAndSkyScalarIrradiance(position * METER_TO_LENGTH_UNIT, sunDirection, skyIrradiance); + #else // ACCURATE_SUN_SKY_LIGHT + float alpha = remapClamped(height, minHeight, maxHeight); + skyIrradiance = mix(vCloudsIrradiance.minSky, vCloudsIrradiance.maxSky, alpha); + return mix(vCloudsIrradiance.minSun, vCloudsIrradiance.maxSun, alpha); + #endif // ACCURATE_SUN_SKY_LIGHT +} + +#ifdef GROUND_BOUNCE +vec3 approximateRadianceFromGround( + const vec3 position, + const vec3 surfaceNormal, + const float height, + const float mipLevel, + const float jitter +) { + float opticalDepthToGround = marchOpticalDepth( + position, + -surfaceNormal, + maxIterationCountToGround, + mipLevel, + jitter + ); + vec3 skyIrradiance; + vec3 sunIrradiance = getGroundSunSkyIrradiance(position, surfaceNormal, height, skyIrradiance); + const float groundAlbedo = 0.3; + vec3 groundIrradiance = skyIrradiance + (1.0 - coverage) * sunIrradiance; + vec3 bouncedRadiance = groundAlbedo * RECIPROCAL_PI * groundIrradiance; + return bouncedRadiance * exp(-opticalDepthToGround); +} +#endif // GROUND_BOUNCE + +vec4 marchClouds( + const vec3 rayOrigin, + const vec3 rayDirection, + const vec2 rayNearFar, + const float cosTheta, + const float jitter, + const float rayStartTexelsPerPixel, + out float frontDepth, + out ivec3 sampleCount +) { + vec3 radianceIntegral = vec3(0.0); + float transmittanceIntegral = 1.0; + float weightedDistanceSum = 0.0; + float transmittanceSum = 0.0; + + float maxRayDistance = rayNearFar.y - rayNearFar.x; + float stepSize = minStepSize + (perspectiveStepScale - 1.0) * rayNearFar.x; + // I don't understand why spatial aliasing remains unless doubling the jitter. + float rayDistance = stepSize * jitter * 2.0; + + for (int i = 0; i < maxIterationCount; ++i) { + if (rayDistance > maxRayDistance) { + break; // Termination + } + + vec3 position = rayDistance * rayDirection + rayOrigin; + float height = length(position) - bottomRadius; + float mipLevel = log2(max(1.0, rayStartTexelsPerPixel + rayDistance * 1e-5)); + + #if !defined(DEBUG_MARCH_INTERVALS) + if (insideLayerIntervals(height)) { + stepSize *= perspectiveStepScale; + rayDistance += mix(stepSize, maxStepSize, min(1.0, mipLevel)); + continue; + } + #endif // !defined(DEBUG_MARCH_INTERVALS) + + // Sample rough weather. + vec2 uv = getGlobeUv(position); + WeatherSample weather = sampleWeather(uv, height, mipLevel); + + #ifdef DEBUG_SHOW_SAMPLE_COUNT + ++sampleCount.x; + #endif // DEBUG_SHOW_SAMPLE_COUNT + + if (!any(greaterThan(weather.density, vec4(minDensity)))) { + // Step longer in empty space. + // TODO: This produces banding artifacts. + // Possible improvement: Binary search refinement + stepSize *= perspectiveStepScale; + rayDistance += mix(stepSize, maxStepSize, min(1.0, mipLevel)); + continue; + } + + // Sample detailed participating media. + MediaSample media = sampleMedia(weather, position, uv, mipLevel, jitter, sampleCount); + + if (media.extinction > minExtinction) { + vec3 skyIrradiance; + vec3 sunIrradiance = getCloudsSunSkyIrradiance(position, height, skyIrradiance); + vec3 surfaceNormal = normalize(position); + + // March optical depth to the sun for finer details, which BSM lacks. + float sunRayDistance = 0.0; + float opticalDepth = marchOpticalDepth( + position, + sunDirection, + maxIterationCountToSun, + mipLevel, + jitter, + sunRayDistance + ); + + if (height < shadowTopHeight) { + // Obtain the optical depth from BSM at the ray position. + opticalDepth += sampleShadowOpticalDepth( + position, + // Take account of only positions further than the marched ray + // distance. + sunRayDistance, + // Apply PCF only when the sun is close to the horizon. + maxShadowFilterRadius * remapClamped(dot(sunDirection, surfaceNormal), 0.1, 0.0), + jitter + ); + } + + vec3 radiance = sunIrradiance * approximateMultipleScattering(opticalDepth, cosTheta); + + #ifdef GROUND_BOUNCE + // Fudge factor for the irradiance from ground. + if (height < shadowTopHeight && mipLevel < 0.5) { + vec3 groundRadiance = approximateRadianceFromGround( + position, + surfaceNormal, + height, + mipLevel, + jitter + ); + radiance += groundRadiance * RECIPROCAL_PI4 * groundBounceScale; + } + #endif // GROUND_BOUNCE + + // Crude approximation of sky gradient. Better than none in the shadows. + float skyGradient = dot(weather.heightFraction * 0.5 + 0.5, media.weight); + radiance += skyIrradiance * RECIPROCAL_PI4 * skyGradient * skyLightScale; + + // Finally multiply by scattering. + radiance *= media.scattering; + + #ifdef POWDER + radiance *= 1.0 - powderScale * exp(-media.extinction * powderExponent); + #endif // POWDER + + #ifdef DEBUG_SHOW_CASCADES + if (height < shadowTopHeight) { + radiance = 1e-3 * getFadedCascadeColor(position, jitter); + } + #endif // DEBUG_SHOW_CASCADES + + // Energy-conserving analytical integration of scattered light + // See 5.6.3 in https://media.contentapi.ea.com/content/dam/eacom/frostbite/files/s2016-pbs-frostbite-sky-clouds-new.pdf + float transmittance = exp(-media.extinction * stepSize); + float clampedExtinction = max(media.extinction, 1e-7); + vec3 scatteringIntegral = (radiance - radiance * transmittance) / clampedExtinction; + radianceIntegral += transmittanceIntegral * scatteringIntegral; + transmittanceIntegral *= transmittance; + + // Aerial perspective affecting clouds + // See 5.9.1 in https://media.contentapi.ea.com/content/dam/eacom/frostbite/files/s2016-pbs-frostbite-sky-clouds-new.pdf + weightedDistanceSum += rayDistance * transmittanceIntegral; + transmittanceSum += transmittanceIntegral; + } + + if (transmittanceIntegral <= minTransmittance) { + break; // Early termination + } + + // Take a shorter step because we've already hit the clouds. + stepSize *= perspectiveStepScale; + rayDistance += stepSize; + } + + // The final product of 5.9.1 and we'll evaluate this in aerial perspective. + frontDepth = transmittanceSum > 0.0 ? weightedDistanceSum / transmittanceSum : -1.0; + + return vec4(radianceIntegral, remapClamped(transmittanceIntegral, 1.0, minTransmittance)); +} + +#ifdef SHADOW_LENGTH + +float marchShadowLength( + const vec3 rayOrigin, + const vec3 rayDirection, + const vec2 rayNearFar, + const float jitter +) { + float shadowLength = 0.0; + float maxRayDistance = rayNearFar.y - rayNearFar.x; + float stepSize = minShadowLengthStepSize; + float rayDistance = stepSize * jitter; + const float attenuationFactor = 1.0 - 5e-4; + float attenuation = 1.0; + + // TODO: This march is closed, and sample resolution can be much lower. + // Refining the termination by binary search will make it much more efficient. + for (int i = 0; i < maxShadowLengthIterationCount; ++i) { + if (rayDistance > maxRayDistance) { + break; // Termination + } + vec3 position = rayDistance * rayDirection + rayOrigin; + float opticalDepth = sampleShadowOpticalDepth(position, 0.0, 0.0, jitter); + shadowLength += (1.0 - exp(-opticalDepth)) * stepSize * attenuation; + stepSize *= perspectiveStepScale; + rayDistance += stepSize; + } + return shadowLength; +} + +#endif // SHADOW_LENGTH + +#ifdef HAZE + +vec4 approximateHaze( + const vec3 rayOrigin, + const vec3 rayDirection, + const float maxRayDistance, + const float cosTheta, + const float shadowLength +) { + float modulation = remapClamped(coverage, 0.2, 0.4); + if (cameraHeight * modulation < 0.0) { + return vec4(0.0); + } + float density = modulation * hazeDensityScale * exp(-cameraHeight * hazeExponent); + if (density < 1e-7) { + return vec4(0.0); // Prevent artifact in views from space + } + + // Blend two normals by the difference in angle so that normal near the + // ground becomes that of the origin, and in the sky that of the horizon. + vec3 normalAtOrigin = normalize(rayOrigin); + vec3 normalAtHorizon = (rayOrigin - dot(rayOrigin, rayDirection) * rayDirection) / bottomRadius; + float alpha = remapClamped(dot(normalAtOrigin, normalAtHorizon), 0.9, 1.0); + vec3 normal = mix(normalAtOrigin, normalAtHorizon, alpha); + + // Analytical optical depth where density exponentially decreases with height. + // Based on: https://iquilezles.org/articles/fog/ + float angle = max(dot(normal, rayDirection), 1e-5); + float exponent = angle * hazeExponent; + float linearTerm = density / hazeExponent / angle; + + // Derive the optical depths separately for with and without shadow length. + float expTerm = 1.0 - exp(-maxRayDistance * exponent); + float shadowExpTerm = 1.0 - exp(-min(maxRayDistance, shadowLength) * exponent); + float opticalDepth = expTerm * linearTerm; + float shadowOpticalDepth = max((expTerm - shadowExpTerm) * linearTerm, 0.0); + float transmittance = saturate(1.0 - exp(-opticalDepth)); + float shadowTransmittance = saturate(1.0 - exp(-shadowOpticalDepth)); + + vec3 skyIrradiance = vGroundIrradiance.sky; + vec3 sunIrradiance = vGroundIrradiance.sun; + vec3 inscatter = sunIrradiance * phaseFunction(cosTheta) * shadowTransmittance; + inscatter += skyIrradiance * RECIPROCAL_PI4 * skyLightScale * transmittance; + inscatter *= hazeScatteringCoefficient / (hazeAbsorptionCoefficient + hazeScatteringCoefficient); + return vec4(inscatter, transmittance); +} + +#endif // HAZE + +void applyAerialPerspective( + const vec3 cameraPosition, + const vec3 frontPosition, + const float shadowLength, + inout vec4 color +) { + vec3 transmittance; + vec3 inscatter = GetSkyRadianceToPoint( + cameraPosition * METER_TO_LENGTH_UNIT, + frontPosition * METER_TO_LENGTH_UNIT, + shadowLength * METER_TO_LENGTH_UNIT, + sunDirection, + transmittance + ); + color.rgb = color.rgb * transmittance + inscatter * color.a; +} + +bool rayIntersectsGround(const vec3 cameraPosition, const vec3 rayDirection) { + float r = length(cameraPosition); + float mu = dot(cameraPosition, rayDirection) / r; + return mu < 0.0 && r * r * (mu * mu - 1.0) + bottomRadius * bottomRadius >= 0.0; +} + +struct IntersectionResult { + bool ground; + vec4 first; + vec4 second; +}; + +IntersectionResult getIntersections(const vec3 cameraPosition, const vec3 rayDirection) { + IntersectionResult intersections; + intersections.ground = rayIntersectsGround(cameraPosition, rayDirection); + raySphereIntersections( + cameraPosition, + rayDirection, + bottomRadius + vec4(0.0, minHeight, maxHeight, shadowTopHeight), + intersections.first, + intersections.second + ); + return intersections; +} + +vec2 getRayNearFar(const IntersectionResult intersections) { + vec2 nearFar; + if (cameraHeight < minHeight) { + // View below the clouds + if (intersections.ground) { + nearFar = vec2(-1.0); // No clouds to the ground + } else { + nearFar = vec2(intersections.second.y, intersections.second.z); + nearFar.y = min(nearFar.y, maxRayDistance); + } + } else if (cameraHeight < maxHeight) { + // View inside the total cloud layer + if (intersections.ground) { + nearFar = vec2(cameraNear, intersections.first.y); + } else { + nearFar = vec2(cameraNear, intersections.second.z); + } + } else { + // View above the clouds + nearFar = vec2(intersections.first.z, intersections.second.z); + if (intersections.ground) { + // Clamp the ray at the min height. + nearFar.y = intersections.first.y; + } + } + return nearFar; +} + +#ifdef SHADOW_LENGTH +vec2 getShadowRayNearFar(const IntersectionResult intersections) { + vec2 nearFar; + if (cameraHeight < shadowTopHeight) { + if (intersections.ground) { + nearFar = vec2(cameraNear, intersections.first.x); + } else { + nearFar = vec2(cameraNear, intersections.second.w); + } + } else { + nearFar = vec2(intersections.first.w, intersections.second.w); + if (intersections.ground) { + // Clamp the ray at the ground. + nearFar.y = intersections.first.x; + } + } + nearFar.y = min(nearFar.y, maxShadowLengthRayDistance); + return nearFar; +} +#endif // SHADOW_LENGTH + +#ifdef HAZE +vec2 getHazeRayNearFar(const IntersectionResult intersections) { + vec2 nearFar; + if (cameraHeight < maxHeight) { + if (intersections.ground) { + nearFar = vec2(cameraNear, intersections.first.x); + } else { + nearFar = vec2(cameraNear, intersections.second.z); + } + } else { + nearFar = vec2(cameraNear, intersections.second.z); + if (intersections.ground) { + // Clamp the ray at the ground. + nearFar.y = intersections.first.x; + } + } + return nearFar; +} +#endif // HAZE + +float getRayDistanceToScene(const vec3 rayDirection, out float viewZ) { + float depth = readDepth(vUv * targetUvScale + temporalJitter); + if (depth < 1.0 - 1e-7) { + depth = reverseLogDepth(depth, cameraNear, cameraFar); + viewZ = getViewZ(depth); + return -viewZ / dot(rayDirection, vCameraDirection); + } + viewZ = 0.0; + return 0.0; +} + +void main() { + #ifdef DEBUG_SHOW_SHADOW_MAP + outputColor = getCascadedShadowMaps(vUv); + outputDepthVelocity = vec3(0.0); + #ifdef SHADOW_LENGTH + outputShadowLength = 0.0; + #endif // SHADOW_LENGTH + return; + #endif // DEBUG_SHOW_SHADOW_MAP + + vec3 cameraPosition = vCameraPosition + altitudeCorrection; + vec3 rayDirection = normalize(vRayDirection); + float cosTheta = dot(sunDirection, rayDirection); + + IntersectionResult intersections = getIntersections(cameraPosition, rayDirection); + vec2 rayNearFar = getRayNearFar(intersections); + #ifdef SHADOW_LENGTH + vec2 shadowRayNearFar = getShadowRayNearFar(intersections); + #endif // SHADOW_LENGTH + #ifdef HAZE + vec2 hazeRayNearFar = getHazeRayNearFar(intersections); + #endif // HAZE + + float sceneViewZ; + float rayDistanceToScene = getRayDistanceToScene(rayDirection, sceneViewZ); + if (rayDistanceToScene > 0.0) { + rayNearFar.y = min(rayNearFar.y, rayDistanceToScene); + #ifdef SHADOW_LENGTH + shadowRayNearFar.y = min(shadowRayNearFar.y, rayDistanceToScene); + #endif // SHADOW_LENGTH + #ifdef HAZE + hazeRayNearFar.y = min(hazeRayNearFar.y, rayDistanceToScene); + #endif // HAZE + } + + bool intersectsGround = any(lessThan(rayNearFar, vec2(0.0))); + bool intersectsScene = rayNearFar.y < rayNearFar.x; + + float stbn = getSTBN(); + + vec4 color = vec4(0.0); + float frontDepth = rayNearFar.y; + vec3 depthVelocity = vec3(0.0); + float shadowLength = 0.0; + bool hitClouds = false; + + if (!intersectsGround && !intersectsScene) { + vec3 rayOrigin = rayNearFar.x * rayDirection + cameraPosition; + + vec2 globeUv = getGlobeUv(rayOrigin); + #ifdef DEBUG_SHOW_UV + outputColor = vec4(vec3(checker(globeUv, localWeatherRepeat + localWeatherOffset)), 1.0); + outputDepthVelocity = vec3(0.0); + #ifdef SHADOW_LENGTH + outputShadowLength = 0.0; + #endif // SHADOW_LENGTH + return; + #endif // DEBUG_SHOW_UV + + float mipLevel = getMipLevel(globeUv * localWeatherRepeat) * mipLevelScale; + mipLevel = mix(0.0, mipLevel, min(1.0, 0.2 * cameraHeight / maxHeight)); + + float marchedFrontDepth; + ivec3 sampleCount = ivec3(0); + color = marchClouds( + rayOrigin, + rayDirection, + rayNearFar, + cosTheta, + stbn, + pow(2.0, mipLevel), + marchedFrontDepth, + sampleCount + ); + + #ifdef DEBUG_SHOW_SAMPLE_COUNT + outputColor = vec4(vec3(sampleCount) / vec3(500.0, 5.0, 5.0), 1.0); + outputDepthVelocity = vec3(0.0); + #ifdef SHADOW_LENGTH + outputShadowLength = 0.0; + #endif // SHADOW_LENGTH + return; + #endif // DEBUG_SHOW_SAMPLE_COUNT + + // Front depth will be -1.0 when no samples are accumulated. + hitClouds = marchedFrontDepth >= 0.0; + if (hitClouds) { + frontDepth = rayNearFar.x + marchedFrontDepth; + + #ifdef SHADOW_LENGTH + // Clamp the shadow length ray at the clouds. + shadowRayNearFar.y = mix( + shadowRayNearFar.y, + min(frontDepth, shadowRayNearFar.y), + color.a // Interpolate by the alpha for smoother edges. + ); + + // Shadow length must be computed before applying aerial perspective. + if (all(greaterThanEqual(shadowRayNearFar, vec2(0.0)))) { + shadowLength = marchShadowLength( + shadowRayNearFar.x * rayDirection + cameraPosition, + rayDirection, + shadowRayNearFar, + stbn + ); + } + #endif // SHADOW_LENGTH + + #ifdef HAZE + // Clamp the haze ray at the clouds. + hazeRayNearFar.y = mix( + hazeRayNearFar.y, + min(frontDepth, hazeRayNearFar.y), + color.a // Interpolate by the alpha for smoother edges. + ); + #endif // HAZE + + // Apply aerial perspective. + vec3 frontPosition = cameraPosition + frontDepth * rayDirection; + applyAerialPerspective(cameraPosition, frontPosition, shadowLength, color); + + // Velocity for temporal resolution. + vec3 frontPositionWorld = ecefToWorld(frontPosition); + vec4 prevClip = reprojectionMatrix * vec4(frontPositionWorld, 1.0); + prevClip /= prevClip.w; + vec2 prevUv = prevClip.xy * 0.5 + 0.5; + vec2 velocity = vUv - prevUv; + depthVelocity = vec3(frontDepth, velocity); + } + } + + if (!hitClouds) { + #ifdef SHADOW_LENGTH + if (all(greaterThanEqual(shadowRayNearFar, vec2(0.0)))) { + shadowLength = marchShadowLength( + shadowRayNearFar.x * rayDirection + cameraPosition, + rayDirection, + shadowRayNearFar, + stbn + ); + } + #endif // SHADOW_LENGTH + + // Velocity for temporal resolution. Here reproject in the view space for + // greatly reducing the precision errors. + frontDepth = sceneViewZ < 0.0 ? -sceneViewZ : cameraFar; + vec3 frontView = vViewPosition * frontDepth; + vec4 prevClip = viewReprojectionMatrix * vec4(frontView, 1.0); + prevClip /= prevClip.w; + vec2 prevUv = prevClip.xy * 0.5 + 0.5; + vec2 velocity = vUv - prevUv; + depthVelocity = vec3(frontDepth, velocity); + } + + #ifdef DEBUG_SHOW_FRONT_DEPTH + outputColor = vec4(turbo(frontDepth / maxRayDistance), 1.0); + outputDepthVelocity = vec3(0.0); + #ifdef SHADOW_LENGTH + outputShadowLength = 0.0; + #endif // SHADOW_LENGTH + return; + #endif // DEBUG_SHOW_FRONT_DEPTH + + #ifdef HAZE + vec4 haze = approximateHaze( + cameraNear * rayDirection + cameraPosition, + rayDirection, + hazeRayNearFar.y - hazeRayNearFar.x, + cosTheta, + shadowLength + ); + color.rgb = mix(color.rgb, haze.rgb, haze.a); + color.a = color.a * (1.0 - haze.a) + haze.a; + #endif // HAZE + + outputColor = color; + outputDepthVelocity = depthVelocity; + #ifdef SHADOW_LENGTH + outputShadowLength = shadowLength * METER_TO_LENGTH_UNIT; + #endif // SHADOW_LENGTH +} +`,eF=`float getSTBN() { + ivec3 size = textureSize(stbnTexture, 0); + vec3 scale = 1.0 / vec3(size); + return texture(stbnTexture, vec3(gl_FragCoord.xy, float(frame % size.z)) * scale).r; +} + +// Straightforward spherical mapping +vec2 getSphericalUv(const vec3 position) { + vec2 st = normalize(position.yx); + float phi = atan(st.x, st.y); + float theta = asin(normalize(position).z); + return vec2(phi * RECIPROCAL_PI2 + 0.5, theta * RECIPROCAL_PI + 0.5); +} + +vec2 getCubeSphereUv(const vec3 position) { + // Cube-sphere relaxation by: http://mathproofs.blogspot.com/2005/07/mapping-cube-to-sphere.html + // TODO: Tile and fix seams. + // Possible improvements: + // https://iquilezles.org/articles/texturerepetition/ + // https://gamedev.stackexchange.com/questions/184388/fragment-shader-map-dot-texture-repeatedly-over-the-sphere + // https://github.com/mmikk/hextile-demo + + vec3 n = normalize(position); + vec3 f = abs(n); + vec3 c = n / max(f.x, max(f.y, f.z)); + vec2 m; + if (all(greaterThan(f.yy, f.xz))) { + m = c.y > 0.0 ? vec2(-n.x, n.z) : n.xz; + } else if (all(greaterThan(f.xx, f.yz))) { + m = c.x > 0.0 ? n.yz : vec2(-n.y, n.z); + } else { + m = c.z > 0.0 ? n.xy : vec2(n.x, -n.y); + } + + vec2 m2 = m * m; + float q = dot(m2.xy, vec2(-2.0, 2.0)) - 3.0; + float q2 = q * q; + vec2 uv; + uv.x = sqrt(1.5 + m2.x - m2.y - 0.5 * sqrt(-24.0 * m2.x + q2)) * (m.x > 0.0 ? 1.0 : -1.0); + uv.y = sqrt(6.0 / (3.0 - uv.x * uv.x)) * m.y; + return uv * 0.5 + 0.5; +} + +vec2 getGlobeUv(const vec3 position) { + return getCubeSphereUv(position); +} + +float getMipLevel(const vec2 uv) { + const float mipLevelScale = 0.1; + vec2 coord = uv * resolution; + vec2 ddx = dFdx(coord); + vec2 ddy = dFdy(coord); + float deltaMaxSqr = max(dot(ddx, ddx), dot(ddy, ddy)) * mipLevelScale; + return max(0.0, 0.5 * log2(max(1.0, deltaMaxSqr))); +} + +bool insideLayerIntervals(const float height) { + bvec3 gt = greaterThan(vec3(height), minIntervalHeights); + bvec3 lt = lessThan(vec3(height), maxIntervalHeights); + return any(bvec3(gt.x && lt.x, gt.y && lt.y, gt.z && lt.z)); +} + +struct WeatherSample { + vec4 heightFraction; // Normalized height of each layer + vec4 density; +}; + +vec4 shapeAlteringFunction(const vec4 heightFraction, const vec4 bias) { + // Apply a semi-circle transform to round the clouds towards the top. + vec4 biased = pow(heightFraction, bias); + vec4 x = clamp(biased * 2.0 - 1.0, -1.0, 1.0); + return 1.0 - x * x; +} + +WeatherSample sampleWeather(const vec2 uv, const float height, const float mipLevel) { + WeatherSample weather; + weather.heightFraction = remapClamped(vec4(height), minLayerHeights, maxLayerHeights); + + vec4 localWeather = pow( + textureLod( + localWeatherTexture, + uv * localWeatherRepeat + localWeatherOffset, + mipLevel + ).LOCAL_WEATHER_CHANNELS, + weatherExponents + ); + #ifdef SHADOW + localWeather *= shadowLayerMask; + #endif // SHADOW + + vec4 heightScale = shapeAlteringFunction(weather.heightFraction, shapeAlteringBiases); + + // Modulation to control weather by coverage parameter. + // Reference: https://github.com/Prograda/Skybolt/blob/master/Assets/Core/Shaders/Clouds.h#L63 + vec4 factor = 1.0 - coverage * heightScale; + weather.density = remapClamped( + mix(localWeather, vec4(1.0), coverageFilterWidths), + factor, + factor + coverageFilterWidths + ); + + return weather; +} + +vec4 getLayerDensity(const vec4 heightFraction) { + // prettier-ignore + return densityProfile.expTerms * exp(densityProfile.exponents * heightFraction) + + densityProfile.linearTerms * heightFraction + + densityProfile.constantTerms; +} + +struct MediaSample { + float density; + vec4 weight; + float scattering; + float extinction; +}; + +MediaSample sampleMedia( + const WeatherSample weather, + const vec3 position, + const vec2 uv, + const float mipLevel, + const float jitter, + out ivec3 sampleCount +) { + vec4 density = weather.density; + + // TODO: Define in physical length. + vec3 surfaceNormal = normalize(position); + float localWeatherSpeed = length(localWeatherOffset); + vec3 evolution = -surfaceNormal * localWeatherSpeed * 2e4; + + vec3 turbulence = vec3(0.0); + #ifdef TURBULENCE + vec2 turbulenceUv = uv * localWeatherRepeat * turbulenceRepeat; + turbulence = + turbulenceDisplacement * + (texture(turbulenceTexture, turbulenceUv).rgb * 2.0 - 1.0) * + dot(density, remapClamped(weather.heightFraction, vec4(0.3), vec4(0.0))); + #endif // TURBULENCE + + vec3 shapePosition = (position + evolution + turbulence) * shapeRepeat + shapeOffset; + float shape = texture(shapeTexture, shapePosition).r; + density = remapClamped(density, vec4(1.0 - shape) * shapeAmounts, vec4(1.0)); + + #ifdef DEBUG_SHOW_SAMPLE_COUNT + ++sampleCount.y; + #endif // DEBUG_SHOW_SAMPLE_COUNT + + #ifdef SHAPE_DETAIL + if (mipLevel * 0.5 + (jitter - 0.5) * 0.5 < 0.5) { + vec3 detailPosition = (position + turbulence) * shapeDetailRepeat + shapeDetailOffset; + float detail = texture(shapeDetailTexture, detailPosition).r; + // Fluffy at the top and whippy at the bottom. + vec4 modifier = mix( + vec4(pow(detail, 6.0)), + vec4(1.0 - detail), + remapClamped(weather.heightFraction, vec4(0.2), vec4(0.4)) + ); + modifier = mix(vec4(0.0), modifier, shapeDetailAmounts); + density = remapClamped(density * 2.0, vec4(modifier * 0.5), vec4(1.0)); + + #ifdef DEBUG_SHOW_SAMPLE_COUNT + ++sampleCount.z; + #endif // DEBUG_SHOW_SAMPLE_COUNT + } + #endif // SHAPE_DETAIL + + // Apply the density profiles. + density = saturate(density * densityScales * getLayerDensity(weather.heightFraction)); + + MediaSample media; + float densitySum = density.x + density.y + density.z + density.w; + media.weight = density / densitySum; + media.scattering = densitySum * scatteringCoefficient; + media.extinction = densitySum * absorptionCoefficient + media.scattering; + return media; +} + +MediaSample sampleMedia( + const WeatherSample weather, + const vec3 position, + const vec2 uv, + const float mipLevel, + const float jitter +) { + ivec3 sampleCount; + return sampleMedia(weather, position, uv, mipLevel, jitter, sampleCount); +} +`,wle=`precision highp float; +precision highp sampler3D; + +#include "atmosphere/bruneton/definitions" + +uniform AtmosphereParameters ATMOSPHERE; +uniform vec3 SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; +uniform vec3 SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; + +uniform sampler2D transmittance_texture; +uniform sampler3D scattering_texture; +uniform sampler2D irradiance_texture; +uniform sampler3D single_mie_scattering_texture; +uniform sampler3D higher_order_scattering_texture; + +#include "atmosphere/bruneton/common" +#include "atmosphere/bruneton/runtime" + +#include "types" + +uniform mat4 inverseProjectionMatrix; +uniform mat4 inverseViewMatrix; +uniform vec3 cameraPosition; +uniform mat4 worldToECEFMatrix; +uniform vec3 altitudeCorrection; + +// Atmosphere +uniform float bottomRadius; +uniform vec3 sunDirection; + +// Cloud layers +uniform float minHeight; +uniform float maxHeight; + +layout(location = 0) in vec3 position; + +out vec2 vUv; +out vec3 vCameraPosition; +out vec3 vCameraDirection; // Direction to the center of screen +out vec3 vRayDirection; // Direction to the texel +out vec3 vViewPosition; + +out GroundIrradiance vGroundIrradiance; +out CloudsIrradiance vCloudsIrradiance; + +void sampleSunSkyIrradiance(const vec3 positionECEF) { + vGroundIrradiance.sun = GetSunAndSkyScalarIrradiance( + positionECEF * METER_TO_LENGTH_UNIT, + sunDirection, + vGroundIrradiance.sky + ); + + vec3 surfaceNormal = normalize(positionECEF); + vec2 radii = (bottomRadius + vec2(minHeight, maxHeight)) * METER_TO_LENGTH_UNIT; + vCloudsIrradiance.minSun = GetSunAndSkyScalarIrradiance( + surfaceNormal * radii.x, + sunDirection, + vCloudsIrradiance.minSky + ); + vCloudsIrradiance.maxSun = GetSunAndSkyScalarIrradiance( + surfaceNormal * radii.y, + sunDirection, + vCloudsIrradiance.maxSky + ); +} + +void main() { + vUv = position.xy * 0.5 + 0.5; + + vec3 viewPosition = (inverseProjectionMatrix * vec4(position, 1.0)).xyz; + vec3 worldDirection = (inverseViewMatrix * vec4(viewPosition.xyz, 0.0)).xyz; + vec3 cameraDirection = normalize((inverseViewMatrix * vec4(0.0, 0.0, -1.0, 0.0)).xyz); + vCameraPosition = (worldToECEFMatrix * vec4(cameraPosition, 1.0)).xyz; + vCameraDirection = (worldToECEFMatrix * vec4(cameraDirection, 0.0)).xyz; + vRayDirection = (worldToECEFMatrix * vec4(worldDirection, 0.0)).xyz; + vViewPosition = viewPosition; + + sampleSunSkyIrradiance(vCameraPosition + altitudeCorrection); + + gl_Position = vec4(position.xy, 1.0, 1.0); +} +`,tF=`uniform vec2 resolution; +uniform int frame; +uniform sampler3D stbnTexture; + +// Atmosphere +uniform float bottomRadius; +uniform mat4 worldToECEFMatrix; +uniform mat4 ecefToWorldMatrix; +uniform vec3 altitudeCorrection; +uniform vec3 sunDirection; + +// Participating medium +uniform float scatteringCoefficient; +uniform float absorptionCoefficient; + +// Primary raymarch +uniform float minDensity; +uniform float minExtinction; +uniform float minTransmittance; + +// Shape and weather +uniform sampler2D localWeatherTexture; +uniform vec2 localWeatherRepeat; +uniform vec2 localWeatherOffset; +uniform float coverage; +uniform sampler3D shapeTexture; +uniform vec3 shapeRepeat; +uniform vec3 shapeOffset; + +#ifdef SHAPE_DETAIL +uniform sampler3D shapeDetailTexture; +uniform vec3 shapeDetailRepeat; +uniform vec3 shapeDetailOffset; +#endif // SHAPE_DETAIL + +#ifdef TURBULENCE +uniform sampler2D turbulenceTexture; +uniform vec2 turbulenceRepeat; +uniform float turbulenceDisplacement; +#endif // TURBULENCE + +// Haze +#ifdef HAZE +uniform float hazeDensityScale; +uniform float hazeExponent; +uniform float hazeScatteringCoefficient; +uniform float hazeAbsorptionCoefficient; +#endif // HAZE + +// Cloud layers +uniform vec4 minLayerHeights; +uniform vec4 maxLayerHeights; +uniform vec3 minIntervalHeights; +uniform vec3 maxIntervalHeights; +uniform vec4 densityScales; +uniform vec4 shapeAmounts; +uniform vec4 shapeDetailAmounts; +uniform vec4 weatherExponents; +uniform vec4 shapeAlteringBiases; +uniform vec4 coverageFilterWidths; +uniform float minHeight; +uniform float maxHeight; +uniform float shadowTopHeight; +uniform float shadowBottomHeight; +uniform vec4 shadowLayerMask; +uniform CloudDensityProfile densityProfile; +`,HA=`struct GroundIrradiance { + vec3 sun; + vec3 sky; +}; + +struct CloudsIrradiance { + vec3 minSun; + vec3 minSky; + vec3 maxSun; + vec3 maxSky; +}; + +struct CloudDensityProfile { + vec4 expTerms; + vec4 exponents; + vec4 linearTerms; + vec4 constantTerms; +}; +`;var Rle=Object.defineProperty,ya=(n,e,t,i)=>{for(var r=void 0,a=n.length-1,s;a>=0;a--)(s=n[a])&&(r=s(e,t,r)||r);return r&&Rle(e,t,r),r};const Cle=new D,Dle=new Pg;let Jr=class extends gv{constructor({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i},r=mv.DEFAULT){super({name:"CloudsMaterial",glslVersion:No,vertexShader:Wr(wle,{atmosphere:{bruneton:{common:y5,definitions:S5,runtime:x5}},types:HA}),fragmentShader:pv(Wr(Ale,{core:{depth:wB,math:QR,turbo:CB,generators:Lse,raySphereIntersection:_T,cascadedShadowMaps:AB,interleavedGradientNoise:RB,vogelDisk:DB},atmosphere:{bruneton:{common:y5,definitions:S5,runtime:x5}},types:HA,parameters:tF,clouds:eF})),uniforms:{...e,...t,...i,depthBuffer:new $(null),viewMatrix:new $(new Me),inverseProjectionMatrix:new $(new Me),inverseViewMatrix:new $(new Me),reprojectionMatrix:new $(new Me),viewReprojectionMatrix:new $(new Me),resolution:new $(new re),cameraNear:new $(0),cameraFar:new $(0),cameraHeight:new $(0),frame:new $(0),temporalJitter:new $(new re),targetUvScale:new $(new re),mipLevelScale:new $(1),stbnTexture:new $(null),skyLightScale:new $(1),groundBounceScale:new $(1),powderScale:new $(.8),powderExponent:new $(150),maxIterationCount:new $(Ut.clouds.maxIterationCount),minStepSize:new $(Ut.clouds.minStepSize),maxStepSize:new $(Ut.clouds.maxStepSize),maxRayDistance:new $(Ut.clouds.maxRayDistance),perspectiveStepScale:new $(Ut.clouds.perspectiveStepScale),minDensity:new $(Ut.clouds.minDensity),minExtinction:new $(Ut.clouds.minExtinction),minTransmittance:new $(Ut.clouds.minTransmittance),maxIterationCountToSun:new $(Ut.clouds.maxIterationCountToSun),maxIterationCountToGround:new $(Ut.clouds.maxIterationCountToGround),minSecondaryStepSize:new $(Ut.clouds.minSecondaryStepSize),secondaryStepScale:new $(Ut.clouds.secondaryStepScale),shadowBuffer:new $(null),shadowTexelSize:new $(new re),shadowIntervals:new $(Array.from({length:4},()=>new re)),shadowMatrices:new $(Array.from({length:4},()=>new Me)),shadowFar:new $(0),maxShadowFilterRadius:new $(6),shadowLayerMask:new $(new Pt().setScalar(1)),maxShadowLengthIterationCount:new $(Ut.clouds.maxShadowLengthIterationCount),minShadowLengthStepSize:new $(Ut.clouds.minShadowLengthStepSize),maxShadowLengthRayDistance:new $(Ut.clouds.maxShadowLengthRayDistance),hazeDensityScale:new $(3e-5),hazeExponent:new $(.001),hazeScatteringCoefficient:new $(.9),hazeAbsorptionCoefficient:new $(.5)}},r),this.temporalUpscale=!0,this.depthPacking=0,this.localWeatherChannels="rgba",this.shapeDetail=Ut.shapeDetail,this.turbulence=Ut.turbulence,this.shadowLength=Ut.lightShafts,this.haze=Ut.haze,this.multiScatteringOctaves=Ut.clouds.multiScatteringOctaves,this.accurateSunSkyLight=Ut.clouds.accurateSunSkyLight,this.accuratePhaseFunction=Ut.clouds.accuratePhaseFunction,this.shadowCascadeCount=Ut.shadow.cascadeCount,this.shadowSampleCount=8,this.scatterAnisotropy1=.7,this.scatterAnisotropy2=-.2,this.scatterAnisotropyMix=.5}onBeforeRender(e,t,i,r,a,s){const o=this.defines.USE_LOGARITHMIC_DEPTH_BUFFER!=null,l=e.capabilities.logarithmicDepthBuffer;l!==o&&(l?this.defines.USE_LOGARITHMIC_DEPTH_BUFFER="1":delete this.defines.USE_LOGARITHMIC_DEPTH_BUFFER);const u=this.defines.POWDER!=null,d=this.uniforms.powderScale.value>0;d!==u&&(d?this.defines.POWDER="1":delete this.defines.POWDER,this.needsUpdate=!0);const f=this.defines.GROUND_BOUNCE!=null;(this.uniforms.groundBounceScale.value>0&&this.uniforms.maxIterationCountToGround.value>0)!==f&&(d?this.defines.GROUND_BOUNCE="1":delete this.defines.GROUND_BOUNCE,this.needsUpdate=!0)}copyCameraSettings(e){e.isPerspectiveCamera===!0?this.defines.PERSPECTIVE_CAMERA!=="1"&&(this.defines.PERSPECTIVE_CAMERA="1",this.needsUpdate=!0):this.defines.PERSPECTIVE_CAMERA!=null&&(delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0);const t=this.uniforms;t.viewMatrix.value.copy(e.matrixWorldInverse),t.inverseViewMatrix.value.copy(e.matrixWorld);const i=this.previousProjectionMatrix??e.projectionMatrix,r=this.previousViewMatrix??e.matrixWorldInverse,a=t.inverseProjectionMatrix.value,s=t.inverseViewMatrix.value,o=t.reprojectionMatrix.value,l=t.viewReprojectionMatrix.value;if(this.temporalUpscale){const f=t.frame.value%16,p=t.resolution.value,m=$B[f],v=(m.x-.5)/p.x*4,x=(m.y-.5)/p.y*4;t.temporalJitter.value.set(v,x),t.mipLevelScale.value=.25,a.copy(e.projectionMatrix),a.elements[8]+=v*2,a.elements[9]+=x*2,a.invert(),o.copy(i),o.elements[8]+=v*2,o.elements[9]+=x*2,o.multiply(r),l.copy(o).multiply(s)}else t.temporalJitter.value.setScalar(0),t.mipLevelScale.value=1,a.copy(e.projectionMatrixInverse),o.copy(i).multiply(r),l.copy(o).multiply(s);t.cameraNear.value=e.near,t.cameraFar.value=e.far;const u=e.getWorldPosition(t.cameraPosition.value),d=Cle.copy(u).applyMatrix4(t.worldToECEFMatrix.value);try{t.cameraHeight.value=Dle.setFromECEF(d).height}catch{}}copyReprojectionMatrix(e){this.previousProjectionMatrix??(this.previousProjectionMatrix=new Me),this.previousViewMatrix??(this.previousViewMatrix=new Me),this.previousProjectionMatrix.copy(e.projectionMatrix),this.previousViewMatrix.copy(e.matrixWorldInverse)}setSize(e,t,i,r){this.uniforms.resolution.value.set(e,t),i!=null&&r!=null?this.uniforms.targetUvScale.value.set(e/i,t/r):this.uniforms.targetUvScale.value.setScalar(1),this.previousProjectionMatrix=void 0,this.previousViewMatrix=void 0}setShadowSize(e,t){this.uniforms.shadowTexelSize.value.set(1/e,1/t)}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(e){this.uniforms.depthBuffer.value=e}get accurateSunSkyIrradiance(){return this.accurateSunSkyLight}set accurateSunSkyIrradiance(e){this.accurateSunSkyLight=e}};ya([ad("DEPTH_PACKING")],Jr.prototype,"depthPacking");ya([TB("LOCAL_WEATHER_CHANNELS",{validate:n=>/^[rgba]{4}$/.test(n)})],Jr.prototype,"localWeatherChannels");ya([gn("SHAPE_DETAIL")],Jr.prototype,"shapeDetail");ya([gn("TURBULENCE")],Jr.prototype,"turbulence");ya([gn("SHADOW_LENGTH")],Jr.prototype,"shadowLength");ya([gn("HAZE")],Jr.prototype,"haze");ya([ad("MULTI_SCATTERING_OCTAVES",{min:1,max:12})],Jr.prototype,"multiScatteringOctaves");ya([gn("ACCURATE_SUN_SKY_LIGHT")],Jr.prototype,"accurateSunSkyLight");ya([gn("ACCURATE_PHASE_FUNCTION")],Jr.prototype,"accuratePhaseFunction");ya([ad("SHADOW_CASCADE_COUNT",{min:1,max:4})],Jr.prototype,"shadowCascadeCount");ya([ad("SHADOW_SAMPLE_COUNT",{min:1,max:16})],Jr.prototype,"shadowSampleCount");ya([ZR("SCATTER_ANISOTROPY_1")],Jr.prototype,"scatterAnisotropy1");ya([ZR("SCATTER_ANISOTROPY_2")],Jr.prototype,"scatterAnisotropy2");ya([ZR("SCATTER_ANISOTROPY_MIX")],Jr.prototype,"scatterAnisotropyMix");const Nle=`// Taken from https://gist.github.com/TheRealMJP/c83b8c0f46b63f3a88a5986f4fa982b1 +// TODO: Use 5-taps version: https://www.shadertoy.com/view/MtVGWz +// Or even 4 taps (requires preprocessing in the input buffer): +// https://www.shadertoy.com/view/4tyGDD + +/** + * MIT License + * + * Copyright (c) 2019 MJP + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +vec4 textureCatmullRom(sampler2D tex, vec2 uv) { + vec2 texSize = vec2(textureSize(tex, 0)); + + // We're going to sample a a 4x4 grid of texels surrounding the target UV + // coordinate. We'll do this by rounding down the sample location to get the + // exact center of our "starting" texel. The starting texel will be at + // location [1, 1] in the grid, where [0, 0] is the top left corner. + vec2 samplePos = uv * texSize; + vec2 texPos1 = floor(samplePos - 0.5) + 0.5; + + // Compute the fractional offset from our starting texel to our original + // sample location, which we'll feed into the Catmull-Rom spline function to + // get our filter weights. + vec2 f = samplePos - texPos1; + + // Compute the Catmull-Rom weights using the fractional offset that we + // calculated earlier. These equations are pre-expanded based on our knowledge + // of where the texels will be located, which lets us avoid having to evaluate + // a piece-wise function. + vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f)); + vec2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f); + vec2 w2 = f * (0.5 + f * (2.0 - 1.5 * f)); + vec2 w3 = f * f * (-0.5 + 0.5 * f); + + // Work out weighting factors and sampling offsets that will let us use + // bilinear filtering to simultaneously evaluate the middle 2 samples from the + // 4x4 grid. + vec2 w12 = w1 + w2; + vec2 offset12 = w2 / (w1 + w2); + + // Compute the final UV coordinates we'll use for sampling the texture + vec2 texPos0 = texPos1 - 1.0; + vec2 texPos3 = texPos1 + 2.0; + vec2 texPos12 = texPos1 + offset12; + + texPos0 /= texSize; + texPos3 /= texSize; + texPos12 /= texSize; + + vec4 result = vec4(0.0); + result += texture(tex, vec2(texPos0.x, texPos0.y)) * w0.x * w0.y; + result += texture(tex, vec2(texPos12.x, texPos0.y)) * w12.x * w0.y; + result += texture(tex, vec2(texPos3.x, texPos0.y)) * w3.x * w0.y; + + result += texture(tex, vec2(texPos0.x, texPos12.y)) * w0.x * w12.y; + result += texture(tex, vec2(texPos12.x, texPos12.y)) * w12.x * w12.y; + result += texture(tex, vec2(texPos3.x, texPos12.y)) * w3.x * w12.y; + + result += texture(tex, vec2(texPos0.x, texPos3.y)) * w0.x * w3.y; + result += texture(tex, vec2(texPos12.x, texPos3.y)) * w12.x * w3.y; + result += texture(tex, vec2(texPos3.x, texPos3.y)) * w3.x * w3.y; + + return result; +} + +vec4 textureCatmullRom(sampler2DArray tex, vec3 uv) { + vec2 texSize = vec2(textureSize(tex, 0)); + vec2 samplePos = uv.xy * texSize; + vec2 texPos1 = floor(samplePos - 0.5) + 0.5; + vec2 f = samplePos - texPos1; + vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f)); + vec2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f); + vec2 w2 = f * (0.5 + f * (2.0 - 1.5 * f)); + vec2 w3 = f * f * (-0.5 + 0.5 * f); + vec2 w12 = w1 + w2; + vec2 offset12 = w2 / (w1 + w2); + vec2 texPos0 = texPos1 - 1.0; + vec2 texPos3 = texPos1 + 2.0; + vec2 texPos12 = texPos1 + offset12; + texPos0 /= texSize; + texPos3 /= texSize; + texPos12 /= texSize; + vec4 result = vec4(0.0); + result += texture(tex, vec3(texPos0.x, texPos0.y, uv.z)) * w0.x * w0.y; + result += texture(tex, vec3(texPos12.x, texPos0.y, uv.z)) * w12.x * w0.y; + result += texture(tex, vec3(texPos3.x, texPos0.y, uv.z)) * w3.x * w0.y; + result += texture(tex, vec3(texPos0.x, texPos12.y, uv.z)) * w0.x * w12.y; + result += texture(tex, vec3(texPos12.x, texPos12.y, uv.z)) * w12.x * w12.y; + result += texture(tex, vec3(texPos3.x, texPos12.y, uv.z)) * w3.x * w12.y; + result += texture(tex, vec3(texPos0.x, texPos3.y, uv.z)) * w0.x * w3.y; + result += texture(tex, vec3(texPos12.x, texPos3.y, uv.z)) * w12.x * w3.y; + result += texture(tex, vec3(texPos3.x, texPos3.y, uv.z)) * w3.x * w3.y; + return result; +} +`,Ole=`precision highp float; +precision highp sampler2DArray; + +#include "core/turbo" +#include "catmullRomSampling" +#include "varianceClipping" + +uniform sampler2D colorBuffer; +uniform sampler2D depthVelocityBuffer; +uniform sampler2D colorHistoryBuffer; + +#ifdef SHADOW_LENGTH +uniform sampler2D shadowLengthBuffer; +uniform sampler2D shadowLengthHistoryBuffer; +#endif // SHADOW_LENGTH + +uniform vec2 texelSize; +uniform int frame; +uniform float varianceGamma; +uniform float temporalAlpha; +uniform vec2 jitterOffset; + +in vec2 vUv; + +layout(location = 0) out vec4 outputColor; +#ifdef SHADOW_LENGTH +layout(location = 1) out float outputShadowLength; +#endif // SHADOW_LENGTH + +const ivec2 neighborOffsets[9] = ivec2[9]( + ivec2(-1, -1), + ivec2(-1, 0), + ivec2(-1, 1), + ivec2(0, -1), + ivec2(0, 0), + ivec2(0, 1), + ivec2(1, -1), + ivec2(1, 0), + ivec2(1, 1) +); + +const ivec4[4] bayerIndices = ivec4[4]( + ivec4(0, 12, 3, 15), + ivec4(8, 4, 11, 7), + ivec4(2, 14, 1, 13), + ivec4(10, 6, 9, 5) +); + +vec4 getClosestFragment(const ivec2 coord) { + vec4 result = vec4(1e7, 0.0, 0.0, 0.0); + vec4 neighbor; + #pragma unroll_loop_start + for (int i = 0; i < 9; ++i) { + neighbor = texelFetchOffset(depthVelocityBuffer, coord, 0, neighborOffsets[i]); + if (neighbor.r < result.r) { + result = neighbor; + } + } + #pragma unroll_loop_end + return result; +} + +void temporalUpscale( + const ivec2 coord, + const ivec2 lowResCoord, + const bool currentFrame, + out vec4 outputColor, + out float outputShadowLength +) { + vec4 currentColor = texelFetch(colorBuffer, lowResCoord, 0); + #ifdef SHADOW_LENGTH + vec4 currentShadowLength = vec4(texelFetch(shadowLengthBuffer, lowResCoord, 0).rgb, 1.0); + #endif // SHADOW_LENGTH + + if (currentFrame) { + // Use the texel just rendered without any accumulation. + outputColor = currentColor; + #ifdef SHADOW_LENGTH + outputShadowLength = currentShadowLength.r; + #endif // SHADOW_LENGTH + return; + } + + vec4 depthVelocity = getClosestFragment(lowResCoord); + vec2 velocity = depthVelocity.gb; + vec2 prevUv = vUv - velocity; + if (prevUv.x < 0.0 || prevUv.x > 1.0 || prevUv.y < 0.0 || prevUv.y > 1.0) { + outputColor = currentColor; + #ifdef SHADOW_LENGTH + outputShadowLength = currentShadowLength.r; + #endif // SHADOW_LENGTH + return; // Rejection + } + + // Variance clipping with a large variance gamma seems to work fine for + // upsampling. This increases ghosting, of course, but it's hard to notice on + // clouds. + // vec4 historyColor = textureCatmullRom(colorHistoryBuffer, prevUv); + vec4 historyColor = texture(colorHistoryBuffer, prevUv); + vec4 clippedColor = varianceClipping(colorBuffer, vUv, currentColor, historyColor, varianceGamma); + outputColor = clippedColor; + + #ifdef SHADOW_LENGTH + // Sampling the shadow length history using scene depth doesn't make much + // sense, but it's too hard to derive it properly. At least this approach + // resolves the edges of scene objects. + // vec4 historyShadowLength = vec4(textureCatmullRom(shadowLengthHistoryBuffer, prevUv).rgb, 1.0); + vec4 historyShadowLength = vec4(texture(shadowLengthHistoryBuffer, prevUv).rgb, 1.0); + vec4 clippedShadowLength = varianceClipping( + shadowLengthBuffer, + vUv, + currentShadowLength, + historyShadowLength, + varianceGamma + ); + outputShadowLength = clippedShadowLength.r; + #endif // SHADOW_LENGTH +} + +void temporalAntialiasing(const ivec2 coord, out vec4 outputColor, out float outputShadowLength) { + vec4 currentColor = texelFetch(colorBuffer, coord, 0); + #ifdef SHADOW_LENGTH + vec4 currentShadowLength = vec4(texelFetch(shadowLengthBuffer, coord, 0).rgb, 1.0); + #endif // SHADOW_LENGTH + + vec4 depthVelocity = getClosestFragment(coord); + vec2 velocity = depthVelocity.gb; + + vec2 prevUv = vUv - velocity; + if (prevUv.x < 0.0 || prevUv.x > 1.0 || prevUv.y < 0.0 || prevUv.y > 1.0) { + outputColor = currentColor; + #ifdef SHADOW_LENGTH + outputShadowLength = currentShadowLength.r; + #endif // SHADOW_LENGTH + return; // Rejection + } + + vec4 historyColor = texture(colorHistoryBuffer, prevUv); + vec4 clippedColor = varianceClipping(colorBuffer, coord, currentColor, historyColor); + outputColor = mix(clippedColor, currentColor, temporalAlpha); + + #ifdef SHADOW_LENGTH + vec4 historyShadowLength = vec4(texture(shadowLengthHistoryBuffer, prevUv).rgb, 1.0); + vec4 clippedShadowLength = varianceClipping( + shadowLengthBuffer, + coord, + currentShadowLength, + historyShadowLength + ); + outputShadowLength = mix(clippedShadowLength.r, currentShadowLength.r, temporalAlpha); + #endif // SHADOW_LENGTH +} + +void main() { + ivec2 coord = ivec2(gl_FragCoord.xy); + + #if !defined(SHADOW_LENGTH) + float outputShadowLength; + #endif // !defined(SHADOW_LENGTH) + + #ifdef TEMPORAL_UPSCALE + ivec2 lowResCoord = coord / 4; + int bayerValue = bayerIndices[coord.x % 4][coord.y % 4]; + bool currentFrame = bayerValue == frame % 16; + temporalUpscale(coord, lowResCoord, currentFrame, outputColor, outputShadowLength); + #else // TEMPORAL_UPSCALE + temporalAntialiasing(coord, outputColor, outputShadowLength); + #endif // TEMPORAL_UPSCALE + + #if defined(SHADOW_LENGTH) && defined(DEBUG_SHOW_SHADOW_LENGTH) + outputColor = vec4(turbo(outputShadowLength * 0.05), 1.0); + #endif // defined(SHADOW_LENGTH) && defined(DEBUG_SHOW_SHADOW_LENGTH) + + #ifdef DEBUG_SHOW_VELOCITY + outputColor.rgb = outputColor.rgb + vec3(abs(texture(depthVelocityBuffer, vUv).gb) * 10.0, 0.0); + #endif // DEBUG_SHOW_VELOCITY +} +`,Lle=`precision highp float; + +layout(location = 0) in vec3 position; + +out vec2 vUv; + +void main() { + vUv = position.xy * 0.5 + 0.5; + gl_Position = vec4(position.xy, 1.0, 1.0); +} +`,nF=`#ifdef VARIANCE_9_SAMPLES +#define VARIANCE_OFFSET_COUNT 8 +const ivec2 varianceOffsets[8] = ivec2[8]( + ivec2(-1, -1), + ivec2(-1, 1), + ivec2(1, -1), + ivec2(1, 1), + ivec2(1, 0), + ivec2(0, -1), + ivec2(0, 1), + ivec2(-1, 0) +); +#else // VARIANCE_9_SAMPLES +#define VARIANCE_OFFSET_COUNT 4 +const ivec2 varianceOffsets[4] = ivec2[4](ivec2(1, 0), ivec2(0, -1), ivec2(0, 1), ivec2(-1, 0)); +#endif // VARIANCE_9_SAMPLES + +// Reference: https://github.com/playdeadgames/temporal +vec4 clipAABB(const vec4 current, const vec4 history, const vec4 minColor, const vec4 maxColor) { + vec3 pClip = 0.5 * (maxColor.rgb + minColor.rgb); + vec3 eClip = 0.5 * (maxColor.rgb - minColor.rgb) + 1e-7; + vec4 vClip = history - vec4(pClip, current.a); + vec3 vUnit = vClip.xyz / eClip; + vec3 aUnit = abs(vUnit); + float maUnit = max(aUnit.x, max(aUnit.y, aUnit.z)); + if (maUnit > 1.0) { + return vec4(pClip, current.a) + vClip / maUnit; + } + return history; +} + +#ifdef VARIANCE_SAMPLER_ARRAY +#define VARIANCE_SAMPLER sampler2DArray +#define VARIANCE_SAMPLER_COORD ivec3 +#else // VARIANCE_SAMPLER_ARRAY +#define VARIANCE_SAMPLER sampler2D +#define VARIANCE_SAMPLER_COORD ivec2 +#endif // VARIANCE_SAMPLER_ARRAY + +// Variance clipping +// Reference: https://developer.download.nvidia.com/gameworks/events/GDC2016/msalvi_temporal_supersampling.pdf +vec4 varianceClipping( + const VARIANCE_SAMPLER inputBuffer, + const VARIANCE_SAMPLER_COORD coord, + const vec4 current, + const vec4 history, + const float gamma +) { + vec4 moment1 = current; + vec4 moment2 = current * current; + vec4 neighbor; + #pragma unroll_loop_start + for (int i = 0; i < 8; ++i) { + #if UNROLLED_LOOP_INDEX < VARIANCE_OFFSET_COUNT + neighbor = texelFetchOffset(inputBuffer, coord, 0, varianceOffsets[i]); + moment1 += neighbor; + moment2 += neighbor * neighbor; + #endif // UNROLLED_LOOP_INDEX < VARIANCE_OFFSET_COUNT + } + #pragma unroll_loop_end + + const float N = float(VARIANCE_OFFSET_COUNT + 1); + vec4 mean = moment1 / N; + vec4 varianceGamma = sqrt(max(moment2 / N - mean * mean, 0.0)) * gamma; + vec4 minColor = mean - varianceGamma; + vec4 maxColor = mean + varianceGamma; + return clipAABB(clamp(mean, minColor, maxColor), history, minColor, maxColor); +} + +vec4 varianceClipping( + const VARIANCE_SAMPLER inputBuffer, + const VARIANCE_SAMPLER_COORD coord, + const vec4 current, + const vec4 history +) { + return varianceClipping(inputBuffer, coord, current, history, 1.0); +} + +vec4 varianceClipping( + const sampler2D inputBuffer, + const vec2 coord, + const vec4 current, + const vec4 history, + const float gamma +) { + vec4 moment1 = current; + vec4 moment2 = current * current; + vec4 neighbor; + #pragma unroll_loop_start + for (int i = 0; i < 8; ++i) { + #if UNROLLED_LOOP_INDEX < VARIANCE_OFFSET_COUNT + neighbor = textureOffset(inputBuffer, coord, varianceOffsets[i]); + moment1 += neighbor; + moment2 += neighbor * neighbor; + #endif // UNROLLED_LOOP_INDEX < VARIANCE_OFFSET_COUNT + } + #pragma unroll_loop_end + + const float N = float(VARIANCE_OFFSET_COUNT + 1); + vec4 mean = moment1 / N; + vec4 varianceGamma = sqrt(max(moment2 / N - mean * mean, 0.0)) * gamma; + vec4 minColor = mean - varianceGamma; + vec4 maxColor = mean + varianceGamma; + return clipAABB(clamp(mean, minColor, maxColor), history, minColor, maxColor); +} + +vec4 varianceClipping( + const sampler2D inputBuffer, + const vec2 coord, + const vec4 current, + const vec4 history +) { + return varianceClipping(inputBuffer, coord, current, history, 1.0); +} +`;var Ile=Object.defineProperty,iF=(n,e,t,i)=>{for(var r=void 0,a=n.length-1,s;a>=0;a--)(s=n[a])&&(r=s(e,t,r)||r);return r&&Ile(e,t,r),r};let aC=class extends td{constructor({colorBuffer:e=null,depthVelocityBuffer:t=null,shadowLengthBuffer:i=null,colorHistoryBuffer:r=null,shadowLengthHistoryBuffer:a=null}={}){super({name:"CloudsResolveMaterial",glslVersion:No,vertexShader:Lle,fragmentShader:pv(Wr(Ole,{core:{turbo:CB},catmullRomSampling:Nle,varianceClipping:nF})),uniforms:{colorBuffer:new $(e),depthVelocityBuffer:new $(t),shadowLengthBuffer:new $(i),colorHistoryBuffer:new $(r),shadowLengthHistoryBuffer:new $(a),texelSize:new $(new re),frame:new $(0),jitterOffset:new $(new re),varianceGamma:new $(2),temporalAlpha:new $(.1)}}),this.temporalUpscale=!0,this.shadowLength=!0}setSize(e,t){this.uniforms.texelSize.value.set(1/e,1/t)}onBeforeRender(e,t,i,r,a,s){const o=this.uniforms.frame.value%16,l=$B[o],u=(l.x-.5)*4,d=(l.y-.5)*4;this.uniforms.jitterOffset.value.set(u,d)}};iF([gn("TEMPORAL_UPSCALE")],aC.prototype,"temporalUpscale");iF([gn("SHADOW_LENGTH")],aC.prototype,"shadowLength");class rF extends Qr{constructor(e,t){super(e),this._mainCamera=new ou;const{shadow:i}=t;this.shadow=i}get mainCamera(){return this._mainCamera}set mainCamera(e){this._mainCamera=e}}function uM(n,{depthVelocity:e,shadowLength:t}){const i=new pi(1,1,{depthBuffer:!1,type:Jn});i.texture.minFilter=Bt,i.texture.magFilter=Bt,i.texture.name=n;let r;e&&(r=i.texture.clone(),r.isRenderTargetTexture=!0,i.depthVelocity=r,i.textures.push(r));let a;return t&&(a=i.texture.clone(),a.isRenderTargetTexture=!0,a.format=Qs,i.shadowLength=a,i.textures.push(a)),Object.assign(i,{depthVelocity:r??null,shadowLength:a??null})}let Ule=class extends rF{constructor({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i,...r},a){super("CloudsPass",r),this.atmosphere=a,this.width=0,this.height=0,this.currentMaterial=new Jr({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i},a),this.currentPass=new dA(this.currentMaterial),this.resolveMaterial=new aC,this.resolvePass=new dA(this.resolveMaterial),this.initRenderTargets({depthVelocity:!0,shadowLength:Ut.lightShafts})}copyCameraSettings(e){this.currentMaterial.copyCameraSettings(e)}initialize(e,t,i){this.currentPass.initialize(e,t,i),this.resolvePass.initialize(e,t,i)}initRenderTargets(e){var s,o,l;(s=this.currentRenderTarget)==null||s.dispose(),(o=this.resolveRenderTarget)==null||o.dispose(),(l=this.historyRenderTarget)==null||l.dispose();const t=uM("Clouds",e),i=uM("Clouds.A",{...e,depthVelocity:!1}),r=uM("Clouds.B",{...e,depthVelocity:!1});this.currentRenderTarget=t,this.resolveRenderTarget=i,this.historyRenderTarget=r;const a=this.resolveMaterial.uniforms;a.colorBuffer.value=t.texture,a.depthVelocityBuffer.value=t.depthVelocity,a.shadowLengthBuffer.value=t.shadowLength,a.colorHistoryBuffer.value=r.texture,a.shadowLengthHistoryBuffer.value=r.shadowLength}copyShadow(){const e=this.shadow,t=this.currentMaterial.uniforms;for(let i=0;i + +#include "core/math" +#include "core/raySphereIntersection" +#include "types" +#include "parameters" +#include "structuredSampling" +#include "clouds" + +uniform mat4 inverseShadowMatrices[CASCADE_COUNT]; +uniform mat4 reprojectionMatrices[CASCADE_COUNT]; + +// Primary raymarch +uniform int maxIterationCount; +uniform float minStepSize; +uniform float maxStepSize; +uniform float opticalDepthTailScale; + +in vec2 vUv; + +layout(location = 0) out vec4 outputColor[CASCADE_COUNT]; + +// Redundant notation for prettier. +#if CASCADE_COUNT == 1 +layout(location = 1) out vec3 outputDepthVelocity[CASCADE_COUNT]; +#elif CASCADE_COUNT == 2 +layout(location = 2) out vec3 outputDepthVelocity[CASCADE_COUNT]; +#elif CASCADE_COUNT == 3 +layout(location = 3) out vec3 outputDepthVelocity[CASCADE_COUNT]; +#elif CASCADE_COUNT == 4 +layout(location = 4) out vec3 outputDepthVelocity[CASCADE_COUNT]; +#endif // CASCADE_COUNT + +vec4 marchClouds( + const vec3 rayOrigin, + const vec3 rayDirection, + const float maxRayDistance, + const float jitter, + const float mipLevel +) { + // Setup structured volume sampling (SVS). + // While SVS introduces spatial aliasing, it is indeed temporally stable, + // which is important for lower-resolution shadow maps where a flickering + // single pixel can be highly noticeable. + vec3 normal = getStructureNormal(rayDirection, jitter); + float rayDistance; + float stepSize; + intersectStructuredPlanes( + normal, + rayOrigin, + rayDirection, + clamp(maxRayDistance / float(maxIterationCount), minStepSize, maxStepSize), + rayDistance, + stepSize + ); + + #ifdef TEMPORAL_JITTER + rayDistance -= stepSize * jitter; + #endif // TEMPORAL_JITTER + + float extinctionSum = 0.0; + float maxOpticalDepth = 0.0; + float maxOpticalDepthTail = 0.0; + float transmittanceIntegral = 1.0; + float weightedDistanceSum = 0.0; + float transmittanceSum = 0.0; + + int sampleCount = 0; + for (int i = 0; i < maxIterationCount; ++i) { + if (rayDistance > maxRayDistance) { + break; // Termination + } + + vec3 position = rayDistance * rayDirection + rayOrigin; + float height = length(position) - bottomRadius; + + #if !defined(DEBUG_MARCH_INTERVALS) + if (insideLayerIntervals(height)) { + rayDistance += stepSize; + continue; + } + #endif // !defined(DEBUG_MARCH_INTERVALS) + + // Sample rough weather. + vec2 uv = getGlobeUv(position); + WeatherSample weather = sampleWeather(uv, height, mipLevel); + + if (any(greaterThan(weather.density, vec4(minDensity)))) { + // Sample detailed participating media. + // Note this assumes an homogeneous medium. + MediaSample media = sampleMedia(weather, position, uv, mipLevel, jitter); + if (media.extinction > minExtinction) { + extinctionSum += media.extinction; + maxOpticalDepth += media.extinction * stepSize; + transmittanceIntegral *= exp(-media.extinction * stepSize); + weightedDistanceSum += rayDistance * transmittanceIntegral; + transmittanceSum += transmittanceIntegral; + ++sampleCount; + } + } + + if (transmittanceIntegral <= minTransmittance) { + // A large amount of optical depth accumulates in the tail, beyond the + // point of minimum transmittance. The expected optical depth seems to + // decrease exponentially with the number of samples taken before reaching + // the minimum transmittance. + // See the discussion here: https://x.com/shotamatsuda/status/1886259549931520437 + maxOpticalDepthTail = min( + opticalDepthTailScale * stepSize * exp(float(1 - sampleCount)), + stepSize * 0.5 // Excessive optical depth only introduces aliasing. + ); + break; // Early termination + } + rayDistance += stepSize; + } + + if (sampleCount == 0) { + return vec4(maxRayDistance, 0.0, 0.0, 0.0); + } + float frontDepth = min(weightedDistanceSum / transmittanceSum, maxRayDistance); + float meanExtinction = extinctionSum / float(sampleCount); + return vec4(frontDepth, meanExtinction, maxOpticalDepth, maxOpticalDepthTail); +} + +void getRayNearFar( + const vec3 sunPosition, + const vec3 rayDirection, + out float rayNear, + out float rayFar +) { + vec4 firstIntersections = raySphereFirstIntersection( + sunPosition, + rayDirection, + vec3(0.0), + bottomRadius + vec4(shadowTopHeight, shadowBottomHeight, 0.0, 0.0) + ); + rayNear = max(0.0, firstIntersections.x); + rayFar = firstIntersections.y; + if (rayFar < 0.0) { + rayFar = 1e6; + } +} + +void cascade( + const int cascadeIndex, + const float mipLevel, + out vec4 outputColor, + out vec3 outputDepthVelocity +) { + vec2 clip = vUv * 2.0 - 1.0; + vec4 point = inverseShadowMatrices[cascadeIndex] * vec4(clip.xy, -1.0, 1.0); + point /= point.w; + vec3 sunPosition = (worldToECEFMatrix * vec4(point.xyz, 1.0)).xyz + altitudeCorrection; + + vec3 rayDirection = normalize(-sunDirection); + float rayNear; + float rayFar; + getRayNearFar(sunPosition, rayDirection, rayNear, rayFar); + + vec3 rayOrigin = rayNear * rayDirection + sunPosition; + float stbn = getSTBN(); + vec4 color = marchClouds(rayOrigin, rayDirection, rayFar - rayNear, stbn, mipLevel); + outputColor = color; + + // Velocity for temporal resolution. + #ifdef TEMPORAL_PASS + vec3 frontPosition = color.x * rayDirection + rayOrigin; + vec3 frontPositionWorld = (ecefToWorldMatrix * vec4(frontPosition - altitudeCorrection, 1.0)).xyz; + vec4 prevClip = reprojectionMatrices[cascadeIndex] * vec4(frontPositionWorld, 1.0); + prevClip /= prevClip.w; + vec2 prevUv = prevClip.xy * 0.5 + 0.5; + vec2 velocity = (vUv - prevUv) * resolution; + outputDepthVelocity = vec3(color.x, velocity); + #else // TEMPORAL_PASS + outputDepthVelocity = vec3(0.0); + #endif // TEMPORAL_PASS +} + +// TODO: Calculate from the main camera frustum perhaps? +const float mipLevels[4] = float[4](0.0, 0.5, 1.0, 2.0); + +void main() { + #pragma unroll_loop_start + for (int i = 0; i < 4; ++i) { + #if UNROLLED_LOOP_INDEX < CASCADE_COUNT + cascade(UNROLLED_LOOP_INDEX, mipLevels[i], outputColor[i], outputDepthVelocity[i]); + #endif // UNROLLED_LOOP_INDEX < CASCADE_COUNT + } + #pragma unroll_loop_end +} +`,Ble=`precision highp float; + +layout(location = 0) in vec3 position; + +out vec2 vUv; + +void main() { + vUv = position.xy * 0.5 + 0.5; + gl_Position = vec4(position.xy, 1.0, 1.0); +} +`,Fle=`// Implements Structured Volume Sampling in fragment shader: +// https://github.com/huwb/volsample +// Implementation reference: +// https://www.shadertoy.com/view/ttVfDc + +void getIcosahedralVertices(const vec3 direction, out vec3 v1, out vec3 v2, out vec3 v3) { + // Normalization scalers to fit dodecahedron to unit sphere. + const float a = 0.85065080835204; // phi / sqrt(2 + phi) + const float b = 0.5257311121191336; // 1 / sqrt(2 + phi) + + // Derive the vertices of icosahedron where triangle intersects the direction. + // See: https://www.ppsloan.org/publications/AmbientDice.pdf + const float kT = 0.6180339887498948; // 1 / phi + const float kT2 = 0.38196601125010515; // 1 / phi^2 + vec3 absD = abs(direction); + float selector1 = dot(absD, vec3(1.0, kT2, -kT)); + float selector2 = dot(absD, vec3(-kT, 1.0, kT2)); + float selector3 = dot(absD, vec3(kT2, -kT, 1.0)); + v1 = selector1 > 0.0 ? vec3(a, b, 0.0) : vec3(-b, 0.0, a); + v2 = selector2 > 0.0 ? vec3(0.0, a, b) : vec3(a, -b, 0.0); + v3 = selector3 > 0.0 ? vec3(b, 0.0, a) : vec3(0.0, a, -b); + vec3 octantSign = sign(direction); + v1 *= octantSign; + v2 *= octantSign; + v3 *= octantSign; +} + +void swapIfBigger(inout vec4 a, inout vec4 b) { + if (a.w > b.w) { + vec4 t = a; + a = b; + b = t; + } +} + +void sortVertices(inout vec3 a, inout vec3 b, inout vec3 c) { + const vec3 base = vec3(0.5, 0.5, 1.0); + vec4 aw = vec4(a, dot(a, base)); + vec4 bw = vec4(b, dot(b, base)); + vec4 cw = vec4(c, dot(c, base)); + swapIfBigger(aw, bw); + swapIfBigger(bw, cw); + swapIfBigger(aw, bw); + a = aw.xyz; + b = bw.xyz; + c = cw.xyz; +} + +vec3 getPentagonalWeights(const vec3 direction, const vec3 v1, const vec3 v2, const vec3 v3) { + float d1 = dot(v1, direction); + float d2 = dot(v2, direction); + float d3 = dot(v3, direction); + vec3 w = exp(vec3(d1, d2, d3) * 40.0); + return w / (w.x + w.y + w.z); +} + +vec3 getStructureNormal( + const vec3 direction, + const float jitter, + out vec3 a, + out vec3 b, + out vec3 c, + out vec3 weights +) { + getIcosahedralVertices(direction, a, b, c); + sortVertices(a, b, c); + weights = getPentagonalWeights(direction, a, b, c); + return jitter < weights.x + ? a + : jitter < weights.x + weights.y + ? b + : c; +} + +vec3 getStructureNormal(const vec3 direction, const float jitter) { + vec3 a, b, c, weights; + return getStructureNormal(direction, jitter, a, b, c, weights); +} + +// Reference: https://github.com/huwb/volsample/blob/master/src/unity/Assets/Shaders/RayMarchCore.cginc +void intersectStructuredPlanes( + const vec3 normal, + const vec3 rayOrigin, + const vec3 rayDirection, + const float samplePeriod, + out float stepOffset, + out float stepSize +) { + float NoD = dot(rayDirection, normal); + stepSize = samplePeriod / abs(NoD); + + // Skips leftover bit to get from rayOrigin to first strata plane. + stepOffset = -mod(dot(rayOrigin, normal), samplePeriod) / NoD; + + // mod() gives different results depending on if the arg is negative or + // positive. This line makes it consistent, and ensures the first sample is in + // front of the viewer. + if (stepOffset < 0.0) { + stepOffset += stepSize; + } +} +`;var Hle=Object.defineProperty,sm=(n,e,t,i)=>{for(var r=void 0,a=n.length-1,s;a>=0;a--)(s=n[a])&&(r=s(e,t,r)||r);return r&&Hle(e,t,r),r};let od=class extends td{constructor({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i}){super({name:"ShadowMaterial",glslVersion:No,vertexShader:Ble,fragmentShader:pv(Wr(zle,{core:{math:QR,raySphereIntersection:_T},types:HA,parameters:tF,structuredSampling:Fle,clouds:eF})),uniforms:{...e,...t,...i,inverseShadowMatrices:new $(Array.from({length:4},()=>new Me)),reprojectionMatrices:new $(Array.from({length:4},()=>new Me)),resolution:new $(new re),frame:new $(0),stbnTexture:new $(null),maxIterationCount:new $(Ut.shadow.maxIterationCount),minStepSize:new $(Ut.shadow.minStepSize),maxStepSize:new $(Ut.shadow.maxStepSize),minDensity:new $(Ut.shadow.minDensity),minExtinction:new $(Ut.shadow.minExtinction),minTransmittance:new $(Ut.shadow.minTransmittance),opticalDepthTailScale:new $(2)},defines:{SHADOW:"1",TEMPORAL_PASS:"1",TEMPORAL_JITTER:"1"}}),this.localWeatherChannels="rgba",this.cascadeCount=Ut.shadow.cascadeCount,this.temporalPass=!0,this.temporalJitter=!0,this.shapeDetail=Ut.shapeDetail,this.turbulence=Ut.turbulence,this.cascadeCount=Ut.shadow.cascadeCount}setSize(e,t){this.uniforms.resolution.value.set(e,t)}};sm([TB("LOCAL_WEATHER_CHANNELS",{validate:n=>/^[rgba]{4}$/.test(n)})],od.prototype,"localWeatherChannels");sm([ad("CASCADE_COUNT",{min:1,max:4})],od.prototype,"cascadeCount");sm([gn("TEMPORAL_PASS")],od.prototype,"temporalPass");sm([gn("TEMPORAL_JITTER")],od.prototype,"temporalJitter");sm([gn("SHAPE_DETAIL")],od.prototype,"shapeDetail");sm([gn("TURBULENCE")],od.prototype,"turbulence");const Vle=`precision highp float; +precision highp sampler2DArray; + +#define VARIANCE_9_SAMPLES 1 +#define VARIANCE_SAMPLER_ARRAY 1 + +#include "varianceClipping" + +uniform sampler2DArray inputBuffer; +uniform sampler2DArray historyBuffer; + +uniform vec2 texelSize; +uniform float varianceGamma; +uniform float temporalAlpha; + +in vec2 vUv; + +layout(location = 0) out vec4 outputColor[CASCADE_COUNT]; + +const ivec2 neighborOffsets[9] = ivec2[9]( + ivec2(-1, -1), + ivec2(-1, 0), + ivec2(-1, 1), + ivec2(0, -1), + ivec2(0, 0), + ivec2(0, 1), + ivec2(1, -1), + ivec2(1, 0), + ivec2(1, 1) +); + +vec4 getClosestFragment(const ivec3 coord) { + vec4 result = vec4(1e7, 0.0, 0.0, 0.0); + vec4 neighbor; + #pragma unroll_loop_start + for (int i = 0; i < 9; ++i) { + neighbor = texelFetchOffset( + inputBuffer, + coord + ivec3(0, 0, CASCADE_COUNT), + 0, + neighborOffsets[i] + ); + if (neighbor.r < result.r) { + result = neighbor; + } + } + #pragma unroll_loop_end + return result; +} + +void cascade(const int cascadeIndex, out vec4 outputColor) { + ivec3 coord = ivec3(gl_FragCoord.xy, cascadeIndex); + vec4 current = texelFetch(inputBuffer, coord, 0); + + vec4 depthVelocity = getClosestFragment(coord); + vec2 velocity = depthVelocity.gb * texelSize; + vec2 prevUv = vUv - velocity; + if (prevUv.x < 0.0 || prevUv.x > 1.0 || prevUv.y < 0.0 || prevUv.y > 1.0) { + outputColor = current; + return; // Rejection + } + + vec4 history = texture(historyBuffer, vec3(prevUv, float(cascadeIndex))); + vec4 clippedHistory = varianceClipping(inputBuffer, coord, current, history, varianceGamma); + outputColor = mix(clippedHistory, current, temporalAlpha); +} + +void main() { + #pragma unroll_loop_start + for (int i = 0; i < 4; ++i) { + #if UNROLLED_LOOP_INDEX < CASCADE_COUNT + cascade(UNROLLED_LOOP_INDEX, outputColor[i]); + #endif // UNROLLED_LOOP_INDEX < CASCADE_COUNT + } + #pragma unroll_loop_end +} +`,Gle=`precision highp float; + +layout(location = 0) in vec3 position; + +out vec2 vUv; + +void main() { + vUv = position.xy * 0.5 + 0.5; + gl_Position = vec4(position.xy, 1.0, 1.0); +} +`;var kle=Object.defineProperty,Wle=(n,e,t,i)=>{for(var r=void 0,a=n.length-1,s;a>=0;a--)(s=n[a])&&(r=s(e,t,r)||r);return r&&kle(e,t,r),r};let aF=class extends td{constructor({inputBuffer:e=null,historyBuffer:t=null}={}){super({name:"ShadowResolveMaterial",glslVersion:No,vertexShader:Gle,fragmentShader:pv(Wr(Vle,{varianceClipping:nF})),uniforms:{inputBuffer:new $(e),historyBuffer:new $(t),texelSize:new $(new re),varianceGamma:new $(1),temporalAlpha:new $(.01)},defines:{}}),this.cascadeCount=Ut.shadow.cascadeCount}setSize(e,t){this.uniforms.texelSize.value.set(1/e,1/t)}};Wle([ad("CASCADE_COUNT",{min:1,max:4})],aF.prototype,"cascadeCount");function hM(n){const e=new O9(1,1,1,{depthBuffer:!1});return e.texture.type=Jn,e.texture.minFilter=Bt,e.texture.magFilter=Bt,e.texture.name=n,e}let Xle=class extends rF{constructor({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i,...r}){super("ShadowPass",r),this.width=0,this.height=0,this.currentMaterial=new od({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i}),this.currentPass=new A5(this.currentMaterial),this.resolveMaterial=new aF,this.resolvePass=new A5(this.resolveMaterial),this.initRenderTargets()}initialize(e,t,i){this.currentPass.initialize(e,t,i),this.resolvePass.initialize(e,t,i)}initRenderTargets(){var a,s,o;(a=this.currentRenderTarget)==null||a.dispose(),(s=this.resolveRenderTarget)==null||s.dispose(),(o=this.historyRenderTarget)==null||o.dispose();const e=hM("Shadow"),t=this.temporalPass?hM("Shadow.A"):null,i=this.temporalPass?hM("Shadow.B"):null;this.currentRenderTarget=e,this.resolveRenderTarget=t,this.historyRenderTarget=i;const r=this.resolveMaterial.uniforms;r.inputBuffer.value=e.texture,r.historyBuffer.value=(i==null?void 0:i.texture)??null}copyShadow(){const e=this.shadow,t=this.currentMaterial.uniforms;for(let i=0;i0&&(lr&&(r=f),d&&f>s&&(s=f)),dM[o]=d?1:0}i!==1/0?(n.minHeight.value=i,n.maxHeight.value=r):(Uc(r===0),n.minHeight.value=0),a!==1/0?(n.shadowBottomHeight.value=a,n.shadowTopHeight.value=s):(Uc(s===0),n.shadowBottomHeight.value=0),n.shadowLayerMask.value.fromArray(dM)}function Zle(n,e){return{bottomRadius:new $(n.bottomRadius),topRadius:new $(n.topRadius),worldToECEFMatrix:new $(e.worldToECEFMatrix),ecefToWorldMatrix:new $(e.ecefToWorldMatrix),altitudeCorrection:new $(e.altitudeCorrection),sunDirection:new $(e.sunDirection)}}const Qle=`uniform sampler2D cloudsBuffer; + +void mainImage(const vec4 inputColor, const vec2 uv, out vec4 outputColor) { + #ifdef SKIP_RENDERING + outputColor = inputColor; + #else // SKIP_RENDERING + vec4 clouds = texture(cloudsBuffer, uv); + outputColor.rgb = inputColor.rgb * (1.0 - clouds.a) + clouds.rgb; + outputColor.a = inputColor.a * (1.0 - clouds.a) + clouds.a; + #endif // SKIP_RENDERING +} +`;var Kle=Object.defineProperty,Jle=(n,e,t,i)=>{for(var r=void 0,a=n.length-1,s;a>=0;a--)(s=n[a])&&(r=s(e,t,r)||r);return r&&Kle(e,t,r),r};const l0=new D,$le=new re,ece=new Mt,tce=["maxIterationCount","minStepSize","maxStepSize","maxRayDistance","perspectiveStepScale","minDensity","minExtinction","minTransmittance","maxIterationCountToSun","maxIterationCountToGround","minSecondaryStepSize","secondaryStepScale","maxShadowFilterRadius","maxShadowLengthIterationCount","minShadowLengthStepSize","maxShadowLengthRayDistance","hazeDensityScale","hazeExponent","hazeScatteringCoefficient","hazeAbsorptionCoefficient"],nce=["multiScatteringOctaves","accurateSunSkyLight","accuratePhaseFunction"],ice=["maxIterationCount","minStepSize","maxStepSize","minDensity","minExtinction","minTransmittance","opticalDepthTailScale"],rce=["temporalJitter"],ace=["temporalPass"],sce=["cascadeCount","mapSize","maxFar","farScale","splitMode","splitLambda"],ol={type:"change"},sF={resolutionScale:Ut.resolutionScale,width:Rs.AUTO_SIZE,height:Rs.AUTO_SIZE};class oF extends Ug{constructor(e=new ou,t,i=mv.DEFAULT){var d,f,p,m;super("CloudsEffect",Qle,{attributes:Dl.DEPTH,uniforms:new Map([["cloudsBuffer",new $(null)]])}),this.camera=e,this.atmosphere=i,this.cloudLayers=eS.DEFAULT.clone(),this.correctAltitude=!0,this.localWeatherRepeat=new re().setScalar(100),this.localWeatherOffset=new re,this.shapeRepeat=new D().setScalar(3e-4),this.shapeOffset=new D,this.shapeDetailRepeat=new D().setScalar(.006),this.shapeDetailOffset=new D,this.turbulenceRepeat=new re().setScalar(20),this.worldToECEFMatrix=new Me,this.ecefToWorldMatrix=new Me,this.altitudeCorrection=new D,this.sunDirection=new D,this.localWeatherVelocity=new re,this.shapeVelocity=new D,this.shapeDetailVelocity=new D,this._atmosphereOverlay=null,this._atmosphereShadow=null,this._atmosphereShadowLength=null,this.events=new Mi,this.frame=0,this.shadowCascadeCount=0,this.shadowMapSize=new re,this.onResolutionChange=()=>{this.setSize(this.resolution.baseWidth,this.resolution.baseHeight)},this.skipRendering=!0;const{resolutionScale:r,width:a,height:s,resolutionX:o=a,resolutionY:l=s}={...sF,...t};this.shadowMaps=new Ele({cascadeCount:Ut.shadow.cascadeCount,mapSize:Ut.shadow.mapSize,splitLambda:.6}),this.parameterUniforms=qle({localWeatherTexture:((d=this.proceduralLocalWeather)==null?void 0:d.texture)??null,localWeatherRepeat:this.localWeatherRepeat,localWeatherOffset:this.localWeatherOffset,shapeTexture:((f=this.proceduralShape)==null?void 0:f.texture)??null,shapeRepeat:this.shapeRepeat,shapeOffset:this.shapeOffset,shapeDetailTexture:((p=this.proceduralShapeDetail)==null?void 0:p.texture)??null,shapeDetailRepeat:this.shapeDetailRepeat,shapeDetailOffset:this.shapeDetailOffset,turbulenceTexture:((m=this.proceduralTurbulence)==null?void 0:m.texture)??null,turbulenceRepeat:this.turbulenceRepeat}),this.layerUniforms=Yle(),this.atmosphereUniforms=Zle(i,{worldToECEFMatrix:this.worldToECEFMatrix,ecefToWorldMatrix:this.ecefToWorldMatrix,altitudeCorrection:this.altitudeCorrection,sunDirection:this.sunDirection});const u={shadow:this.shadowMaps,parameterUniforms:this.parameterUniforms,layerUniforms:this.layerUniforms,atmosphereUniforms:this.atmosphereUniforms};this.shadowPass=new Xle(u),this.shadowPass.mainCamera=e,this.cloudsPass=new Ule(u,i),this.cloudsPass.mainCamera=e,this.clouds=a5(s5({},this.cloudsPass.currentMaterial,tce),this.cloudsPass.currentMaterial,nce),this.shadow=a5(s5({},this.shadowPass.currentMaterial,ice),this.shadowPass.currentMaterial,rce,this.shadowPass,ace,this.shadowMaps,sce),this.resolution=new Rs(this,o,l,r),this.resolution.addEventListener("change",this.onResolutionChange)}get mainCamera(){return this.camera}set mainCamera(e){this.camera=e,this.shadowPass.mainCamera=e,this.cloudsPass.mainCamera=e}initialize(e,t,i){this.shadowPass.initialize(e,t,i),this.cloudsPass.initialize(e,t,i)}updateSharedUniforms(e){jle(this.layerUniforms,this.cloudLayers);const{parameterUniforms:t}=this;t.localWeatherOffset.value.add($le.copy(this.localWeatherVelocity).multiplyScalar(e)),t.shapeOffset.value.add(l0.copy(this.shapeVelocity).multiplyScalar(e)),t.shapeDetailOffset.value.add(l0.copy(this.shapeDetailVelocity).multiplyScalar(e));const i=this.worldToECEFMatrix;this.ecefToWorldMatrix.copy(i).invert();const r=this.camera.getWorldPosition(l0).applyMatrix4(this.worldToECEFMatrix),a=this.altitudeCorrection;this.correctAltitude?KR(r,this.atmosphere.bottomRadius,this.ellipsoid,a):a.setScalar(0);const s=this.ellipsoid.getSurfaceNormal(r,l0),o=this.sunDirection.dot(s),l=SB(1e6,1e3,o),u=ece.setFromMatrix4(i).transpose();this.shadowMaps.update(this.camera,l0.copy(this.sunDirection).applyMatrix3(u),l)}updateWeatherTextureChannels(){const e=this.cloudLayers.localWeatherChannels;this.cloudsPass.currentMaterial.localWeatherChannels=e,this.shadowPass.currentMaterial.localWeatherChannels=e}updateAtmosphereComposition(){const{shadowMaps:e,shadowPass:t,cloudsPass:i}=this,r=t.currentMaterial.uniforms,a=i.currentMaterial.uniforms,s=this._atmosphereOverlay,o=Object.assign(this._atmosphereOverlay??{},{map:i.outputBuffer});s!==o&&(this._atmosphereOverlay=o,ol.target=this,ol.property="atmosphereOverlay",this.events.dispatchEvent(ol));const l=this._atmosphereShadow,u=Object.assign(this._atmosphereShadow??{},{map:t.outputBuffer,mapSize:e.mapSize,cascadeCount:e.cascadeCount,intervals:a.shadowIntervals.value,matrices:a.shadowMatrices.value,inverseMatrices:r.inverseShadowMatrices.value,far:e.far,topHeight:a.shadowTopHeight.value});l!==u&&(this._atmosphereShadow=u,ol.target=this,ol.property="atmosphereShadow",this.events.dispatchEvent(ol));const d=this._atmosphereShadowLength,f=i.shadowLengthBuffer!=null?Object.assign(this._atmosphereShadowLength??{},{map:i.shadowLengthBuffer}):null;d!==f&&(this._atmosphereShadowLength=f,ol.target=this,ol.property="atmosphereShadowLength",this.events.dispatchEvent(ol))}update(e,t,i=0){var o,l,u,d;const{shadowMaps:r,shadowPass:a,cloudsPass:s}=this;if(r.cascadeCount!==this.shadowCascadeCount||!r.mapSize.equals(this.shadowMapSize)){const{width:f,height:p}=r.mapSize,m=r.cascadeCount;this.shadowMapSize.set(f,p),this.shadowCascadeCount=m,a.setSize(f,p,m),s.setShadowSize(f,p,m)}(o=this.proceduralLocalWeather)==null||o.render(e,i),(l=this.proceduralShape)==null||l.render(e,i),(u=this.proceduralShapeDetail)==null||u.render(e,i),(d=this.proceduralTurbulence)==null||d.render(e,i),++this.frame,this.updateSharedUniforms(i),this.updateWeatherTextureChannels(),a.update(e,this.frame,i),s.shadowBuffer=a.outputBuffer,s.update(e,this.frame,i),this.updateAtmosphereComposition(),this.uniforms.get("cloudsBuffer").value=this.cloudsPass.outputBuffer}setSize(e,t){const{resolution:i}=this;i.setBaseSize(e,t);const{width:r,height:a}=i;this.cloudsPass.setSize(r,a)}setDepthTexture(e,t){this.shadowPass.setDepthTexture(e,t),this.cloudsPass.setDepthTexture(e,t)}set qualityPreset(e){const{clouds:t,shadow:i,...r}=Mle[e];Object.assign(this,r),Object.assign(this.clouds,t),Object.assign(this.shadow,i)}get localWeatherTexture(){return this.proceduralLocalWeather??this.parameterUniforms.localWeatherTexture.value}set localWeatherTexture(e){e instanceof In||e==null?(this.proceduralLocalWeather=void 0,this.parameterUniforms.localWeatherTexture.value=e):(this.proceduralLocalWeather=e,this.parameterUniforms.localWeatherTexture.value=e.texture)}get shapeTexture(){return this.proceduralShape??this.parameterUniforms.shapeTexture.value}set shapeTexture(e){e instanceof ws||e==null?(this.proceduralShape=void 0,this.parameterUniforms.shapeTexture.value=e):(this.proceduralShape=e,this.parameterUniforms.shapeTexture.value=e.texture)}get shapeDetailTexture(){return this.proceduralShapeDetail??this.parameterUniforms.shapeDetailTexture.value}set shapeDetailTexture(e){e instanceof ws||e==null?(this.proceduralShapeDetail=void 0,this.parameterUniforms.shapeDetailTexture.value=e):(this.proceduralShapeDetail=e,this.parameterUniforms.shapeDetailTexture.value=e.texture)}get turbulenceTexture(){return this.proceduralTurbulence??this.parameterUniforms.turbulenceTexture.value}set turbulenceTexture(e){e instanceof In||e==null?(this.proceduralTurbulence=void 0,this.parameterUniforms.turbulenceTexture.value=e):(this.proceduralTurbulence=e,this.parameterUniforms.turbulenceTexture.value=e.texture)}get stbnTexture(){return this.cloudsPass.currentMaterial.uniforms.stbnTexture.value}set stbnTexture(e){this.cloudsPass.currentMaterial.uniforms.stbnTexture.value=e,this.shadowPass.currentMaterial.uniforms.stbnTexture.value=e}get resolutionScale(){return this.resolution.scale}set resolutionScale(e){this.resolution.scale=e}get temporalUpscale(){return this.cloudsPass.temporalUpscale}set temporalUpscale(e){this.cloudsPass.temporalUpscale=e}get lightShafts(){return this.cloudsPass.lightShafts}set lightShafts(e){this.cloudsPass.lightShafts=e}get shapeDetail(){return this.cloudsPass.currentMaterial.shapeDetail}set shapeDetail(e){this.cloudsPass.currentMaterial.shapeDetail=e,this.shadowPass.currentMaterial.shapeDetail=e}get turbulence(){return this.cloudsPass.currentMaterial.turbulence}set turbulence(e){this.cloudsPass.currentMaterial.turbulence=e,this.shadowPass.currentMaterial.turbulence=e}get haze(){return this.cloudsPass.currentMaterial.haze}set haze(e){this.cloudsPass.currentMaterial.haze=e}get scatteringCoefficient(){return this.parameterUniforms.scatteringCoefficient.value}set scatteringCoefficient(e){this.parameterUniforms.scatteringCoefficient.value=e}get absorptionCoefficient(){return this.parameterUniforms.absorptionCoefficient.value}set absorptionCoefficient(e){this.parameterUniforms.absorptionCoefficient.value=e}get coverage(){return this.parameterUniforms.coverage.value}set coverage(e){this.parameterUniforms.coverage.value=e}get turbulenceDisplacement(){return this.parameterUniforms.turbulenceDisplacement.value}set turbulenceDisplacement(e){this.parameterUniforms.turbulenceDisplacement.value=e}get scatterAnisotropy1(){return this.cloudsPass.currentMaterial.scatterAnisotropy1}set scatterAnisotropy1(e){this.cloudsPass.currentMaterial.scatterAnisotropy1=e}get scatterAnisotropy2(){return this.cloudsPass.currentMaterial.scatterAnisotropy2}set scatterAnisotropy2(e){this.cloudsPass.currentMaterial.scatterAnisotropy2=e}get scatterAnisotropyMix(){return this.cloudsPass.currentMaterial.scatterAnisotropyMix}set scatterAnisotropyMix(e){this.cloudsPass.currentMaterial.scatterAnisotropyMix=e}get skyIrradianceScale(){return this.skyLightScale}set skyIrradianceScale(e){this.skyLightScale=e}get skyLightScale(){return this.cloudsPass.currentMaterial.uniforms.skyLightScale.value}set skyLightScale(e){this.cloudsPass.currentMaterial.uniforms.skyLightScale.value=e}get groundIrradianceScale(){return this.groundBounceScale}set groundIrradianceScale(e){this.groundBounceScale=e}get groundBounceScale(){return this.cloudsPass.currentMaterial.uniforms.groundBounceScale.value}set groundBounceScale(e){this.cloudsPass.currentMaterial.uniforms.groundBounceScale.value=e}get powderScale(){return this.cloudsPass.currentMaterial.uniforms.powderScale.value}set powderScale(e){this.cloudsPass.currentMaterial.uniforms.powderScale.value=e}get powderExponent(){return this.cloudsPass.currentMaterial.uniforms.powderExponent.value}set powderExponent(e){this.cloudsPass.currentMaterial.uniforms.powderExponent.value=e}get atmosphereOverlay(){return this._atmosphereOverlay}get atmosphereShadow(){return this._atmosphereShadow}get atmosphereShadowLength(){return this._atmosphereShadowLength}get irradianceTexture(){return this.cloudsPass.currentMaterial.irradianceTexture}set irradianceTexture(e){this.cloudsPass.currentMaterial.irradianceTexture=e}get scatteringTexture(){return this.cloudsPass.currentMaterial.scatteringTexture}set scatteringTexture(e){this.cloudsPass.currentMaterial.scatteringTexture=e}get transmittanceTexture(){return this.cloudsPass.currentMaterial.transmittanceTexture}set transmittanceTexture(e){this.cloudsPass.currentMaterial.transmittanceTexture=e}get singleMieScatteringTexture(){return this.cloudsPass.currentMaterial.singleMieScatteringTexture}set singleMieScatteringTexture(e){this.cloudsPass.currentMaterial.singleMieScatteringTexture=e}get higherOrderScatteringTexture(){return this.cloudsPass.currentMaterial.higherOrderScatteringTexture}set higherOrderScatteringTexture(e){this.cloudsPass.currentMaterial.higherOrderScatteringTexture=e}get ellipsoid(){return this.cloudsPass.currentMaterial.ellipsoid}set ellipsoid(e){this.cloudsPass.currentMaterial.ellipsoid=e}get sunAngularRadius(){return this.cloudsPass.currentMaterial.sunAngularRadius}set sunAngularRadius(e){this.cloudsPass.currentMaterial.sunAngularRadius=e}}Jle([gn("SKIP_RENDERING")],oF.prototype,"skipRendering");const oce=128,lce=32,bT="45a1c6c1bb9fd38b3680fd120795ff4c32df68ff",cce=`https://media.githubusercontent.com/media/takram-design-engineering/three-geospatial/${bT}/packages/clouds/assets/local_weather.png`,uce=`https://media.githubusercontent.com/media/takram-design-engineering/three-geospatial/${bT}/packages/clouds/assets/shape.bin`,hce=`https://media.githubusercontent.com/media/takram-design-engineering/three-geospatial/${bT}/packages/clouds/assets/shape_detail.bin`,dce=`https://media.githubusercontent.com/media/takram-design-engineering/three-geospatial/${bT}/packages/clouds/assets/turbulence.png`,lF=ie.createContext(null),fce=({layers:n,disableDefault:e=!1,children:t})=>{const[i,r]=ie.useState();return ie.useLayoutEffect(()=>{n.set(e?Array(4).fill(Ys.DEFAULT):eS.DEFAULT),r({layers:n,indexPool:[0,1,2,3],disableDefault:e})},[n,e]),i!=null&&ot.jsx(lF.Provider,{value:i,children:t})};function w5(n,e){const t=ie.useMemo(()=>typeof n=="string"?new ER().load(n,i=>{i.minFilter=m9,i.magFilter=Bt,i.wrapS=Ir,i.wrapT=Ir,i.colorSpace=Xr,i.needsUpdate=!0}):void 0,[n]);return ie.useEffect(()=>{if(t!=null)return()=>{t.dispose()}},[t]),(typeof n=="string"?t:n)??null}function R5(n,e){const t=ie.useMemo(()=>typeof n=="string"?new ch(ws,bB,{width:e,height:e,depth:e,format:Qs,minFilter:Bt,magFilter:Bt,wrapS:Ir,wrapT:Ir,wrapR:Ir,colorSpace:Xr}).load(n):void 0,[n,e]);return ie.useEffect(()=>{if(t!=null)return()=>{t.dispose()}},[t]),(typeof n=="string"?t:n)??null}function pce(n){const e=ie.useMemo(()=>typeof n=="string"?new MB().load(n):void 0,[n]);return ie.useEffect(()=>{if(e!=null)return()=>{e.dispose()}},[e]),(typeof n=="string"?e:n)??null}const mce=({ref:n,disableDefaultLayers:e=!1,localWeatherTexture:t=cce,shapeTexture:i=uce,shapeDetailTexture:r=hce,turbulenceTexture:a=dce,stbnTexture:s=Jz,children:o,...l})=>{const{textures:u,transientStates:d,...f}=ie.useContext(rC),[p,m]=YB({...sF,...f,...u,...l}),v=ie.useMemo(()=>new oF,[]);ie.useEffect(()=>()=>{v.dispose()},[v]),_a(()=>{d!=null&&(v.sunDirection.copy(d.sunDirection),v.worldToECEFMatrix.copy(d.worldToECEFMatrix))}),ie.useEffect(()=>{if(d!=null)return d.overlay=v.atmosphereOverlay,d.shadow=v.atmosphereShadow,d.shadowLength=v.atmosphereShadowLength,()=>{d.overlay=null,d.shadow=null,d.shadowLength=null}},[v,d]);const x=ie.useCallback(w=>{if(d!=null)switch(w.property){case"atmosphereOverlay":d.overlay=v.atmosphereOverlay;break;case"atmosphereShadow":d.shadow=v.atmosphereShadow;break;case"atmosphereShadowLength":d.shadowLength=v.atmosphereShadowLength;break}},[v,d]);ie.useEffect(()=>(v.events.addEventListener("change",x),()=>{v.events.removeEventListener("change",x)}),[v,x]),pn(({gl:w})=>w);const S=w5(t),_=R5(i,oce),T=R5(r,lce),E=w5(a),b=pce(s),{camera:R}=ie.useContext(HR);return ot.jsxs(ot.Fragment,{children:[ot.jsx("primitive",{ref:n,object:v,mainCamera:R,...p,localWeatherTexture:S,shapeTexture:_,shapeDetailTexture:T,turbulenceTexture:E,stbnTexture:b,...m}),ot.jsx(fce,{layers:v.cloudLayers,disableDefault:e,children:o})]})},gce=({ref:n,index:e,...t})=>{const i=ie.useContext(lF);if(i==null)throw new Error("CloudLayer can only be used within the Clouds component!");const{layers:r,indexPool:a,disableDefault:s}=i,[o,l]=ie.useState();if(ie.useLayoutEffect(()=>{if(e!=null){const u=a.indexOf(e);if(u!==-1)return a.splice(u,1),l(e),()=>{a.push(e),l(void 0)}}else{const u=a.sort((d,f)=>d-f).shift();if(u!=null)return l(u),()=>{a.push(u),l(void 0)}}},[e,r,a]),ie.useLayoutEffect(()=>{if(o==null)return;const u=r[o];return()=>{u.copy(s?Ys.DEFAULT:eS.DEFAULT[o])}},[r,o,s]),ie.useEffect(()=>{o!=null&&(typeof n=="function"?n(r[o]):n!=null&&(n.current=r[o]))},[n,r,o]),o!=null){const u=r[o];u.copy(s?Ys.DEFAULT:eS.DEFAULT[o]),u.set(t)}return null};class vce{get unloadPriorityCallback(){return this._unloadPriorityCallback}set unloadPriorityCallback(e){e.length===1?(console.warn('LRUCache: "unloadPriorityCallback" function has been changed to take two arguments.'),this._unloadPriorityCallback=(t,i)=>{const r=e(t),a=e(i);return ra?1:0}):this._unloadPriorityCallback=e}constructor(){this.minSize=6e3,this.maxSize=8e3,this.minBytesSize=.3*1073741824,this.maxBytesSize=.4*1073741824,this.unloadPercent=.05,this.autoMarkUnused=!0,this.itemSet=new Map,this.itemList=[],this.usedSet=new Set,this.callbacks=new Map,this.unloadingHandle=-1,this.cachedBytes=0,this.bytesMap=new Map,this.loadedSet=new Set,this._unloadPriorityCallback=null;const e=this.itemSet;this.defaultPriorityCallback=t=>e.get(t)}isFull(){return this.itemSet.size>=this.maxSize||this.cachedBytes>=this.maxBytesSize}getMemoryUsage(e){return this.bytesMap.get(e)||0}setMemoryUsage(e,t){const{bytesMap:i,itemSet:r}=this;r.has(e)&&(this.cachedBytes-=i.get(e)||0,i.set(e,t),this.cachedBytes+=t)}add(e,t){const i=this.itemSet;if(i.has(e)||this.isFull())return!1;const r=this.usedSet,a=this.itemList,s=this.callbacks;return a.push(e),r.add(e),i.set(e,Date.now()),s.set(e,t),!0}has(e){return this.itemSet.has(e)}remove(e){const t=this.usedSet,i=this.itemSet,r=this.itemList,a=this.bytesMap,s=this.callbacks,o=this.loadedSet;if(i.has(e)){this.cachedBytes-=a.get(e)||0,a.delete(e),s.get(e)(e);const l=r.indexOf(e);return r.splice(l,1),t.delete(e),i.delete(e),s.delete(e),o.delete(e),!0}return!1}setLoaded(e,t){const{itemSet:i,loadedSet:r}=this;i.has(e)&&(t===!0?r.add(e):r.delete(e))}markUsed(e){const t=this.itemSet,i=this.usedSet;t.has(e)&&!i.has(e)&&(t.set(e,Date.now()),i.add(e))}markUnused(e){this.usedSet.delete(e)}markAllUnused(){this.usedSet.clear()}unloadUnusedContent(){const{unloadPercent:e,minSize:t,maxSize:i,itemList:r,itemSet:a,usedSet:s,loadedSet:o,callbacks:l,bytesMap:u,minBytesSize:d,maxBytesSize:f}=this,p=r.length-s.size,m=r.length-o.size,v=Math.max(Math.min(r.length-t,p),0),x=this.cachedBytes-d,S=this.unloadPriorityCallback||this.defaultPriorityCallback;let _=!1;const T=v>0&&p>0||m&&r.length>i;if(p&&this.cachedBytes>d||m&&this.cachedBytes>f||T){r.sort((N,C)=>{const z=s.has(N),W=s.has(C);if(z===W){const K=o.has(N),oe=o.has(C);return K===oe?-S(N,C):K?1:-1}else return z?1:-1});const E=Math.max(t*e,v*e),b=Math.ceil(Math.min(E,p,v)),R=Math.max(e*x,e*d),w=Math.min(R,x);let L=0,U=0;for(;this.cachedBytes-U>f||r.length-L>i;){const N=r[L],C=u.get(N)||0;if(s.has(N)&&o.has(N)||this.cachedBytes-U-C=b)break;U+=C,L++}r.splice(0,L).forEach(N=>{this.cachedBytes-=u.get(N)||0,l.get(N)(N),u.delete(N),a.delete(N),l.delete(N),o.delete(N),s.delete(N)}),_=L0}_&&(this.unloadingHandle=requestAnimationFrame(()=>this.scheduleUnload()))}scheduleUnload(){cancelAnimationFrame(this.unloadingHandle),this.scheduled||(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1,this.unloadUnusedContent()}))}}let fM=class{get running(){return this.items.length!==0||this.currJobs!==0}constructor(){this.maxJobs=6,this.items=[],this.callbacks=new Map,this.currJobs=0,this.scheduled=!1,this.autoUpdate=!0,this.priorityCallback=null,this.schedulingCallback=e=>{requestAnimationFrame(e)},this._runjobs=()=>{this.scheduled=!1,this.tryRunJobs()}}sort(){const e=this.priorityCallback,t=this.items;e!==null&&t.sort(e)}has(e){return this.callbacks.has(e)}add(e,t){const i={callback:t,reject:null,resolve:null,promise:null};return i.promise=new Promise((r,a)=>{const s=this.items,o=this.callbacks;i.resolve=r,i.reject=a,s.unshift(e),o.set(e,i),this.autoUpdate&&this.scheduleJobRun()}),i.promise}remove(e){const t=this.items,i=this.callbacks,r=t.indexOf(e);if(r!==-1){const a=i.get(e);a.promise.catch(()=>{}),a.reject(new Error("PriorityQueue: Item removed.")),t.splice(r,1),i.delete(e)}}removeByFilter(e){const{items:t}=this;for(let i=0;i{this.currJobs--,this.autoUpdate&&this.scheduleJobRun()};for(;i>this.currJobs&&e.length>0&&r0;){const r=i.pop(),a=i.pop(),s=i.pop();if(e&&e(s,a,r)){t&&t(s,a,r);return}const o=s.children;if(o)for(let l=o.length-1;l>=0;l--)i.push(o[l]),i.push(s),i.push(r+1);t&&t(s,a,r)}}function Bp(n){if(n===null||n.byteLength<4)return"";let e;if(n instanceof DataView?e=n:e=new DataView(n),String.fromCharCode(e.getUint8(0))==="{")return null;let t="";for(let i=0;i<4;i++)t+=String.fromCharCode(e.getUint8(i));return t}const xce=new TextDecoder;function uF(n){return xce.decode(n)}function sC(n){return n.replace(/[\\/][^\\/]+$/,"")+"/"}let MT=class{constructor(){this.fetchOptions={},this.workingPath=""}load(...e){return console.warn('Loader: "load" function has been deprecated in favor of "loadAsync".'),this.loadAsync(...e)}loadAsync(e){return fetch(e,this.fetchOptions).then(t=>{if(!t.ok)throw new Error(`Failed to load file "${e}" with status ${t.status} : ${t.statusText}`);return t.arrayBuffer()}).then(t=>(this.workingPath===""&&(this.workingPath=sC(e)),this.parse(t)))}resolveExternalURL(e){return new URL(e,this.workingPath).href}parse(e){throw new Error("LoaderBase: Parse not implemented.")}};function D5(n){if(!n)return null;let e=n.length;const t=n.indexOf("?"),i=n.indexOf("#");t!==-1&&(e=Math.min(e,t)),i!==-1&&(e=Math.min(e,i));const r=n.lastIndexOf(".",e),a=n.lastIndexOf("/",e),s=n.indexOf("://");return s!==-1&&s+2===a||r===-1||r0&&n.__depth+1>=e.maxDepth||!oC(n))}function pF(n,e){if(e.ensureChildrenArePreprocessed(n),cC(n,e),!n.__inFrustum)return;if(!yce(n,e)){GA(n,e);return}let t=!1,i=!1;const r=n.children;for(let a=0,s=r.length;as.setTileActive&&s.setTileActive(n,i)),n.__wasSetVisible!==r&&e.invokeOnePlugin(s=>s.setTileVisible&&s.setTileVisible(n,r))),n.__wasSetActive=i,n.__wasSetVisible=r,n.__usedLastFrame=t;const a=n.children;for(let s=0,o=a.length;s{e===null&&(e=requestAnimationFrame(()=>{e=null,n()}))}}const N5=Symbol("PLUGIN_REGISTERED"),O5=(n,e)=>{const t=n.priority||0,i=e.priority||0;return t!==i?t>i?1:-1:n.__used!==e.__used?n.__used?1:-1:n.__error!==e.__error?n.__error>e.__error?1:-1:n.__distanceFromCamera!==e.__distanceFromCamera?n.__distanceFromCamera>e.__distanceFromCamera?-1:1:n.__depthFromRenderedParent!==e.__depthFromRenderedParent?n.__depthFromRenderedParent>e.__depthFromRenderedParent?-1:1:0},Tce=(n,e)=>{const t=n.priority||0,i=e.priority||0;return t!==i?t>i?1:-1:n.__lastFrameVisited!==e.__lastFrameVisited?n.__lastFrameVisited>e.__lastFrameVisited?-1:1:n.__depthFromRenderedParent!==e.__depthFromRenderedParent?n.__depthFromRenderedParent>e.__depthFromRenderedParent?1:-1:n.__loadingState!==e.__loadingState?n.__loadingState>e.__loadingState?-1:1:n.__hasUnrenderableContent!==e.__hasUnrenderableContent?n.__hasUnrenderableContent?-1:1:n.__error!==e.__error?n.__error>e.__error?-1:1:0};let Ece=class{get root(){const e=this.rootTileSet;return e?e.root:null}get loadProgress(){const{stats:e,isLoading:t}=this,i=e.downloading+e.parsing,r=e.inCacheSinceLoad+(t?1:0);return r===0?1:1-i/r}get errorThreshold(){return this._errorThreshold}set errorThreshold(e){console.warn('TilesRenderer: The "errorThreshold" option has been deprecated.'),this._errorThreshold=e}constructor(e=null){this.rootLoadingState=gc,this.rootTileSet=null,this.rootURL=e,this.fetchOptions={},this.plugins=[],this.queuedTiles=[],this.cachedSinceLoadComplete=new Set,this.isLoading=!1;const t=new vce;t.unloadPriorityCallback=Tce;const i=new fM;i.maxJobs=25,i.priorityCallback=O5;const r=new fM;r.maxJobs=5,r.priorityCallback=O5;const a=new fM;a.maxJobs=25,this.processedTiles=new WeakSet,this.visibleTiles=new Set,this.activeTiles=new Set,this.usedSet=new Set,this.lruCache=t,this.downloadQueue=i,this.parseQueue=r,this.processNodeQueue=a,this.stats={inCacheSinceLoad:0,inCache:0,parsing:0,downloading:0,failed:0,inFrustum:0,used:0,active:0,visible:0},this.frameCount=0,this._dispatchNeedsUpdateEvent=Sce(()=>{this.dispatchEvent({type:"needs-update"})}),this.errorTarget=16,this._errorThreshold=1/0,this.displayActiveTiles=!1,this.maxDepth=1/0}registerPlugin(e){if(e[N5]===!0)throw new Error("TilesRendererBase: A plugin can only be registered to a single tile set");const t=this.plugins,i=e.priority||0;let r=t.length;for(let a=0;ai){r=a;break}t.splice(r,0,e),e[N5]=!0,e.init&&e.init(this)}unregisterPlugin(e){const t=this.plugins;if(typeof e=="string"&&(e=this.getPluginByName(e)),t.includes(e)){const i=t.indexOf(e);return t.splice(i,1),e.dispose&&e.dispose(),!0}return!1}getPluginByName(e){return this.plugins.find(t=>t.name===e)||null}traverse(e,t,i=!0){this.root&&cF(this.root,(r,...a)=>(i&&this.ensureChildrenArePreprocessed(r,!0),e?e(r,...a):!1),t)}queueTileForDownload(e){e.__loadingState!==gc||this.lruCache.isFull()||this.queuedTiles.push(e)}markTileUsed(e){this.usedSet.add(e),this.lruCache.markUsed(e)}update(){const{lruCache:e,usedSet:t,stats:i,root:r,downloadQueue:a,parseQueue:s,processNodeQueue:o}=this;if(this.rootLoadingState===gc&&(this.rootLoadingState=Ax,this.invokeOnePlugin(u=>u.loadRootTileSet&&u.loadRootTileSet()).then(u=>{let d=this.rootURL;d!==null&&this.invokeAllPlugins(f=>d=f.preprocessURL?f.preprocessURL(d,null):d),this.rootLoadingState=Bg,this.rootTileSet=u,this.dispatchEvent({type:"needs-update"}),this.dispatchEvent({type:"load-content"}),this.dispatchEvent({type:"load-tile-set",tileSet:u,url:d})}).catch(u=>{this.rootLoadingState=Yf,console.error(u),this.rootTileSet=null,this.dispatchEvent({type:"load-error",tile:null,error:u,url:this.rootURL})})),!r)return;i.inFrustum=0,i.used=0,i.active=0,i.visible=0,this.frameCount++,t.forEach(u=>e.markUnused(u)),t.clear(),pF(r,this),mF(r,this),gF(r,this),vF(r,this);const l=this.queuedTiles;l.sort(e.unloadPriorityCallback);for(let u=0,d=l.length;u{t.__loadingState===Yf&&(t.__loadingState=gc)},null,!1),e.failed=0)}dispose(){[...this.plugins].forEach(i=>{this.unregisterPlugin(i)});const e=this.lruCache,t=[];this.traverse(i=>(t.push(i),!1),null,!1);for(let i=0,r=t.length;it.setTileVisible&&t.setTileVisible(e,!1)),e.__visible=!1),e.__active&&(this.invokeOnePlugin(t=>t.setTileActive&&t.setTileActive(e,!1)),e.__active=!1)}preprocessNode(e,t,i=null){var r;if(this.processedTiles.add(e),e.content&&(!("uri"in e.content)&&"url"in e.content&&(e.content.uri=e.content.url,delete e.content.url),e.content.boundingVolume&&!("box"in e.content.boundingVolume||"sphere"in e.content.boundingVolume||"region"in e.content.boundingVolume)&&delete e.content.boundingVolume),e.parent=i,e.children=e.children||[],(r=e.content)!=null&&r.uri){const a=D5(e.content.uri);e.__hasContent=!0,e.__hasUnrenderableContent=!!(a&&/json$/.test(a)),e.__hasRenderableContent=!e.__hasUnrenderableContent}else e.__hasContent=!1,e.__hasUnrenderableContent=!1,e.__hasRenderableContent=!1;e.__childrenProcessed=0,i&&i.__childrenProcessed++,e.__distanceFromCamera=1/0,e.__error=1/0,e.__inFrustum=!1,e.__isLeaf=!1,e.__usedLastFrame=!1,e.__used=!1,e.__wasSetVisible=!1,e.__visible=!1,e.__allChildrenReady=!1,e.__wasSetActive=!1,e.__active=!1,e.__loadingState=gc,i===null?(e.__depth=0,e.__depthFromRenderedParent=e.__hasRenderableContent?1:0,e.refine=e.refine||"REPLACE"):(e.__depth=i.__depth+1,e.__depthFromRenderedParent=i.__depthFromRenderedParent+(e.__hasRenderableContent?1:0),e.refine=e.refine||i.refine),e.__basePath=t,e.__lastFrameVisited=-1,this.invokeAllPlugins(a=>{a!==this&&a.preprocessNode&&a.preprocessNode(e,t,i)})}setTileActive(e,t){t?this.activeTiles.add(e):this.activeTiles.delete(e)}setTileVisible(e,t){t?this.visibleTiles.add(e):this.visibleTiles.delete(e)}calculateTileViewError(e,t){}ensureChildrenArePreprocessed(e,t=!1){const i=e.children;for(let r=0,a=i.length;r{this.preprocessNode(o,e.__basePath,e),this._dispatchNeedsUpdateEvent()})}}getBytesUsed(e){let t=0;return this.invokeAllPlugins(i=>{i.calculateBytesUsed&&(t+=i.calculateBytesUsed(e,e.cached.scene)||0)}),t}recalculateBytesUsed(e=null){const{lruCache:t,processedTiles:i}=this;e===null?t.itemSet.forEach(r=>{i.has(r)&&t.setMemoryUsage(r,this.getBytesUsed(r))}):t.setMemoryUsage(e,this.getBytesUsed(e))}preprocessTileSet(e,t,i=null){const r=e.asset.version,[a,s]=r.split(".").map(l=>parseInt(l));console.assert(a<=1,"TilesRenderer: asset.version is expected to be a 1.x or a compatible version."),a===1&&s>0&&console.warn("TilesRenderer: tiles versions at 1.1 or higher have limited support. Some new extensions and features may not be supported.");let o=t.replace(/\/[^/]*$/,"");o=new URL(o,window.location.href).toString(),this.preprocessNode(e.root,o,i)}loadRootTileSet(){let e=this.rootURL;return this.invokeAllPlugins(t=>e=t.preprocessURL?t.preprocessURL(e,null):e),this.invokeOnePlugin(t=>t.fetchData&&t.fetchData(e,this.fetchOptions)).then(t=>{if(t instanceof Response){if(t.ok)return t.json();throw new Error(`TilesRenderer: Failed to load tileset "${e}" with status ${t.status} : ${t.statusText}`)}else return t}).then(t=>(this.preprocessTileSet(t,e),t))}requestTileContents(e){if(e.__loadingState!==gc)return;let t=!1,i=null,r=new URL(e.content.uri,e.__basePath+"/").toString();this.invokeAllPlugins(p=>r=p.preprocessURL?p.preprocessURL(r,e):r);const a=this.stats,s=this.lruCache,o=this.downloadQueue,l=this.parseQueue,u=D5(r),d=new AbortController,f=d.signal;if(s.add(e,p=>{d.abort(),t?(p.children.length=0,p.__childrenProcessed=0):this.invokeAllPlugins(m=>{m.disposeTile&&m.disposeTile(p)}),a.inCache--,this.cachedSinceLoadComplete.has(e)&&(this.cachedSinceLoadComplete.delete(e),a.inCacheSinceLoad--),p.__loadingState===Ax?a.downloading--:p.__loadingState===pM&&a.parsing--,p.__loadingState=gc,l.remove(p),o.remove(p)}))return this.isLoading||(this.isLoading=!0,this.dispatchEvent({type:"tiles-load-start"})),s.setMemoryUsage(e,this.getBytesUsed(e)),this.cachedSinceLoadComplete.add(e),a.inCacheSinceLoad++,a.inCache++,a.downloading++,e.__loadingState=Ax,o.add(e,p=>{if(f.aborted)return Promise.resolve();const m=this.invokeOnePlugin(v=>v.fetchData&&v.fetchData(r,{...this.fetchOptions,signal:f}));return this.dispatchEvent({type:"tile-download-start",tile:e}),m}).then(p=>{if(!f.aborted)if(p instanceof Response){if(p.ok)return u==="json"?p.json():p.arrayBuffer();throw new Error(`Failed to load model with error code ${p.status}`)}else return p}).then(p=>{if(!f.aborted)return a.downloading--,a.parsing++,e.__loadingState=pM,l.add(e,m=>f.aborted?Promise.resolve():u==="json"&&p.root?(this.preprocessTileSet(p,r,e),e.children.push(p.root),i=p,t=!0,Promise.resolve()):this.invokeOnePlugin(v=>v.parseTile&&v.parseTile(p,m,u,r,f)))}).then(()=>{if(f.aborted)return;a.parsing--,e.__loadingState=Bg,s.setLoaded(e,!0);const p=this.getBytesUsed(e);if(s.getMemoryUsage(e)===0&&p>0&&s.isFull()){s.remove(e);return}s.setMemoryUsage(e,p),this.dispatchEvent({type:"needs-update"}),this.dispatchEvent({type:"load-content"}),t&&this.dispatchEvent({type:"load-tile-set",tileSet:i,url:r}),e.cached.scene&&this.dispatchEvent({type:"load-model",scene:e.cached.scene,tile:e})}).catch(p=>{f.aborted||(p.name!=="AbortError"?(l.remove(e),o.remove(e),e.__loadingState===pM?a.parsing--:e.__loadingState===Ax&&a.downloading--,a.failed++,console.error(`TilesRenderer : Failed to load tile at url "${e.content.uri}".`),console.error(p),e.__loadingState=Yf,s.setLoaded(e,!0),this.dispatchEvent({type:"load-error",tile:e,error:p,url:r})):s.remove(e))})}getAttributions(e=[]){return this.invokeAllPlugins(t=>t!==this&&t.getAttributions&&t.getAttributions(e)),e}invokeOnePlugin(e){const t=[...this.plugins,this];for(let i=0;ie!=="extensions")}getData(e,t,i=null,r=null){const a=this.header;if(!(e in a))return null;const s=a[e];if(s instanceof Object){if(Array.isArray(s))return s;{const{buffer:o,binOffset:l,binLength:u}=this,d=s.byteOffset||0,f=s.type||r,p=s.componentType||i;if("type"in s&&r&&s.type!==r)throw new Error("FeatureTable: Specified type does not match expected type.");const m=l+d,v=_F(o,m,t,f,p,e);if(m+v.byteLength>l+u)throw new Error("FeatureTable: Feature data read outside binary body length.");return v}}else return s}getBuffer(e,t){const{buffer:i,binOffset:r}=this;return i.slice(r+e,r+e+t)}},bce=class{constructor(e){this.batchTable=e;const t=e.header.extensions["3DTILES_batch_table_hierarchy"];this.classes=t.classes;for(const r of this.classes){const a=r.instances;for(const s in a)r.instances[s]=this._parseProperty(a[s],r.length,s)}if(this.instancesLength=t.instancesLength,this.classIds=this._parseProperty(t.classIds,this.instancesLength,"classIds"),t.parentCounts?this.parentCounts=this._parseProperty(t.parentCounts,this.instancesLength,"parentCounts"):this.parentCounts=new Array(this.instancesLength).fill(1),t.parentIds){const r=this.parentCounts.reduce((a,s)=>a+s,0);this.parentIds=this._parseProperty(t.parentIds,r,"parentIds")}else this.parentIds=null;this.instancesIds=[];const i={};for(const r of this.classIds)i[r]=i[r]??0,this.instancesIds.push(i[r]),i[r]++}_parseProperty(e,t,i){if(Array.isArray(e))return e;{const{buffer:r,binOffset:a}=this.batchTable,s=e.byteOffset,o=e.componentType||"UNSIGNED_SHORT",l=a+s;return _F(r,l,t,"SCALAR",o,i)}}getDataFromId(e,t={}){const i=this.parentCounts[e];if(this.parentIds&&i>0){let l=0;for(let u=0;u=this.count)throw new Error(`BatchTable: id value "${e}" out of bounds for "${this.count}" features number.`);for(const i of this.getKeys())t[i]=super.getData(i,this.count)[e];for(const i in this.extensions){const r=this.extensions[i];r.getDataFromId instanceof Function&&(t[i]=t[i]||{},r.getDataFromId(e,t[i]))}return t}getPropertyArray(e){return super.getData(e,this.count)}},Mce=class extends MT{parse(e){const t=new DataView(e),i=Bp(t);console.assert(i==="b3dm");const r=t.getUint32(4,!0);console.assert(r===1);const a=t.getUint32(8,!0);console.assert(a===e.byteLength);const s=t.getUint32(12,!0),o=t.getUint32(16,!0),l=t.getUint32(20,!0),u=t.getUint32(24,!0),d=28,f=e.slice(d,d+s+o),p=new AT(f,0,s,o),m=d+s+o,v=e.slice(m,m+l+u),x=new uC(v,p.getData("BATCH_LENGTH"),0,l,u),S=m+l+u,_=new Uint8Array(e,S,a-S);return{version:r,featureTable:p,batchTable:x,glbBytes:_}}},Ace=class extends MT{parse(e){const t=new DataView(e),i=Bp(t);console.assert(i==="i3dm");const r=t.getUint32(4,!0);console.assert(r===1);const a=t.getUint32(8,!0);console.assert(a===e.byteLength);const s=t.getUint32(12,!0),o=t.getUint32(16,!0),l=t.getUint32(20,!0),u=t.getUint32(24,!0),d=t.getUint32(28,!0),f=32,p=e.slice(f,f+s+o),m=new AT(p,0,s,o),v=f+s+o,x=e.slice(v,v+l+u),S=new uC(x,m.getData("INSTANCES_LENGTH"),0,l,u),_=v+l+u,T=new Uint8Array(e,_,a-_);let E=null,b=null,R=null;if(d)E=T,b=Promise.resolve();else{const w=this.resolveExternalURL(uF(T));R=sC(w),b=fetch(w,this.fetchOptions).then(L=>{if(!L.ok)throw new Error(`I3DMLoaderBase : Failed to load file "${w}" with status ${L.status} : ${L.statusText}`);return L.arrayBuffer()}).then(L=>{E=new Uint8Array(L)})}return b.then(()=>({version:r,featureTable:m,batchTable:S,glbBytes:E,gltfWorkingPath:R}))}},wce=class extends MT{parse(e){const t=new DataView(e),i=Bp(t);console.assert(i==="pnts");const r=t.getUint32(4,!0);console.assert(r===1);const a=t.getUint32(8,!0);console.assert(a===e.byteLength);const s=t.getUint32(12,!0),o=t.getUint32(16,!0),l=t.getUint32(20,!0),u=t.getUint32(24,!0),d=28,f=e.slice(d,d+s+o),p=new AT(f,0,s,o),m=d+s+o,v=e.slice(m,m+l+u),x=new uC(v,p.getData("BATCH_LENGTH")||p.getData("POINTS_LENGTH"),0,l,u);return Promise.resolve({version:r,featureTable:p,batchTable:x})}},Rce=class extends MT{parse(e){const t=new DataView(e),i=Bp(t);console.assert(i==="cmpt",'CMPTLoader: The magic bytes equal "cmpt".');const r=t.getUint32(4,!0);console.assert(r===1,'CMPTLoader: The version listed in the header is "1".');const a=t.getUint32(8,!0);console.assert(a===e.byteLength,"CMPTLoader: The contents buffer length listed in the header matches the file.");const s=t.getUint32(12,!0),o=[];let l=16;for(let u=0;uNce);return t.set(e.x*T,e.y*E,e.z*b)}calculateHorizonDistance(e,t){const i=this.calculateEffectiveRadius(e);return Math.sqrt(2*i*t+t**2)}calculateEffectiveRadius(e){const t=this.radius.x,i=1-this.radius.z**2/t**2,r=e*lt.DEG2RAD,a=Math.sin(r)**2;return t/Math.sqrt(1-i*a)}getPositionElevation(e){this.getPositionToSurfacePoint(e,aa);const t=mM.subVectors(e,aa);return Math.sign(t.dot(e))*t.length()}closestPointToRayEstimate(e,t){return this.intersectRay(e,t)?t:(hs.makeScale(...this.radius).invert(),Rx.copy(e).applyMatrix4(hs),aa.set(0,0,0),Rx.closestPointToPoint(aa,t).normalize(),hs.makeScale(...this.radius),t.applyMatrix4(hs))}copy(e){return this.radius.copy(e.radius),this}clone(){return new this.constructor().copy(this)}};const Fp=new wT(C5,C5,_ce);Fp.name="WGS84 Earth";const Dx=new D,Nx=new D,oa=new D,Ox=new Pr;let F5=class{constructor(e=new Qi,t=new Me){this.box=e.clone(),this.transform=t.clone(),this.inverseTransform=new Me,this.points=new Array(8).fill().map(()=>new D),this.planes=new Array(6).fill().map(()=>new xs)}copy(e){return this.box.copy(e.box),this.transform.copy(e.transform),this.update(),this}clone(){return new this.constructor().copy(this)}clampPoint(e,t){return t.copy(e).applyMatrix4(this.inverseTransform).clamp(this.box.min,this.box.max).applyMatrix4(this.transform)}distanceToPoint(e){return this.clampPoint(e,oa).distanceTo(e)}containsPoint(e){return oa.copy(e).applyMatrix4(this.inverseTransform),this.box.containsPoint(oa)}intersectsRay(e){return Ox.copy(e).applyMatrix4(this.inverseTransform),Ox.intersectsBox(this.box)}intersectRay(e,t){return Ox.copy(e).applyMatrix4(this.inverseTransform),Ox.intersectBox(this.box,t)?(t.applyMatrix4(this.transform),t):null}update(){const{points:e,inverseTransform:t,transform:i,box:r}=this;t.copy(i).invert();const{min:a,max:s}=r;let o=0;for(let l=-1;l<=1;l+=2)for(let u=-1;u<=1;u+=2)for(let d=-1;d<=1;d+=2)e[o].set(l<0?a.x:s.x,u<0?a.y:s.y,d<0?a.z:s.z).applyMatrix4(i),o++;this.updatePlanes()}updatePlanes(){Dx.copy(this.box.min).applyMatrix4(this.transform),Nx.copy(this.box.max).applyMatrix4(this.transform),oa.set(0,0,1).transformDirection(this.transform),this.planes[0].setFromNormalAndCoplanarPoint(oa,Dx),this.planes[1].setFromNormalAndCoplanarPoint(oa,Nx).negate(),oa.set(0,1,0).transformDirection(this.transform),this.planes[2].setFromNormalAndCoplanarPoint(oa,Dx),this.planes[3].setFromNormalAndCoplanarPoint(oa,Nx).negate(),oa.set(1,0,0).transformDirection(this.transform),this.planes[4].setFromNormalAndCoplanarPoint(oa,Dx),this.planes[5].setFromNormalAndCoplanarPoint(oa,Nx).negate()}intersectsSphere(e){return this.clampPoint(e.center,oa),oa.distanceToSquared(e.center)<=e.radius*e.radius}intersectsFrustum(e){return this._intersectsPlaneShape(e.planes,e.points)}intersectsOBB(e){return this._intersectsPlaneShape(e.planes,e.points)}_intersectsPlaneShape(e,t){const i=this.points,r=this.planes;for(let a=0;a<6;a++){const s=e[a];let o=-1/0;for(let l=0;l<8;l++){const u=i[l],d=s.distanceToPoint(u);o=o=t&&T<=i&&E>=r&&E<=a){const b=Lce(e);p.push(b),this.getCartographicToPosition(T,E,x,b)}}}return p}getBoundingBox(e,t){V5();const{latStart:i,latEnd:r,lonStart:a,lonEnd:s}=this;if(r-i{if(i.geometry&&!e.has(i.geometry)&&(t+=dee(i.geometry),e.add(i.geometry)),i.material){const r=i.material;for(const a in r){const s=r[a];s&&s.isTexture&&!e.has(s)&&(t+=Uce(s),e.add(s))}}}),t}let xF=class extends Mce{constructor(e=Kp){super(),this.manager=e,this.adjustmentTransform=new Me}parse(e){const t=super.parse(e),i=t.glbBytes.slice().buffer;return new Promise((r,a)=>{const s=this.manager,o=this.fetchOptions,l=s.getHandler("path.gltf")||new Lp(s);o.credentials==="include"&&o.mode==="cors"&&l.setCrossOrigin("use-credentials"),"credentials"in o&&l.setWithCredentials(o.credentials==="include"),o.headers&&l.setRequestHeader(o.headers);let u=this.workingPath;!/[\\/]$/.test(u)&&u.length&&(u+="/");const d=this.adjustmentTransform;l.parse(i,u,f=>{const{batchTable:p,featureTable:m}=t,{scene:v}=f,x=m.getData("RTC_CENTER",1,"FLOAT","VEC3");x&&(v.position.x+=x[0],v.position.y+=x[1],v.position.z+=x[2]),f.scene.updateMatrix(),f.scene.matrix.multiply(d),f.scene.matrix.decompose(f.scene.position,f.scene.quaternion,f.scene.scale),f.batchTable=p,f.featureTable=m,v.batchTable=p,v.featureTable=m,r(f)},a)})}};function zce(n){const e=n>>11,t=n>>5&63,i=n&31,r=Math.round(e/31*255),a=Math.round(t/63*255),s=Math.round(i/31*255);return[r,a,s]}const u0=new re;function Bce(n,e,t=new D){u0.set(n,e).divideScalar(256).multiplyScalar(2).subScalar(1),t.set(u0.x,u0.y,1-Math.abs(u0.x)-Math.abs(u0.y));const i=lt.clamp(-t.z,0,1);return t.x>=0?t.setX(t.x-i):t.setX(t.x+i),t.y>=0?t.setY(t.y-i):t.setY(t.y+i),t.normalize(),t}const G5={RGB:"color",POSITION:"position"};let yF=class extends wce{constructor(e=Kp){super(),this.manager=e}parse(e){return super.parse(e).then(async t=>{const{featureTable:i,batchTable:r}=t,a=new nv,s=i.header.extensions,o=new D;let l;if(s&&s["3DTILES_draco_point_compression"]){const{byteOffset:f,byteLength:p,properties:m}=s["3DTILES_draco_point_compression"],v=this.manager.getHandler("draco.drc");if(v==null)throw new Error("PNTSLoader: dracoLoader not available.");const x={};for(const T in m)if(T in G5&&T in m){const E=G5[T];x[E]=m[T]}const S={attributeIDs:x,attributeTypes:{position:"Float32Array",color:"Uint8Array"},useUniqueIDs:!0},_=i.getBuffer(f,p);l=await v.decodeGeometry(_,S),l.attributes.color&&(a.vertexColors=!0)}else{const f=i.getData("POINTS_LENGTH"),p=i.getData("POSITION",f,"FLOAT","VEC3"),m=i.getData("NORMAL",f,"FLOAT","VEC3"),v=i.getData("NORMAL",f,"UNSIGNED_BYTE","VEC2"),x=i.getData("RGB",f,"UNSIGNED_BYTE","VEC3"),S=i.getData("RGBA",f,"UNSIGNED_BYTE","VEC4"),_=i.getData("RGB565",f,"UNSIGNED_SHORT","SCALAR"),T=i.getData("CONSTANT_RGBA",f,"UNSIGNED_BYTE","VEC4"),E=i.getData("POSITION_QUANTIZED",f,"UNSIGNED_SHORT","VEC3"),b=i.getData("QUANTIZED_VOLUME_SCALE",f,"FLOAT","VEC3"),R=i.getData("QUANTIZED_VOLUME_OFFSET",f,"FLOAT","VEC3");if(l=new Ct,E){const w=new Float32Array(f*3);for(let L=0;L{const{featureTable:i,batchTable:r}=t,a=t.glbBytes.slice().buffer;return new Promise((s,o)=>{const l=this.fetchOptions,u=this.manager,d=u.getHandler("path.gltf")||new Lp(u);l.credentials==="include"&&l.mode==="cors"&&d.setCrossOrigin("use-credentials"),"credentials"in l&&d.setWithCredentials(l.credentials==="include"),l.headers&&d.setRequestHeader(l.headers);let f=t.gltfWorkingPath??this.workingPath;/[\\/]$/.test(f)||(f+="/");const p=this.adjustmentTransform;d.parse(a,f,m=>{const v=i.getData("INSTANCES_LENGTH");let x=i.getData("POSITION",v,"FLOAT","VEC3");const S=i.getData("POSITION_QUANTIZED",v,"UNSIGNED_SHORT","VEC3"),_=i.getData("QUANTIZED_VOLUME_OFFSET",1,"FLOAT","VEC3"),T=i.getData("QUANTIZED_VOLUME_SCALE",1,"FLOAT","VEC3"),E=i.getData("NORMAL_UP",v,"FLOAT","VEC3"),b=i.getData("NORMAL_RIGHT",v,"FLOAT","VEC3"),R=i.getData("SCALE_NON_UNIFORM",v,"FLOAT","VEC3"),w=i.getData("SCALE",v,"FLOAT","SCALAR"),L=i.getData("RTC_CENTER",1,"FLOAT","VEC3"),U=i.getData("EAST_NORTH_UP");if(["NORMAL_UP_OCT32P","NORMAL_RIGHT_OCT32P"].forEach(W=>{W in i.header&&console.warn(`I3DMLoader: Unsupported FeatureTable feature "${W}" detected.`)}),!x&&S){x=new Float32Array(v*3);for(let W=0;W{if(W.isMesh){z.push(W);const{geometry:K,material:oe}=W,ae=new VS(K,oe,v);ae.position.copy(N),L&&(ae.position.x+=L[0],ae.position.y+=L[1],ae.position.z+=L[2]),C.push(ae)}});for(let W=0;W{const l=new Xi;return o.forEach(u=>{l.add(u.scene)}),{tiles:o,scene:l}})}}const h0=new Me;class Hce extends Xi{constructor(e){super(),this.isTilesGroup=!0,this.name="TilesRenderer.TilesGroup",this.tilesRenderer=e,this.matrixWorldInverse=new Me}raycast(e,t){return this.tilesRenderer.optimizeRaycast?(this.tilesRenderer.raycast(e,t),!1):!0}updateMatrixWorld(e){if(this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldNeedsUpdate||e){this.parent===null?h0.copy(this.matrix):h0.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1;const t=h0.elements,i=this.matrixWorld.elements;let r=!1;for(let a=0;a<16;a++){const s=t[a],o=i[a];if(Math.abs(s-o)>Number.EPSILON){r=!0;break}}if(r){this.matrixWorld.copy(h0),this.matrixWorldInverse.copy(h0).invert();const a=this.children;for(let s=0,o=a.length;sa.raycastTile&&a.raycastTile(n,r,e,i))||e.intersectObject(r,!0,i)}function Vce(n,e,t){bF(n,e,t,Px),Px.sort(EF);const i=Px[0]||null;return Px.length=0,i}function MF(n){return"__used"in n}function AF(n,e,t,i=null){const{group:r,activeTiles:a}=n;i===null&&(i=TF,i.copy(t.ray).applyMatrix4(r.matrixWorldInverse));const s=[],o=e.children;for(let d=0,f=o.length;du)break;const x=AF(n,v,t,i);if(x){const S=x.distance*x.distance;Sa?r:a}intersectsFrustum(e){const t=this.obb||this.regionObb,i=this.sphere;return i&&!e.intersectsSphere(i)||t&&!t.intersectsFrustum(e)?!1:!!(i||t)}intersectsSphere(e){const t=this.obb||this.regionObb,i=this.sphere;return i&&!i.intersectsSphere(e)||t&&!t.intersectsSphere(e)?!1:!!(i||t)}intersectsOBB(e){const t=this.obb||this.regionObb,i=this.sphere;return i&&!e.intersectsSphere(i)||t&&!t.intersectsOBB(e)?!1:!!(i||t)}getOBB(e,t){const i=this.obb||this.regionObb;i?(e.copy(i.box),t.copy(i.transform)):(this.getAABB(e),t.identity())}getAABB(e){if(this.sphere)this.sphere.getBoundingBox(e);else{const t=this.obb||this.regionObb;e.copy(t.box).applyMatrix4(t.transform)}}getSphere(e){if(this.sphere)e.copy(this.sphere);else if(this.region)this.region.getBoundingSphere(e);else{const t=this.obb||this.regionObb;t.box.getBoundingSphere(e),e.applyMatrix4(t.transform)}}setObbData(e,t){const i=new F5;ll.set(e[3],e[4],e[5]),cl.set(e[6],e[7],e[8]),ul.set(e[9],e[10],e[11]);const r=ll.length(),a=cl.length(),s=ul.length();ll.normalize(),cl.normalize(),ul.normalize(),r===0&&ll.crossVectors(cl,ul),a===0&&cl.crossVectors(ll,ul),s===0&&ul.crossVectors(ll,cl),i.transform.set(ll.x,cl.x,ul.x,e[0],ll.y,cl.y,ul.y,e[1],ll.z,cl.z,ul.z,e[2],0,0,0,1).premultiply(t),i.box.min.set(-r,-a,-s),i.box.max.set(r,a,s),i.update(),this.obb=i}setSphereData(e,t,i,r,a){const s=new qi;s.center.set(e,t,i),s.radius=r,s.applyMatrix4(a),this.sphere=s}setRegionData(e,t,i,r,a,s,o){const l=new Ice(...e.radius,i,a,t,r,s,o),u=new F5;l.getBoundingBox(u.box,u.transform),u.update(),this.region=l,this.regionObb=u}}const kce=new Mt;function Wce(n,e,t,i){const r=kce.set(n.normal.x,n.normal.y,n.normal.z,e.normal.x,e.normal.y,e.normal.z,t.normal.x,t.normal.y,t.normal.z);return i.set(-n.constant,-e.constant,-t.constant),i.applyMatrix3(r.invert()),i}let Xce=class extends ed{constructor(){super(),this.points=Array(8).fill().map(()=>new D)}setFromProjectionMatrix(e,t){return super.setFromProjectionMatrix(e,t),this.calculateFrustumPoints(),this}calculateFrustumPoints(){const{planes:e,points:t}=this;[[e[0],e[3],e[4]],[e[1],e[3],e[4]],[e[0],e[2],e[4]],[e[1],e[2],e[4]],[e[0],e[3],e[5]],[e[1],e[3],e[5]],[e[0],e[2],e[5]],[e[1],e[2],e[5]]].forEach((i,r)=>{Wce(i[0],i[1],i[2],t[r])})}};const Z5=new Me,Q5=new Ai,RF=Symbol("INITIAL_FRUSTUM_CULLED"),zx=new Me,d0=new D,MM=new re,xf={inView:!1,error:1/0},qce=new D(1,0,0),Yce=new D(0,1,0);function K5(n,e){n.traverse(t=>{t.frustumCulled=t[RF]&&e})}class jce extends Ece{get autoDisableRendererCulling(){return this._autoDisableRendererCulling}set autoDisableRendererCulling(e){this._autoDisableRendererCulling!==e&&(super._autoDisableRendererCulling=e,this.forEachLoadedModel(t=>{K5(t,!e)}))}get optimizeRaycast(){return this._optimizeRaycast}set optimizeRaycast(e){console.warn('TilesRenderer: The "optimizeRaycast" option has been deprecated.'),this._optimizeRaycast=e}constructor(...e){super(...e),this.group=new Hce(this),this.ellipsoid=Fp.clone(),this.cameras=[],this.cameraMap=new Map,this.cameraInfo=[],this._optimizeRaycast=!0,this._upRotationMatrix=new Me,this._bytesUsed=new WeakMap,this._autoDisableRendererCulling=!0,this.manager=new rT,this._listeners={}}addEventListener(...e){Mi.prototype.addEventListener.call(this,...e)}hasEventListener(...e){Mi.prototype.hasEventListener.call(this,...e)}removeEventListener(...e){Mi.prototype.removeEventListener.call(this,...e)}dispatchEvent(...e){Mi.prototype.dispatchEvent.call(this,...e)}getBoundingBox(e){if(!this.root)return!1;const t=this.root.cached.boundingVolume;return t?(t.getAABB(e),!0):!1}getOrientedBoundingBox(e,t){if(!this.root)return!1;const i=this.root.cached.boundingVolume;return i?(i.getOBB(e,t),!0):!1}getBoundingSphere(e){if(!this.root)return!1;const t=this.root.cached.boundingVolume;return t?(t.getSphere(e),!0):!1}forEachLoadedModel(e){this.traverse(t=>{const i=t.cached&&t.cached.scene;i&&e(i,t)},null,!1)}raycast(e,t){if(this.root)if(e.firstHitOnly){const i=AF(this,this.root,e);i&&t.push(i)}else wF(this,this.root,e,t)}hasCamera(e){return this.cameraMap.has(e)}setCamera(e){const t=this.cameras,i=this.cameraMap;return i.has(e)?!1:(i.set(e,new re),t.push(e),this.dispatchEvent({type:"add-camera",camera:e}),!0)}setResolution(e,t,i){const r=this.cameraMap;if(!r.has(e))return!1;const a=t.isVector2?t.x:t,s=t.isVector2?t.y:i,o=r.get(e);return(o.width!==a||o.height!==s)&&(o.set(a,s),this.dispatchEvent({type:"camera-resolution-change"})),!0}setResolutionFromRenderer(e,t){return t.getSize(MM),this.setResolution(e,MM.x,MM.y)}deleteCamera(e){const t=this.cameras,i=this.cameraMap;if(i.has(e)){const r=t.indexOf(e);return t.splice(r,1),i.delete(e),this.dispatchEvent({type:"delete-camera",camera:e}),!0}return!1}loadRootTileSet(...e){return super.loadRootTileSet(...e).then(t=>{const{asset:i,extensions:r={}}=t;switch((i&&i.gltfUpAxis||"y").toLowerCase()){case"x":this._upRotationMatrix.makeRotationAxis(Yce,-Math.PI/2);break;case"y":this._upRotationMatrix.makeRotationAxis(qce,Math.PI/2);break}if("3DTILES_ellipsoid"in r){const a=r["3DTILES_ellipsoid"],{ellipsoid:s}=this;s.name=a.body,a.radii?s.radius.set(...a.radii):s.radius.set(1,1,1)}return t})}update(){let e=null;if(this.invokeAllPlugins(s=>{if(s.doTilesNeedUpdate){const o=s.doTilesNeedUpdate();e===null?e=o:e=!!(e||o)}}),e===!1){this.dispatchEvent({type:"update-before"}),this.dispatchEvent({type:"update-after"});return}this.dispatchEvent({type:"update-before"});const t=this.group,i=this.cameras,r=this.cameraMap,a=this.cameraInfo;for(;a.length>i.length;)a.pop();for(;a.length1e-6&&console.warn("ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.");for(let s=0,o=a.length;ss=s||!!(o!==this&&o.calculateTileViewError)),s===!1&&console.warn("TilesRenderer: no cameras defined. Cannot update 3d tiles.")}}preprocessNode(e,t,i=null){super.preprocessNode(e,t,i);const r=new Me;if(e.transform){const o=e.transform;for(let l=0;l<16;l++)r.elements[l]=o[l]}i&&r.premultiply(i.cached.transform);const a=new Me().copy(r).invert(),s=new Gce;"sphere"in e.boundingVolume&&s.setSphereData(...e.boundingVolume.sphere,r),"box"in e.boundingVolume&&s.setObbData(e.boundingVolume.box,r),"region"in e.boundingVolume&&s.setRegionData(this.ellipsoid,...e.boundingVolume.region),e.cached={transform:r,transformInverse:a,active:!1,boundingVolume:s,metadata:null,scene:null,geometry:null,materials:null,textures:null}}async parseTile(e,t,i,r,a){const s=t.cached,o=sC(r),l=this.fetchOptions,u=this.manager;let d=null;const f=s.transform,p=this._upRotationMatrix,m=(Bp(e)||i).toLowerCase();switch(m){case"b3dm":{const b=new xF(u);b.workingPath=o,b.fetchOptions=l,b.adjustmentTransform.copy(p),d=b.parse(e);break}case"pnts":{const b=new yF(u);b.workingPath=o,b.fetchOptions=l,d=b.parse(e);break}case"i3dm":{const b=new SF(u);b.workingPath=o,b.fetchOptions=l,b.adjustmentTransform.copy(p),b.ellipsoid.copy(this.ellipsoid),d=b.parse(e);break}case"cmpt":{const b=new Fce(u);b.workingPath=o,b.fetchOptions=l,b.adjustmentTransform.copy(p),b.ellipsoid.copy(this.ellipsoid),d=b.parse(e).then(R=>R.scene);break}case"gltf":case"glb":{const b=u.getHandler("path.gltf")||u.getHandler("path.glb")||new Lp(u);b.setWithCredentials(l.credentials==="include"),b.setRequestHeader(l.headers||{}),l.credentials==="include"&&l.mode==="cors"&&b.setCrossOrigin("use-credentials");let R=b.resourcePath||b.path||o;!/[\\/]$/.test(R)&&R.length&&(R+="/"),d=b.parseAsync(e,R).then(w=>{w.scene=w.scene||new Xi;const{scene:L}=w;return L.updateMatrix(),L.matrix.multiply(p).decompose(L.position,L.quaternion,L.scale),w});break}default:{d=this.invokeOnePlugin(b=>b.parseToMesh&&b.parseToMesh(e,t,i,r,a));break}}const v=await d;if(v===null)throw new Error(`TilesRenderer: Content type "${m}" not supported.`);let x,S;v.isObject3D?(x=v,S=null):(x=v.scene,S=v),x.updateMatrix(),x.matrix.premultiply(f),x.matrix.decompose(x.position,x.quaternion,x.scale),await this.invokeAllPlugins(b=>b.processTileModel&&b.processTileModel(x,t)),x.traverse(b=>{b[RF]=b.frustumCulled}),K5(x,!this.autoDisableRendererCulling);const _=[],T=[],E=[];if(x.traverse(b=>{if(b.geometry&&T.push(b.geometry),b.material){const R=b.material;_.push(b.material);for(const w in R){const L=R[w];L&&L.isTexture&&E.push(L)}}}),a.aborted){for(let b=0,R=E.length;b{o.userData.meshFeatures&&o.userData.meshFeatures.dispose(),o.userData.structuralMetadata&&o.userData.structuralMetadata.dispose()});for(let o=0,l=r.length;o{p!==this&&p.calculateTileViewError&&p.calculateTileViewError(e,xf)&&(o=o&&xf.inView,d=Math.max(d,xf.error),xf.inView&&(l=Math.max(l,xf.error)))}),o?(t.inView=!0,t.error=l,t.distanceFromCamera=u):(t.inView=xf.inView,t.error=d,t.distanceFromCamera=f)}setLatLonToYUp(e,t){console.warn("TilesRenderer: setLatLonToYUp is deprecated. Use the ReorientationPlugin, instead.");const{ellipsoid:i,group:r}=this;Q5.set(Math.PI/2,Math.PI/2,0),Z5.makeRotationFromEuler(Q5),i.getEastNorthUpFrame(e,t,0,r.matrix).multiply(Z5).invert().decompose(r.position,r.quaternion,r.scale),r.updateMatrixWorld(!0)}dispose(){super.dispose(),this.group.removeFromParent()}}class Zce extends jn{constructor(){super(new uu(0,0),new Qce),this.renderOrder=1/0}onBeforeRender(e){const t=this.material.uniforms;e.getSize(t.resolution.value)}updateMatrixWorld(){this.matrixWorld.makeTranslation(this.position)}dispose(){this.geometry.dispose(),this.material.dispose()}}class Qce extends Oi{constructor(){super({depthWrite:!1,depthTest:!1,transparent:!0,uniforms:{resolution:{value:new re},size:{value:15},thickness:{value:2},opacity:{value:1}},vertexShader:` + + uniform float pixelRatio; + uniform float size; + uniform float thickness; + uniform vec2 resolution; + varying vec2 vUv; + + void main() { + + vUv = uv; + + float aspect = resolution.x / resolution.y; + vec2 offset = uv * 2.0 - vec2( 1.0 ); + offset.y *= aspect; + + vec4 screenPoint = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + screenPoint.xy += offset * ( size + thickness ) * screenPoint.w / resolution.x; + + gl_Position = screenPoint; + + } + `,fragmentShader:` + + uniform float size; + uniform float thickness; + uniform float opacity; + + varying vec2 vUv; + void main() { + + float ht = 0.5 * thickness; + float planeDim = size + thickness; + float offset = ( planeDim - ht - 2.0 ) / planeDim; + float texelThickness = ht / planeDim; + + vec2 vec = vUv * 2.0 - vec2( 1.0 ); + float dist = abs( length( vec ) - offset ); + float fw = fwidth( dist ) * 0.5; + float a = smoothstep( texelThickness - fw, texelThickness + fw, dist ); + + gl_FragColor = vec4( 1, 1, 1, opacity * ( 1.0 - a ) ); + + } + `})}}const J5=new re,$5=new re;class Kce{constructor(){this.domElement=null,this.buttons=0,this.pointerType=null,this.pointerOrder=[],this.previousPositions={},this.pointerPositions={},this.startPositions={},this.pointerSetThisFrame={},this.hoverPosition=new re,this.hoverSet=!1}reset(){this.buttons=0,this.pointerType=null,this.pointerOrder=[],this.previousPositions={},this.pointerPositions={},this.startPositions={},this.pointerSetThisFrame={},this.hoverPosition=new re,this.hoverSet=!1}updateFrame(){const{previousPositions:e,pointerPositions:t}=this;for(const i in t)e[i].copy(t[i])}setHoverEvent(e){(e.pointerType==="mouse"||e.type==="wheel")&&(this.getAdjustedPointer(e,this.hoverPosition),this.hoverSet=!0)}getLatestPoint(e){return this.pointerType!==null?(this.getCenterPoint(e),e):this.hoverSet?(e.copy(this.hoverPosition),e):null}getAdjustedPointer(e,t){const i=(this.domElement?this.domElement:e.target).getBoundingClientRect(),r=e.clientX-i.left,a=e.clientY-i.top;t.set(r,a)}addPointer(e){const t=e.pointerId,i=new re;this.getAdjustedPointer(e,i),this.pointerOrder.push(t),this.pointerPositions[t]=i,this.previousPositions[t]=i.clone(),this.startPositions[t]=i.clone(),this.getPointerCount()===1&&(this.pointerType=e.pointerType,this.buttons=e.buttons)}updatePointer(e){const t=e.pointerId;return t in this.pointerPositions?(this.getAdjustedPointer(e,this.pointerPositions[t]),!0):!1}deletePointer(e){const t=e.pointerId,i=this.pointerOrder;i.splice(i.indexOf(t),1),delete this.pointerPositions[t],delete this.previousPositions[t],delete this.startPositions[t],this.getPointerCount.length===0&&(this.buttons=0,this.pointerType=null)}getPointerCount(){return this.pointerOrder.length}getCenterPoint(e,t=this.pointerPositions){const i=this.pointerOrder;if(this.getPointerCount()===1||this.getPointerType()==="mouse"){const r=i[0];return e.copy(t[r]),e}else if(this.getPointerCount()===2){const r=this.pointerOrder[0],a=this.pointerOrder[1],s=t[r],o=t[a];return e.addVectors(s,o).multiplyScalar(.5),e}return null}getPreviousCenterPoint(e){return this.getCenterPoint(e,this.previousPositions)}getStartCenterPoint(e){return this.getCenterPoint(e,this.startPositions)}getMoveDistance(){return this.getCenterPoint(J5),this.getPreviousCenterPoint($5),J5.sub($5).length()}getTouchPointerDistance(e=this.pointerPositions){if(this.getPointerCount()<=1||this.getPointerType()==="mouse")return 0;const{pointerOrder:t}=this,i=t[0],r=t[1],a=e[i],s=e[r];return a.distanceTo(s)}getPreviousTouchPointerDistance(){return this.getTouchPointerDistance(this.previousPositions)}getStartTouchPointerDistance(){return this.getTouchPointerDistance(this.startPositions)}getPointerType(){return this.pointerType}isPointerTouch(){return this.getPointerType()==="touch"}getPointerButtons(){return this.buttons}isLeftClicked(){return!!(this.buttons&1)}isRightClicked(){return!!(this.buttons&2)}}const Bx=new Me;new D;function op(n,e,t){return t.makeTranslation(-n.x,-n.y,-n.z),Bx.makeRotationFromQuaternion(e),t.premultiply(Bx),Bx.makeTranslation(n.x,n.y,n.z),t.premultiply(Bx),t}function wf(n,e,t,i){i.x=(n-t.offsetLeft)/t.clientWidth*2-1,i.y=-((e-t.offsetTop)/t.clientHeight)*2+1,i.isVector3&&(i.z=0)}function ps(n,e,t){const i=n instanceof Pr?n:n.ray,{origin:r,direction:a}=i;r.set(e.x,e.y,-1).unproject(t),a.set(e.x,e.y,1).unproject(t).sub(r),n.isRay||(n.near=0,n.far=a.length(),n.camera=t),a.normalize()}const Ws=0,yc=1,hl=2,Rf=3,AM=4,wM=.05,RM=.025,_c=new Me,Fx=new Me,Ia=new D,an=new D,Hx=new D,Vx=new D,mr=new D,ds=new D,CM=new D,Gx=new D,Vs=new ft,eU=new xs,Bi=new D,kx=new D,DM=new D,Jce=new ft,Fn=new Pr,f0=new re,ar=new re,tU=new re,p0=new re,NM=new re,nU=new re,iU={type:"change"},rU={type:"start"},aU={type:"end"};class CF extends Mi{get enabled(){return this._enabled}set enabled(e){e!==this.enabled&&(this._enabled=e,this.resetState(),this.pointerTracker.reset(),this.enabled||(this.dragInertia.set(0,0,0),this.rotationInertia.set(0,0)))}constructor(e=null,t=null,i=null,r=null){super(),this.isEnvironmentControls=!0,this.domElement=null,this.camera=null,this.scene=null,this.tilesRenderer=null,this._enabled=!0,this.cameraRadius=5,this.rotationSpeed=1,this.minAltitude=0,this.maxAltitude=.45*Math.PI,this.minDistance=10,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.zoomSpeed=1,this.adjustHeight=!0,this.enableDamping=!1,this.dampingFactor=.15,this.fallbackPlane=new xs(new D(0,1,0),0),this.useFallbackPlane=!0,this.scaleZoomOrientationAtEdges=!1,this.autoAdjustCameraRotation=!0,this.state=Ws,this.pointerTracker=new Kce,this.needsUpdate=!1,this.actionHeightOffset=0,this.pivotPoint=new D,this.zoomDirectionSet=!1,this.zoomPointSet=!1,this.zoomDirection=new D,this.zoomPoint=new D,this.zoomDelta=0,this.rotationInertiaPivot=new D,this.rotationInertia=new re,this.dragInertia=new D,this.inertiaTargetDistance=1/0,this.inertiaStableFrames=0,this.pivotMesh=new Zce,this.pivotMesh.raycast=()=>{},this.pivotMesh.scale.setScalar(.25),this.raycaster=new sT,this.raycaster.firstHitOnly=!0,this.up=new D(0,1,0),this.clock=new cv,this._detachCallback=null,this._upInitialized=!1,this._lastUsedState=Ws,this._zoomPointWasSet=!1,this._tilesOnChangeCallback=()=>this.zoomPointSet=!1,i&&this.attach(i),t&&this.setCamera(t),e&&this.setScene(e),r&&this.setTilesRenderer(r)}setScene(e){this.scene=e}setCamera(e){this.camera=e,this._upInitialized=!1,this.zoomDirectionSet=!1,this.zoomPointSet=!1,this.needsUpdate=!0,this.raycaster.camera=e,this.resetState()}setTilesRenderer(e){console.warn('EnvironmentControls: "setTilesRenderer" has been deprecated. Use "setScene" and "setEllipsoid", instead.'),this.tilesRenderer=e,this.tilesRenderer!==null&&this.setScene(this.tilesRenderer.group)}attach(e){if(this.domElement)throw new Error("EnvironmentControls: Controls already attached to element");this.domElement=e,this.pointerTracker.domElement=e,e.style.touchAction="none";const t=d=>{this.enabled&&d.preventDefault()},i=d=>{if(!this.enabled)return;d.preventDefault();const{camera:f,raycaster:p,domElement:m,up:v,pivotMesh:x,pointerTracker:S,scene:_,pivotPoint:T,enabled:E}=this;if(S.addPointer(d),this.needsUpdate=!0,S.isPointerTouch()){if(x.visible=!1,S.getPointerCount()===0)m.setPointerCapture(d.pointerId);else if(S.getPointerCount()>2){this.resetState();return}}S.getCenterPoint(ar),wf(ar.x,ar.y,m,ar),ps(p,ar,f);const b=Math.abs(p.ray.direction.dot(v));if(b{const{pointerTracker:f}=this;if(!this.enabled)return;d.preventDefault();const{pivotMesh:p,enabled:m}=this;this.zoomDirectionSet=!1,this.zoomPointSet=!1,this.state!==Ws&&(this.needsUpdate=!0),f.setHoverEvent(d),f.updatePointer(d)&&(f.isPointerTouch()&&f.getPointerCount()===2&&(r||(r=!0,queueMicrotask(()=>{r=!1,f.getCenterPoint(NM);const v=f.getStartTouchPointerDistance(),x=f.getTouchPointerDistance(),S=x-v;if(this.state===Ws||this.state===AM){f.getCenterPoint(NM),f.getStartCenterPoint(nU);const _=2*window.devicePixelRatio,T=NM.distanceTo(nU);(Math.abs(S)>_||T>_)&&(Math.abs(S)>T?(this.setState(Rf),this.zoomDirectionSet=!1):this.setState(hl))}if(this.state===Rf){const _=f.getPreviousTouchPointerDistance();this.zoomDelta+=x-_,p.visible=!1}else this.state===hl&&(p.visible=m)}))),this.dispatchEvent(iU))},s=d=>{const{pointerTracker:f}=this;!this.enabled||f.getPointerCount()===0||(f.deletePointer(d),f.getPointerType()==="touch"&&f.getPointerCount()===0&&e.releasePointerCapture(d.pointerId),this.resetState(),this.needsUpdate=!0)},o=d=>{if(!this.enabled)return;d.preventDefault();const{pointerTracker:f}=this;f.setHoverEvent(d),f.updatePointer(d),this.dispatchEvent(rU);let p;switch(d.deltaMode){case 2:p=d.deltaY*800;break;case 1:p=d.deltaY*40;break;case 0:p=d.deltaY;break}const m=Math.sign(p),v=Math.abs(p);this.zoomDelta-=.25*m*v,this.needsUpdate=!0,this._lastUsedState=Rf,this.dispatchEvent(aU)},l=d=>{this.enabled&&this.resetState()};e.addEventListener("contextmenu",t),e.addEventListener("pointerdown",i),e.addEventListener("wheel",o,{passive:!1});const u=e.getRootNode();u.addEventListener("pointermove",a),u.addEventListener("pointerup",s),u.addEventListener("pointerleave",l),this._detachCallback=()=>{e.removeEventListener("contextmenu",t),e.removeEventListener("pointerdown",i),e.removeEventListener("wheel",o),u.removeEventListener("pointermove",a),u.removeEventListener("pointerup",s),u.removeEventListener("pointerleave",l)}}detach(){this.domElement=null,this._detachCallback&&(this._detachCallback(),this._detachCallback=null,this.pointerTracker.reset())}getUpDirection(e,t){t.copy(this.up)}getCameraUpDirection(e){this.getUpDirection(this.camera.position,e)}getPivotPoint(e){let t=null;this._lastUsedState===Rf?this._zoomPointWasSet&&(t=e.copy(this.zoomPoint)):(this._lastUsedState===hl||this._lastUsedState===yc)&&(t=e.copy(this.pivotPoint));const{camera:i,raycaster:r}=this;t!==null&&(an.copy(t).project(i),(an.x<-1||an.x>1||an.y<-1||an.y>1)&&(t=null)),ps(r,{x:0,y:0},i);const a=this._raycast(r);return a&&(t===null||a.distance1){r.set(0,0,0),t.set(0,0,0);return}const f=Math.pow(2,-e/s),p=Math.max(o.near,l,u,d),m=.25*(2/(2*1e3));if(t.lengthSq()>0){ps(Fn,an.set(0,0,-1),o),Fn.applyMatrix4(o.matrixWorldInverse),Fn.direction.normalize(),Fn.recast(-Fn.direction.dot(Fn.origin)).at(p/Fn.direction.z,an),an.applyMatrix4(o.matrixWorld),ps(Fn,Ia.set(m,m,-1),o),Fn.applyMatrix4(o.matrixWorldInverse),Fn.direction.normalize(),Fn.recast(-Fn.direction.dot(Fn.origin)).at(p/Fn.direction.z,Ia),Ia.applyMatrix4(o.matrixWorld),an.sub(i).normalize(),Ia.sub(i).normalize();const v=an.angleTo(Ia)/e;t.multiplyScalar(f),(t.lengthSq()0){ps(Fn,an.set(0,0,-1),o),Fn.applyMatrix4(o.matrixWorldInverse),Fn.direction.normalize(),Fn.recast(-Fn.direction.dot(Fn.origin)).at(p/Fn.direction.z,an),an.applyMatrix4(o.matrixWorld),ps(Fn,Ia.set(m,m,-1),o),Fn.applyMatrix4(o.matrixWorldInverse),Fn.direction.normalize(),Fn.recast(-Fn.direction.dot(Fn.origin)).at(p/Fn.direction.z,Ia),Ia.applyMatrix4(o.matrixWorld);const v=an.distanceTo(Ia)/e;r.multiplyScalar(f),(r.lengthSq()0&&this._applyRotation(t.x*e,t.y*e,i),r.lengthSq()>0&&(o.position.addScaledVector(r,e),o.updateMatrixWorld())}_inertiaNeedsUpdate(){const{rotationInertia:e,dragInertia:t}=this;return e.lengthSq()!==0||t.lengthSq()!==0}_updateZoom(){const{zoomPoint:e,zoomDirection:t,camera:i,minDistance:r,maxDistance:a,pointerTracker:s,domElement:o,minZoom:l,maxZoom:u,zoomSpeed:d,state:f}=this;let p=this.zoomDelta;if(this.zoomDelta=0,!(!s.getLatestPoint(ar)||p===0&&f!==Rf))if(this.rotationInertia.set(0,0),this.dragInertia.set(0,0,0),i.isOrthographicCamera){this._updateZoomDirection();const m=this.zoomPointSet||this._updateZoomPoint();kx.unproject(i);const v=Math.pow(.95,Math.abs(p*.05));let x=p>0?1/Math.abs(v):v;x*=d,x>1?ui.zoom*x&&(x=1),i.zoom*=x,i.updateProjectionMatrix(),m&&(wf(ar.x,ar.y,o,DM),DM.unproject(i),i.position.sub(DM).add(kx),i.updateMatrixWorld())}else{this._updateZoomDirection();const m=an.copy(t);if(this.zoomPointSet||this._updateZoomPoint()){const v=e.distanceTo(i.position);if(p<0){const x=Math.min(0,v-a);p=p*v*d*.0025,p=Math.max(p,x)}else{const x=Math.max(0,v-r);p=p*Math.max(v-r,0)*d*.0025,p=Math.min(p,x)}i.position.addScaledVector(t,p),i.updateMatrixWorld()}else{const v=this._getPointBelowCamera();if(v){const x=v.distance;m.set(0,0,-1).transformDirection(i.matrixWorld),i.position.addScaledVector(m,p*x*.01),i.updateMatrixWorld()}}}}_updateZoomDirection(){if(this.zoomDirectionSet)return;const{domElement:e,raycaster:t,camera:i,zoomDirection:r,pointerTracker:a}=this;a.getLatestPoint(ar),wf(ar.x,ar.y,e,kx),ps(t,kx,i),r.copy(t.ray.direction).normalize(),this.zoomDirectionSet=!0}_updateZoomPoint(){const{camera:e,zoomDirectionSet:t,zoomDirection:i,raycaster:r,zoomPoint:a,pointerTracker:s,domElement:o}=this;if(this._zoomPointWasSet=!1,!t)return!1;e.isOrthographicCamera&&s.getLatestPoint(f0)?(wf(f0.x,f0.y,o,f0),ps(r,f0,e)):(r.ray.origin.copy(e.position),r.ray.direction.copy(i),r.near=0,r.far=1/0);const l=this._raycast(r);return l?(a.copy(l.point),this.zoomPointSet=!0,this._zoomPointWasSet=!0,!0):!1}_getPointBelowCamera(e=this.camera.position,t=this.up){const{raycaster:i}=this;i.ray.direction.copy(t).multiplyScalar(-1),i.ray.origin.copy(e).addScaledVector(t,1e5),i.near=0,i.far=1/0;const r=this._raycast(i);return r&&(r.distance-=1e5),r}_updatePosition(e){const{raycaster:t,camera:i,pivotPoint:r,up:a,pointerTracker:s,domElement:o,state:l,dragInertia:u}=this;if(l===yc){if(s.getCenterPoint(ar),wf(ar.x,ar.y,o,ar),eU.setFromNormalAndCoplanarPoint(a,r),ps(t,ar,i),Math.abs(t.ray.direction.dot(a))1-1e-10?d=0:(an.crossVectors(Bi,mr).normalize(),d=Math.sign(an.dot(ds))*Bi.angleTo(mr)),u>0?(u=Math.min(d-a,u),u=Math.max(0,u)):(u=Math.max(d-s,u),u=Math.min(0,u)),Vs.setFromAxisAngle(Bi,l),op(i,Vs,_c),r.matrixWorld.premultiply(_c),ds.set(1,0,0).transformDirection(r.matrixWorld),Vs.setFromAxisAngle(ds,-u),op(i,Vs,_c),r.matrixWorld.premultiply(_c),r.matrixWorld.decompose(r.position,r.quaternion,an)}_setFrame(e){const{up:t,camera:i,zoomPoint:r,zoomDirectionSet:a,zoomPointSet:s,scaleZoomOrientationAtEdges:o}=this;if(a&&(s||this._updateZoomPoint())){if(Vs.setFromUnitVectors(t,e),o){this.getUpDirection(r,an);let l=Math.max(an.dot(t)-.6,0)/.4;l=lt.mapLinear(l,0,.5,0,1),l=Math.min(l,1),i.isOrthographicCamera&&(l*=.1),Vs.slerp(Jce,1-l)}op(r,Vs,_c),i.updateMatrixWorld(),i.matrixWorld.premultiply(_c),i.matrixWorld.decompose(i.position,i.quaternion,an),this.zoomDirectionSet=!1,this._updateZoomDirection()}t.copy(e),i.updateMatrixWorld()}_raycast(e){const{scene:t,useFallbackPlane:i,fallbackPlane:r}=this,a=e.intersectObject(t)[0]||null;if(a)return a;if(i){const s=r;if(e.ray.intersectPlane(s,an))return{point:an.clone(),distance:e.ray.origin.distanceTo(an)}}return null}_alignCameraUp(e,t=1){const{camera:i,state:r,pivotPoint:a,zoomPoint:s,zoomPointSet:o}=this;i.updateMatrixWorld(),mr.set(0,0,-1).transformDirection(i.matrixWorld),ds.set(-1,0,0).transformDirection(i.matrixWorld);let l=lt.mapLinear(1-Math.abs(mr.dot(e)),0,.2,0,1);l=lt.clamp(l,0,1),t*=l,CM.crossVectors(e,mr),CM.lerp(ds,1-t).normalize(),Vs.setFromUnitVectors(ds,CM),i.quaternion.premultiply(Vs);let u=null;r===yc||r===hl?u=Hx.copy(a):o&&(u=Hx.copy(s)),u&&(Fx.copy(i.matrixWorld).invert(),an.copy(u).applyMatrix4(Fx),i.updateMatrixWorld(),an.applyMatrix4(i.matrixWorld),Vx.subVectors(u,an),i.position.add(Vx)),i.updateMatrixWorld()}_clampRotation(e){const{camera:t,minAltitude:i,maxAltitude:r,state:a,pivotPoint:s,zoomPoint:o,zoomPointSet:l}=this;t.updateMatrixWorld(),mr.set(0,0,1).transformDirection(t.matrixWorld),ds.set(1,0,0).transformDirection(t.matrixWorld);let u;e.dot(mr)>1-1e-10?u=0:(an.crossVectors(e,mr),u=Math.sign(an.dot(ds))*e.angleTo(mr));let d;if(u>r)d=r;else if(uUa.subVectors(Rn,Hn.origin).dot(Hn.direction))&&e.copy(Rn),e}getVectorToCenter(e){const{ellipsoidFrame:t,camera:i}=this;return e.setFromMatrixPosition(t).sub(i.position)}getDistanceToCenter(){return this.getVectorToCenter(Rn).length()}getUpDirection(e,t){const{ellipsoidFrame:i,ellipsoidFrameInverse:r,ellipsoid:a}=this;Rn.copy(e).applyMatrix4(r),a.getPositionToNormal(Rn,t),t.transformDirection(i)}getCameraUpDirection(e){const{ellipsoidFrame:t,ellipsoidFrameInverse:i,ellipsoid:r,camera:a}=this;a.isOrthographicCamera?(this._getVirtualOrthoCameraPosition(Rn),Rn.applyMatrix4(i),r.getPositionToNormal(Rn,e),e.transformDirection(t)):this.getUpDirection(a.position,e)}update(e=Math.min(this.clock.getDelta(),64/1e3)){if(!this.enabled||!this.camera||e===0)return;const{camera:t,pivotMesh:i}=this;this._isNearControls()?this.scaleZoomOrientationAtEdges=this.zoomDelta<0:(this.state!==Ws&&this._dragMode!==1&&this._rotationMode!==1&&(i.visible=!1),this.scaleZoomOrientationAtEdges=!1);const r=this.needsUpdate||this._inertiaNeedsUpdate();super.update(e),this.adjustCamera(t),r&&this._isNearControls()&&(this.getCameraUpDirection(Sf),this._alignCameraUp(Sf,1),this.getCameraUpDirection(Sf),this._clampRotation(Sf))}adjustCamera(e){super.adjustCamera(e);const{ellipsoidFrame:t,ellipsoidFrameInverse:i,ellipsoid:r,nearMargin:a,farMargin:s}=this,o=Math.max(...r.radius);if(e.isPerspectiveCamera){const l=Rn.setFromMatrixPosition(t).sub(e.position).length(),u=a*o,d=lt.clamp((l-o)/u,0,1),f=lt.lerp(1,1e3,d);e.near=Math.max(f,l-o-u),Ua.copy(e.position).applyMatrix4(i),r.getPositionToCartographic(Ua,cU);const p=Math.max(r.getPositionElevation(Ua),eue),m=r.calculateHorizonDistance(cU.lat,p);e.far=m+.1+o*s,e.updateProjectionMatrix()}else{this._getVirtualOrthoCameraPosition(e.position,e),e.updateMatrixWorld(),sU.copy(e.matrixWorld).invert(),Rn.setFromMatrixPosition(t).applyMatrix4(sU);const l=-Rn.z;e.near=l-o*(1+a),e.far=l+.1+o*s,e.position.addScaledVector(Pa,e.near),e.far-=e.near,e.near=0,e.updateProjectionMatrix(),e.updateMatrixWorld()}}setState(...e){super.setState(...e),this._dragMode=0,this._rotationMode=0}_updateInertia(e){super._updateInertia(e);const{globeInertia:t,enableDamping:i,dampingFactor:r,camera:a,cameraRadius:s,minDistance:o,inertiaTargetDistance:l,ellipsoidFrame:u}=this;if(!this.enableDamping||this.inertiaStableFrames>1){this.globeInertiaFactor=0,this.globeInertia.identity();return}const d=Math.pow(2,-e/r),f=Math.max(a.near,s,o,l),p=.25*(2/(2*1e3));if(dl.setFromMatrixPosition(u),this.globeInertiaFactor!==0){ps(Hn,Rn.set(0,0,-1),a),Hn.applyMatrix4(a.matrixWorldInverse),Hn.direction.normalize(),Hn.recast(-Hn.direction.dot(Hn.origin)).at(f/Hn.direction.z,Rn),Rn.applyMatrix4(a.matrixWorld),ps(Hn,Ua.set(p,p,-1),a),Hn.applyMatrix4(a.matrixWorldInverse),Hn.direction.normalize(),Hn.recast(-Hn.direction.dot(Hn.origin)).at(f/Hn.direction.z,Ua),Ua.applyMatrix4(a.matrixWorld),Rn.sub(dl).normalize(),Ua.sub(dl).normalize(),this.globeInertiaFactor*=d;const m=Rn.angleTo(Ua)/e;(2*Math.acos(t.w)*this.globeInertiaFactor0){if(this._updateZoomDirection(),e<0&&(this.zoomPointSet||this._updateZoomPoint())){Pa.set(0,0,-1).transformDirection(a.matrixWorld).normalize(),Ku.copy(this.up).multiplyScalar(-1),this.getUpDirection(r,oU);const u=lt.clamp(lt.mapLinear(-oU.dot(Ku),1,.95,0,1),0,1),d=1-Pa.dot(Ku),f=a.isOrthographicCamera?.05:1,p=lt.clamp(l*3,0,1),m=Math.min(u*d*f*p,.1);Ku.lerpVectors(Pa,Ku,m).normalize(),fl.setFromUnitVectors(Pa,Ku),op(r,fl,yf),a.matrixWorld.premultiply(yf),a.matrixWorld.decompose(a.position,a.quaternion,Ku),this.zoomDirection.subVectors(r,a.position).normalize()}super._updateZoom()}else if(a.isPerspectiveCamera){const u=this._getPerspectiveTransitionDistance(),d=this._getMaxPerspectiveDistance(),f=lt.mapLinear(this.getDistanceToCenter(),u,d,0,1);this._tiltTowardsCenter(lt.lerp(0,.4,f*l)),this._alignCameraUpToNorth(lt.lerp(0,.2,f*l));const p=this.getDistanceToCenter()-t.radius.x,m=e*p*i*.0025,v=Math.max(m,Math.min(this.getDistanceToCenter()-d,0));this.getVectorToCenter(Rn).normalize(),this.camera.position.addScaledVector(Rn,v),this.camera.updateMatrixWorld(),this.zoomDelta=0}else{const u=this._getOrthographicTransitionZoom(),d=this._getMinOrthographicZoom(),f=lt.mapLinear(a.zoom,u,d,0,1);this._tiltTowardsCenter(lt.lerp(0,.4,f*l)),this._alignCameraUpToNorth(lt.lerp(0,.2,f*l));const p=this.zoomDelta,m=Math.pow(.95,Math.abs(p*.05)),v=p>0?1/Math.abs(m):m,x=d/a.zoom,S=Math.max(v*i,Math.min(x,1));a.zoom=Math.min(s,a.zoom*S),a.updateProjectionMatrix(),this.zoomDelta=0,this.zoomDirectionSet=!1}}_alignCameraUpToNorth(e){const{ellipsoidFrame:t}=this;Sf.set(0,0,1).transformDirection(t),this._alignCameraUp(Sf,e)}_tiltTowardsCenter(e){const{camera:t,ellipsoidFrame:i}=this;Pa.set(0,0,-1).transformDirection(t.matrixWorld).normalize(),Rn.setFromMatrixPosition(i).sub(t.position).normalize(),Rn.lerp(Pa,1-e).normalize(),fl.setFromUnitVectors(Pa,Rn),t.quaternion.premultiply(fl),t.updateMatrixWorld()}_getPerspectiveTransitionDistance(){const{camera:e,ellipsoid:t}=this;if(!e.isPerspectiveCamera)throw new Error;const i=Math.max(...t.radius),r=2*Math.atan(Math.tan(lt.DEG2RAD*e.fov*.5)*e.aspect),a=i/Math.tan(lt.DEG2RAD*e.fov*.5),s=i/Math.tan(r*.5);return Math.max(a,s)}_getMaxPerspectiveDistance(){const{camera:e,ellipsoid:t}=this;if(!e.isPerspectiveCamera)throw new Error;const i=Math.max(...t.radius),r=2*Math.atan(Math.tan(lt.DEG2RAD*e.fov*.5)*e.aspect),a=i/Math.tan(lt.DEG2RAD*e.fov*.5),s=i/Math.tan(r*.5);return 2*Math.max(a,s)}_getOrthographicTransitionZoom(){const{camera:e,ellipsoid:t}=this;if(!e.isOrthographicCamera)throw new Error;const i=e.top-e.bottom,r=e.right-e.left,a=Math.max(i,r),s=2*Math.max(...t.radius);return 2*a/s}_getMinOrthographicZoom(){const{camera:e,ellipsoid:t}=this;if(!e.isOrthographicCamera)throw new Error;const i=e.top-e.bottom,r=e.right-e.left,a=Math.min(i,r),s=2*Math.max(...t.radius);return .7*a/s}_getVirtualOrthoCameraPosition(e,t=this.camera){const{ellipsoidFrame:i,ellipsoidFrameInverse:r,ellipsoid:a}=this;if(!t.isOrthographicCamera)throw new Error;Hn.origin.copy(t.position),Hn.direction.set(0,0,-1).transformDirection(t.matrixWorld),Hn.applyMatrix4(r),a.closestPointToRayEstimate(Hn,Ua).applyMatrix4(i);const s=t.top-t.bottom,o=t.right-t.left,l=Math.max(s,o)/t.zoom;Pa.set(0,0,-1).transformDirection(t.matrixWorld);const u=Ua.sub(t.position).dot(Pa);e.copy(t.position).addScaledVector(Pa,u-l*4)}_isNearControls(){const{camera:e}=this;return e.isPerspectiveCamera?this.getDistanceToCenter()this._getOrthographicTransitionZoom()}_raycast(e){const t=super._raycast(e);if(t===null){const{ellipsoid:i,ellipsoidFrame:r,ellipsoidFrameInverse:a}=this;Hn.copy(e.ray).applyMatrix4(a);const s=i.intersectRay(Hn,Rn);return s!==null?(s.applyMatrix4(r),{point:s.clone(),distance:s.distanceTo(e.ray.origin)}):null}else return t}};const Hr=new D,Ju=new D,$u=new Za,nue=new D,iue=new D,rue=new D,uU=new ft,aue=new ft;let sue=class extends Mi{get animating(){return this._alpha!==0&&this._alpha!==1}get alpha(){return this._target===0?1-this._alpha:this._alpha}get camera(){return this._alpha===0?this.perspectiveCamera:this._alpha===1?this.orthographicCamera:this.transitionCamera}get mode(){return this._target===0?"perspective":"orthographic"}set mode(e){if(e===this.mode)return;const t=this.camera;e==="perspective"?(this._target=0,this._alpha=0):(this._target=1,this._alpha=1),this.dispatchEvent({type:"camera-change",camera:this.camera,prevCamera:t})}constructor(e=new si,t=new Za){super(),this.perspectiveCamera=e,this.orthographicCamera=t,this.transitionCamera=new si,this.orthographicPositionalZoom=!0,this.orthographicOffset=50,this.fixedPoint=new D,this.duration=200,this.autoSync=!0,this.easeFunction=i=>i,this._target=0,this._alpha=0,this._clock=new cv}toggle(){this._target=this._target===1?0:1,this._clock.getDelta(),this.dispatchEvent({type:"toggle"})}update(e=Math.min(this._clock.getDelta(),64/1e3)){this.autoSync&&this.syncCameras();const{perspectiveCamera:t,orthographicCamera:i,transitionCamera:r,camera:a}=this,s=e*1e3;if(this._alpha!==this._target){const u=Math.sign(this._target-this._alpha)*s/this.duration;this._alpha=lt.clamp(this._alpha+u,0,1),this.dispatchEvent({type:"change",alpha:this.alpha})}const o=a;let l=null;this._alpha===0?l=t:this._alpha===1?l=i:(l=r,this._updateTransitionCamera()),o!==l&&(l===r&&this.dispatchEvent({type:"transition-start"}),this.dispatchEvent({type:"camera-change",camera:l,prevCamera:o}),o===r&&this.dispatchEvent({type:"transition-end"}))}syncCameras(){const e=this._getFromCamera(),{perspectiveCamera:t,orthographicCamera:i,transitionCamera:r,fixedPoint:a}=this;if(Hr.set(0,0,-1).transformDirection(e.matrixWorld).normalize(),e.isPerspectiveCamera){if(this.orthographicPositionalZoom)i.position.copy(t.position).addScaledVector(Hr,-this.orthographicOffset),i.rotation.copy(t.rotation),i.updateMatrixWorld();else{const u=Ju.subVectors(a,i.position).dot(Hr),d=Ju.subVectors(a,t.position).dot(Hr);Ju.copy(t.position).addScaledVector(Hr,d),i.rotation.copy(t.rotation),i.position.copy(Ju).addScaledVector(Hr,-u),i.updateMatrixWorld()}const s=Math.abs(Ju.subVectors(t.position,a).dot(Hr)),o=2*Math.tan(lt.DEG2RAD*t.fov*.5)*s,l=i.top-i.bottom;i.zoom=l/o,i.updateProjectionMatrix()}else{const s=Math.abs(Ju.subVectors(i.position,a).dot(Hr)),o=(i.top-i.bottom)/i.zoom*.5/Math.tan(lt.DEG2RAD*t.fov*.5);t.rotation.copy(i.rotation),t.position.copy(i.position).addScaledVector(Hr,s).addScaledVector(Hr,-o),t.updateMatrixWorld(),this.orthographicPositionalZoom&&(i.position.copy(t.position).addScaledVector(Hr,-this.orthographicOffset),i.updateMatrixWorld())}r.position.copy(t.position),r.rotation.copy(t.rotation)}_getTransitionDirection(){return Math.sign(this._target-this._alpha)}_getToCamera(){const e=this._getTransitionDirection();return e===0?this._target===0?this.perspectiveCamera:this.orthographicCamera:e>0?this.orthographicCamera:this.perspectiveCamera}_getFromCamera(){const e=this._getTransitionDirection();return e===0?this._target===0?this.perspectiveCamera:this.orthographicCamera:e>0?this.perspectiveCamera:this.orthographicCamera}_updateTransitionCamera(){const{perspectiveCamera:e,orthographicCamera:t,transitionCamera:i,fixedPoint:r}=this,a=this.easeFunction(this._alpha);Hr.set(0,0,-1).transformDirection(t.matrixWorld).normalize(),$u.copy(t),$u.position.addScaledVector(Hr,t.near),t.far-=t.near,t.near=0,Hr.set(0,0,-1).transformDirection(e.matrixWorld).normalize();const s=Math.abs(Ju.subVectors(e.position,r).dot(Hr)),o=2*Math.tan(lt.DEG2RAD*e.fov*.5)*s,l=aue.slerpQuaternions(e.quaternion,$u.quaternion,a),u=lt.lerp(e.fov,1,a),d=o*.5/Math.tan(lt.DEG2RAD*u*.5),f=rue.copy($u.position).sub(r).applyQuaternion(uU.copy($u.quaternion).invert()),p=iue.copy(e.position).sub(r).applyQuaternion(uU.copy(e.quaternion).invert()),m=nue.lerpVectors(p,f,a);m.z-=Math.abs(m.z)-d;const v=-(p.z-m.z),x=-(f.z-m.z),S=lt.lerp(v+e.near,x+$u.near,a),_=lt.lerp(v+e.far,x+$u.far,a),T=Math.max(_,0)-Math.max(S,0);i.aspect=e.aspect,i.fov=u,i.near=Math.max(S,T*1e-5),i.far=_,i.position.copy(m).applyQuaternion(l).add(r),i.quaternion.copy(l),i.updateProjectionMatrix(),i.updateMatrixWorld()}};function oue(n,e){if(n===e)return!0;if(!n||!e)return n===e;for(const t in n)if(n[t]!==e[t])return!1;for(const t in e)if(n[t]!==e[t])return!1;return!0}function DF(n){const e=ie.useRef();return oue(e.current,n)||(e.current=n),e.current}function lue(n){return/^on/g.test(n)}function cue(n){return n.replace(/^on/,"").replace(/[a-z][A-Z]/g,e=>`${e[0]}-${e[1]}`).toLowerCase()}function hU(n){return n.split("-")}function NF(n,e){let t=n;const i=[...e];for(;i.length!==0;){const r=i.shift();t=t[r]}return t}function dU(n,e,t){const i=[...e],r=i.pop();NF(n,i)[r]=t}function vv(n,e,t=!1){ie.useLayoutEffect(()=>{if(n===null)return;const i={},r={};for(const a in e)if(lue(a)&&n.addEventListener&&!(a in n)){const s=cue(a);r[s]=e[a],n.addEventListener(s,e[a])}else{const s=t?[a]:hU(a);i[a]=NF(n,s),dU(n,s,e[a])}return()=>{for(const a in r)n.removeEventListener(a,r[a]);for(const a in i){const s=t?[a]:hU(a);dU(n,s,i[a])}}},[n,DF(e)])}function uue(n,e){vv(n,e,!0)}function _v(n,...e){ie.useEffect(()=>{e.forEach(t=>{t&&(t instanceof Function?t(n):t.current=n)})},[n,...e])}const ld=ie.createContext(null),hue=ie.createContext(null);function due({children:n}){const e=ie.useContext(ld),t=ie.useRef();return ie.useEffect(()=>{e&&(t.current.matrixWorld=e.group.matrixWorld)},[e]),ot.jsx("group",{ref:t,matrixWorldAutoUpdate:!1,matrixAutoUpdate:!1,children:n})}const g0=ie.forwardRef(function(n,e){const{plugin:t,args:i,children:r,...a}=n,s=ie.useContext(ld),[o,l]=ie.useState(null),[,u]=ie.useReducer(d=>d+1,0);if(ie.useLayoutEffect(()=>{if(s===null)return;let d;return Array.isArray(i)?d=new t(...i):d=new t(i),l(d),()=>{l(null)}},[t,s,DF(i)]),vv(o,a),ie.useLayoutEffect(()=>{if(o!==null)return s.registerPlugin(o),u(),()=>{s.unregisterPlugin(o)}},[o]),_v(o,e),!(!o||!s.plugins.includes(o)))return ot.jsx(hue.Provider,{value:o,children:r})}),fue=ie.forwardRef(function(n,e){const{url:t,group:i={},enabled:r=!0,children:a,...s}=n,[o,l,u]=pn(p=>[p.camera,p.gl,p.invalidate]),[d,f]=ie.useState(null);return ie.useEffect(()=>{const p=()=>u(),m=new jce(t);return m.addEventListener("needs-render",p),m.addEventListener("needs-update",p),f(m),()=>{m.removeEventListener("needs-render",p),m.removeEventListener("needs-update",p),m.dispose(),f(null)}},[t,u]),_a(()=>{d===null||!r||(o.updateMatrixWorld(),d.setResolutionFromRenderer(o,l),d.update())}),ie.useLayoutEffect(()=>{if(d!==null)return d.setCamera(o),()=>{d.deleteCamera(o)}},[d,o]),_v(d,e),vv(d,s),d?ot.jsxs(ot.Fragment,{children:[ot.jsx("primitive",{object:d.group,...i}),ot.jsx(ld.Provider,{value:d,children:ot.jsx(due,{children:a})})]}):null});ie.forwardRef(function({children:n,...e},t){const[i]=pn(o=>[o.gl]),[r,a]=ie.useState(null),s=ie.useMemo(()=>document.createElement("div"),[]);ie.useEffect(()=>(s.style.pointerEvents="none",s.style.position="absolute",s.style.width="100%",s.style.height="100%",s.style.left=0,s.style.top=0,i.domElement.parentNode.appendChild(s),()=>{s.remove()}),[s,i.domElement.parentNode]),ie.useEffect(()=>{const o=H8.createRoot(s);return a(o),()=>{o.unmount()}},[s]),r!==null&&r.render(ot.jsx(ie.StrictMode,{children:ot.jsx("div",{...e,ref:t,children:n})}))});const OF=ie.forwardRef(function(n,e){const{controlsConstructor:t,domElement:i,scene:r,camera:a,ellipsoid:s,ellipsoidFrame:o,tilesRenderer:l,...u}=n,[d]=pn(U=>[U.camera]),[f]=pn(U=>[U.gl]),[p]=pn(U=>[U.scene]),[m]=pn(U=>[U.invalidate]),[v]=pn(U=>[U.get]),[x]=pn(U=>[U.set]),S=ie.useContext(ld),_=l||S,T=a||d||null,E=r||p||null,b=i||f.domElement||null,R=s||(_==null?void 0:_.ellipsoid)||null,w=o||(_==null?void 0:_.group)||null,L=ie.useMemo(()=>new t,[t]);_v(L,e),ie.useEffect(()=>{const U=()=>m();return L.addEventListener("change",U),L.addEventListener("start",U),L.addEventListener("end",U),()=>{L.removeEventListener("change",U),L.removeEventListener("start",U),L.removeEventListener("end",U)}},[L,m]),ie.useEffect(()=>{L.setCamera(T)},[L,T]),ie.useEffect(()=>{L.setScene(E)},[L,E]),ie.useEffect(()=>{L.isGlobeControls&&L.setEllipsoid(R,w)},[L,R,w]),ie.useEffect(()=>(L.attach(b),()=>{L.detach()}),[L,b]),ie.useEffect(()=>{const U=v().controls;return x({controls:L}),()=>x({controls:U})},[L,v,x]),_a(()=>{L.update()},-1),uue(L,u)});ie.forwardRef(function(n,e){return ot.jsx(OF,{...n,ref:e,controlsConstructor:CF})});ie.forwardRef(function(n,e){return ot.jsx(OF,{...n,ref:e,controlsConstructor:tue})});ie.forwardRef(function(n,e){const{mode:t="perspective",onBeforeToggle:i,perspectiveCamera:r,orthographicCamera:a,...s}=n,[o,l,u,d,f,p]=pn(v=>[v.set,v.get,v.invalidate,v.controls,v.camera,v.size]),m=ie.useMemo(()=>{const v=new sue;return v.autoSync=!1,f.isOrthographicCamera?(v.orthographicCamera.copy(f),v.mode="orthographic"):v.perspectiveCamera.copy(f),v.syncCameras(),v.mode=t,v},[]);ie.useEffect(()=>{const{perspectiveCamera:v,orthographicCamera:x}=m,S=p.width/p.height;v.aspect=S,v.updateProjectionMatrix(),x.left=-x.top*S,x.right=-x.left,v.updateProjectionMatrix()},[m,p]),_v(m,e),ie.useEffect(()=>{const v=({camera:x})=>{o(()=>({camera:x}))};return o(()=>({camera:m.camera})),m.addEventListener("camera-change",v),()=>{m.removeEventListener("camera-change",v)}},[m,o]),ie.useEffect(()=>{const v=m.perspectiveCamera,x=m.orthographicCamera;return m.perspectiveCamera=r||v,m.orthographicCamera=a||x,o(()=>({camera:m.camera})),()=>{m.perspectiveCamera=v,m.orthographicCamera=x}},[r,a,m,o]),ie.useEffect(()=>{if(t!==m.mode){const v=t==="orthographic"?m.orthographicCamera:m.perspectiveCamera;i?i(m,v):d&&d.isEnvironmentControls?(d.getPivotPoint(m.fixedPoint),m.syncCameras(),d.adjustCamera(m.perspectiveCamera),d.adjustCamera(m.orthographicCamera)):(m.fixedPoint.set(0,0,-1).transformDirection(m.camera.matrixWorld).multiplyScalar(50).add(m.camera.position),m.syncCameras()),m.toggle(),u()}},[t,m,u,d,i]),ie.useEffect(()=>{const v=()=>u();return m.addEventListener("transition-start",v),m.addEventListener("change",v),m.addEventListener("transition-end",v),()=>{m.removeEventListener("transition-start",v),m.removeEventListener("change",v),m.removeEventListener("transition-end",v)}},[m,u]),vv(m,s),_a(()=>{m.update(),d&&(d.enabled=!m.animating);const{camera:v,size:x}=l();if(!a&&v===m.orthographicCamera){const S=x.width/x.height,_=m.orthographicCamera;S!==_.right&&(_.bottom=-1,_.top=1,_.left=-S,_.right=S,_.updateProjectionMatrix())}m.animating&&u()},-1)});function LF(...n){return ie.useCallback(e=>{n.forEach(t=>{t&&(typeof t=="function"?t(e):t.current=e)})},n)}function kA(n,e){e(n)||n.children.forEach(t=>{kA(t,e)})}class pue extends Mi{constructor(){super(),this.objects=new Set,this.observed=new Set,this._addedCallback=({child:e})=>{kA(e,t=>this.observed.has(t)?!0:(this.objects.add(t),t.addEventListener("childadded",this._addedCallback),t.addEventListener("childremoved",this._removedCallback),this.dispatchEvent({type:"childadded",child:e}),!1))},this._removedCallback=({child:e})=>{kA(e,t=>this.observed.has(t)?!0:(this.objects.delete(t),t.removeEventListener("childadded",this._addedCallback),t.removeEventListener("childremoved",this._removedCallback),this.dispatchEvent({type:"childremoved",child:e}),!1))}}observe(e){const{observed:t}=this;this._addedCallback({child:e}),t.add(e)}unobserve(e){const{observed:t}=this;t.delete(e),this._removedCallback({child:e})}dispose(){this.observed.forEach(e=>{this.unobserve(e)})}}const OM=new sT,v0=new NR,Wx=new NR,fU=new re,Xx=new D,pU=new Me;let mue=class extends Mi{constructor(){super(),this.autoRun=!0,this.queryMap=new Map,this.index=0,this.queued=[],this.scheduled=!1,this.duration=1,this.objects=[],this.observer=new pue,this.ellipsoid=new wT,this.frame=new Me,this.cameras=new Set;const e=(()=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{this.queryMap.forEach(i=>this._enqueue(i)),t=!1}))}})();this.observer.addEventListener("childadded",e),this.observer.addEventListener("childremoved",e)}_enqueue(e){e.queued||(this.queued.push(e),e.queued=!0,this._scheduleRun())}_runJobs(){const{queued:e,cameras:t,duration:i}=this,r=performance.now();for(t.forEach((a,s)=>{pU.copy(a.matrixWorldInverse).premultiply(a.projectionMatrix),Xx.set(0,0,-1).transformDirection(a.matrixWorld),v0.start.setFromMatrixPosition(a.matrixWorld),v0.end.addVectors(Xx,v0.start);for(let o=0,l=e.length;o-1&&m.x<1&&m.y>-1&&m.y<1&&m.z>-1&&m.z<1?(u.distance=m.subVectors(u.point,v0.start).dot(Xx),u.inFrustum=!0):(u.distance=0,u.inFrustum=!1)}s===0?(u.distance=f,u.inFrustum=p):(u.inFrustum=u.inFrustum||p,u.distance=Math.min(u.distance,f))}}),t.length!==0&&e.sort((a,s)=>a.point===null!=(s.point===null)?a.point===null?1:-1:a.inFrustum!==s.inFrustum?a.inFrustum?1:-1:a.distance<0!=s.distance<0?a.distance<0?-1:1:s.distance-a.distance);e.length!==0&&performance.now()-r{this.scheduled=!1,this._runJobs()}))}_updateQuery(e){OM.ray.copy(e.ray),OM.far="lat"in e?1e4+Math.max(...this.ellipsoid.radius):1/0;const t=OM.intersectObjects(this.objects)[0]||null;t!==null&&(e.point===null?e.point=t.point.clone():e.point.copy(t.point)),e.callback(t)}addCamera(e){const{queryMap:t,cameras:i}=this;i.add(e),t.forEach(r=>this._enqueue(r))}deleteCamera(e){const{cameras:t}=this;t.delete(e)}runIfNeeded(e){const{queryMap:t,queued:i}=this,r=t.get(e);r.queued&&(this._updateQuery(r),r.queued=!1,i.splice(i.indexOf(r),1))}setScene(...e){const{observer:t}=this;t.dispose(),e.forEach(i=>t.observe(i)),this.objects=e,this._scheduleRun()}setEllipsoidFromTilesRenderer(e){const{queryMap:t,ellipsoid:i,frame:r}=this;(!i.radius.equals(e.ellipsoid.radius)||!r.equals(e.group.matrixWorld))&&(i.copy(e.ellipsoid),r.copy(e.group.matrixWorld),t.forEach(a=>{if("lat"in a){const{lat:s,lon:o,ray:l}=a;i.getCartographicToPosition(s,o,1e4,l.origin).applyMatrix4(r),i.getCartographicToNormal(s,o,l.direction).transformDirection(r).multiplyScalar(-1)}this._enqueue(a)}))}registerRayQuery(e,t){const i=this.index++,r={ray:e.clone(),callback:t,queued:!1,distance:-1,point:null};return this.queryMap.set(i,r),this._enqueue(r),i}registerLatLonQuery(e,t,i){const{ellipsoid:r,frame:a}=this,s=this.index++,o=new Pr;r.getCartographicToPosition(e,t,1e4,o.origin).applyMatrix4(a),r.getCartographicToNormal(e,t,o.direction).transformDirection(a).multiplyScalar(-1);const l={ray:o.clone(),lat:e,lon:t,callback:i,queued:!1,distance:-1,point:null};return this.queryMap.set(s,l),this._enqueue(l),s}unregisterQuery(e){const{queued:t,queryMap:i}=this,r=i.get(e);i.delete(e),r&&r.queued&&(r.queued=!1,t.splice(t.indexOf(r),1))}dispose(){this.queryMap.clear(),this.queued.length=0,this.objects.length=0,this.observer.dispose()}};const gue=function(){const n=new D,e=new D,t=new D;return function(i,r,a){const s=i.start,o=n,l=r.start,u=e;t.subVectors(s,l),n.subVectors(i.end,i.start),e.subVectors(r.end,r.start);const d=t.dot(u),f=u.dot(o),p=u.dot(u),m=t.dot(o),v=o.dot(o)*p-f*f;let x,S;v!==0?x=(d*f-m*p)/v:x=0,S=(d+x*f)/p,a.x=x,a.y=S}}(),hC=ie.createContext(null),tS=new Me,LM=new Pr;ie.forwardRef(function(n,e){const{interpolationFactor:t=.025,onQueryUpdate:i=null,...r}=n,a=ie.useContext(ld),s=ie.useContext(hC),o=pn(({invalidate:m})=>m),l=ie.useMemo(()=>new D,[]),u=ie.useMemo(()=>({value:!1}),[]),d=ie.useMemo(()=>({value:!1}),[]),f=ie.useRef(null),p=ie.useCallback(m=>{if(a===null||m===null||f.current===null)return;const{lat:v,lon:x,rayorigin:S,raydirection:_}=r;v!==null&&x!==null?(l.copy(m.point),d.value=!0,s.ellipsoid.getObjectFrame(v,x,0,0,0,0,tS,jf).premultiply(a.group.matrixWorld),f.current.quaternion.setFromRotationMatrix(tS),o()):S!==null&&_!==null&&(l.copy(m.point),d.value=!0,f.current.quaternion.identity(),o()),i&&i(m)},[o,d,s.ellipsoid,r,l,a,i]);return _a((m,v)=>{if(f.current&&(f.current.visible=u.value),f.current&&d.value)if(u.value===!1)u.value=!0,f.current.position.copy(l);else{const x=1-2**(-v/t);f.current.position.distanceToSquared(l)>1e-6?(f.current.position.lerp(l,t===0?1:x),o()):f.current.position.copy(l)}}),ot.jsx(vue,{ref:LF(f,e),onQueryUpdate:p,...r})});const vue=ie.forwardRef(function(n,e){const{component:t=ot.jsx("group",{}),lat:i=null,lon:r=null,rayorigin:a=null,raydirection:s=null,onQueryUpdate:o=null,...l}=n,u=ie.useRef(null),d=ie.useContext(ld),f=ie.useContext(hC),p=pn(({invalidate:v})=>v),m=ie.useMemo(()=>new D,[]);return ie.useEffect(()=>{const v=x=>{o?o(x):d&&x!==null&&u.current!==null&&(i!==null&&r!==null?(u.current.position.copy(x.point),f.ellipsoid.getObjectFrame(i,r,0,0,0,0,tS,jf).premultiply(d.group.matrixWorld),u.current.quaternion.setFromRotationMatrix(tS),p()):a!==null&&s!==null&&(u.current.position.copy(x.point),u.current.quaternion.identity(),p()))};if(i!==null&&r!==null){const x=f.registerLatLonQuery(i,r,v);return()=>f.unregisterQuery(x)}else if(a!==null&&s!==null){LM.origin.copy(a),LM.direction.copy(s);const x=f.registerRayQuery(LM,v);return()=>f.unregisterQuery(x)}},[i,r,a,s,f,d,p,m,o]),ie.cloneElement(t,{...l,ref:LF(u,e),raycast:()=>!1})});ie.forwardRef(function(n,e){const t=pn(({scene:u})=>u),{scene:i=t,children:r,...a}=n,s=ie.useContext(ld),o=ie.useMemo(()=>new mue,[]),l=pn(({camera:u})=>u);return vv(o,a),ie.useEffect(()=>()=>o.dispose(),[o]),ie.useEffect(()=>{o.setScene(...Array.isArray(i)?i:[i])},[o,i]),ie.useEffect(()=>{o.addCamera(l)},[o,l]),_a(()=>{s&&o.setEllipsoidFromTilesRenderer(s)}),_v(o,e),ot.jsx(hC.Provider,{value:o,children:ot.jsx("group",{matrixAutoUpdate:!1,matrixWorldAutoUpdate:!1,children:r})})});const mU="https://tile.googleapis.com/v1/createSession";class _ue{get isMapTilesSession(){return this.authURL===mU}constructor(e={}){const{apiToken:t,sessionOptions:i=null,autoRefreshToken:r=!1}=e;this.apiToken=t,this.autoRefreshToken=r,this.authURL=mU,this.sessionToken=null,this.sessionOptions=i,this._tokenRefreshPromise=null}async fetch(e,t){this.sessionToken===null&&this.isMapTilesSession&&this.refreshToken(t),await this._tokenRefreshPromise;const i=new URL(e);i.searchParams.set("key",this.apiToken),this.sessionToken&&i.searchParams.set("session",this.sessionToken);let r=await fetch(i,t);return r.status>=400&&r.status<=499&&this.autoRefreshToken&&(await this.refreshToken(t),this.sessionToken&&i.searchParams.set("session",this.sessionToken),r=await fetch(i,t)),this.sessionToken===null&&!this.isMapTilesSession?r.json().then(a=>(this.sessionToken=gU(a),a)):r}refreshToken(e){if(this._tokenRefreshPromise===null){const t=new URL(this.authURL);t.searchParams.set("key",this.apiToken);const i={...e};this.isMapTilesSession&&(i.method="POST",i.body=JSON.stringify(this.sessionOptions),i.headers=i.headers||{},i.headers={...i.headers,"Content-Type":"application/json"}),this._tokenRefreshPromise=fetch(t,i).then(r=>{if(!r.ok)throw new Error(`GoogleCloudAuth: Failed to load data with error code ${r.status}`);return r.json()}).then(r=>(this.sessionToken=gU(r),this._tokenRefreshPromise=null,r))}return this._tokenRefreshPromise}}function gU(n){if("session"in n)return n.session;{let e=null;const t=n.root;return cF(t,i=>{if(i.content&&i.content.uri){const[,r]=i.content.uri.split("?");return e=new URLSearchParams(r).get("session"),!0}return!1}),e}}class xue{constructor(){this.creditsCount={}}_adjustAttributions(e,t){const i=this.creditsCount,r=e.split(/;/g);for(let a=0,s=r.length;a{const i=e[1];return t[1]-i}).map(e=>e[0]).join("; ")}}const yue="https://tile.googleapis.com/v1/3dtiles/root.json";class Sue{constructor({apiToken:e,sessionOptions:t=null,autoRefreshToken:i=!1,logoUrl:r=null,useRecommendedSettings:a=!0}){this.name="GOOGLE_CLOUD_AUTH_PLUGIN",this.apiToken=e,this.useRecommendedSettings=a,this.logoUrl=r,this.auth=new _ue({apiToken:e,autoRefreshToken:i,sessionOptions:t}),this.tiles=null,this._visibilityChangeCallback=null,this._attributionsManager=new xue,this._logoAttribution={value:"",type:"image",collapsible:!1},this._attribution={value:"",type:"string",collapsible:!0}}init(e){const{useRecommendedSettings:t,auth:i}=this;e.resetFailedTiles(),e.rootURL==null&&(e.rootURL=yue),i.sessionOptions||(i.authURL=e.rootURL),t&&!i.isMapTilesSession&&(e.errorTarget=20),this.tiles=e,this._visibilityChangeCallback=({tile:r,visible:a})=>{var s,o;const l=((o=(s=r.cached.metadata)==null?void 0:s.asset)==null?void 0:o.copyright)||"";a?this._attributionsManager.addAttributions(l):this._attributionsManager.removeAttributions(l)},e.addEventListener("tile-visibility-change",this._visibilityChangeCallback)}getAttributions(e){this.tiles.visibleTiles.size>0&&(this.logoUrl&&(this._logoAttribution.value=this.logoUrl,e.push(this._logoAttribution)),this._attribution.value=this._attributionsManager.toString(),e.push(this._attribution))}dispose(){this.tiles.removeEventListener("tile-visibility-change",this._visibilityChangeCallback)}async fetchData(e,t){return this.auth.fetch(e,t)}}const IM=new Me;class Tue{constructor(){this.name="UPDATE_ON_CHANGE_PLUGIN",this.tiles=null,this.needsUpdate=!1,this.cameraMatrices=new Map}init(e){this.tiles=e,this._needsUpdateCallback=()=>{this.needsUpdate=!0},this._onCameraAdd=({camera:t})=>{this.needsUpdate=!0,this.cameraMatrices.set(t,new Me)},this._onCameraDelete=({camera:t})=>{this.needsUpdate=!0,this.cameraMatrices.delete(t)},e.addEventListener("needs-update",this._needsUpdateCallback),e.addEventListener("add-camera",this._onCameraAdd),e.addEventListener("delete-camera",this._onCameraDelete),e.addEventListener("camera-resolution-change",this._needsUpdateCallback),e.cameras.forEach(t=>{this._onCameraAdd({camera:t})})}doTilesNeedUpdate(){const e=this.tiles;let t=!1;this.cameraMatrices.forEach((r,a)=>{IM.copy(e.group.matrixWorld).premultiply(a.matrixWorldInverse).premultiply(a.projectionMatrixInverse),t=t||!IM.equals(r),r.copy(IM)});const i=this.needsUpdate;return this.needsUpdate=!1,i||t}preprocessNode(){this.needsUpdate=!0}dispose(){const e=this.tiles;e.removeEventListener("camera-resolution-change",this._needsUpdateCallback),e.removeEventListener("needs-update",this._needsUpdateCallback),e.removeEventListener("add-camera",this._onCameraAdd),e.removeEventListener("delete-camera",this._onCameraDelete)}}const vU=new D;function _0(n,e){if(n.isInterleavedBufferAttribute||n.array instanceof e)return n;const t=e===Int8Array||e===Int16Array||e===Int32Array?-1:0,i=new e(n.count*n.itemSize),r=new bt(i,n.itemSize,!0),a=n.itemSize,s=n.count;for(let o=0;o{if(p.material&&r){const m=p.material;for(const v in m){const x=m[v];x&&x.isTexture&&x.generateMipmaps&&(x.generateMipmaps=!1,x.minFilter=Bt)}}if(p.geometry){const m=p.geometry,v=m.attributes;if(s){const{uv:x,uv1:S,uv2:_,uv3:T}=v;x&&(v.uv=_0(x,u)),S&&(v.uv1=_0(S,u)),_&&(v.uv2=_0(_,u)),T&&(v.uv3=_0(T,u))}if(i&&!v.normals&&m.computeVertexNormals(),o&&v.normals&&(v.normals=_0(v.normals,d)),l&&Eue(p,f),a&&m.index){const x=v.position.count,S=m.index,_=x>65535?Uint32Array:x>255?Uint16Array:Uint8Array;if(!(S.array instanceof _)){const T=new _(m.index.count);T.set(S.array);const E=new bt(T,1);m.setIndex(E)}}}})}}function lr(n,e,t){return n&&e in n?n[e]:t}function IF(n){return n!=="BOOLEAN"&&n!=="STRING"&&n!=="ENUM"}function Mue(n){return/^FLOAT/.test(n)}function xv(n){return/^VEC/.test(n)}function yv(n){return/^MAT/.test(n)}function UF(n,e,t,i=null){return yv(t)||xv(t)?i.fromArray(n,e):n[e]}function WA(n){const{type:e,componentType:t}=n;switch(e){case"SCALAR":return t==="INT64"?0n:0;case"VEC2":return new re;case"VEC3":return new D;case"VEC4":return new Pt;case"MAT2":return new oT;case"MAT3":return new Mt;case"MAT4":return new Me;case"BOOLEAN":return!1;case"STRING":return"";case"ENUM":return 0}}function _U(n,e){if(e==null)return!1;switch(n){case"SCALAR":return typeof e=="number"||typeof e=="bigint";case"VEC2":return e.isVector2;case"VEC3":return e.isVector3;case"VEC4":return e.isVector4;case"MAT2":return e.isMatrix2;case"MAT3":return e.isMatrix3;case"MAT4":return e.isMatrix4;case"BOOLEAN":return typeof e=="boolean";case"STRING":return typeof e=="string";case"ENUM":return typeof e=="number"||typeof e=="bigint"}throw new Error("ClassProperty: invalid type.")}function Fg(n,e=null){switch(n){case"INT8":return Int8Array;case"INT16":return Int16Array;case"INT32":return Int32Array;case"INT64":return BigInt64Array;case"UINT8":return Uint8Array;case"UINT16":return Uint16Array;case"UINT32":return Uint32Array;case"UINT64":return BigUint64Array;case"FLOAT32":return Float32Array;case"FLOAT64":return Float64Array}switch(e){case"BOOLEAN":return Uint8Array;case"STRING":return Uint8Array}throw new Error("ClassProperty: invalid type.")}function Aue(n,e=null){if(n.array){e=e&&Array.isArray(e)?e:[],e.length=n.count;for(let t=0,i=e.length;ts.value===r);return a===null?"":a.name}}adjustValueScaleOffset(e){return IF(this.type)?Cue(this,e):e}}class fC{constructor(e,t={},i={},r=null){this.definition=e,this.class=t[e.class],this.className=e.class,this.enums=i,this.data=r,this.name="name"in e?e.name:null,this.properties=null}getPropertyNames(){return Object.keys(this.class.properties)}includesData(e){return!!this.definition.properties[e]}dispose(){}_initProperties(e=RT){const t={};for(const i in this.class.properties)t[i]=new e(this.enums,this.class.properties[i],this.definition.properties[i]);this.properties=t}}class Nue extends RT{constructor(e,t,i=null){super(e,t,i),this.attribute=(i==null?void 0:i.attribute)??null}}class Oue extends fC{constructor(...e){super(...e),this.isPropertyAttributeAccessor=!0,this._initProperties(Nue)}getData(e,t,i={}){const r=this.properties;iS(r,i);for(const a in r)i[a]=this.getPropertyValue(a,e,t,i[a]);return i}getPropertyValue(e,t,i,r=null){if(t>=this.count)throw new Error("PropertyAttributeAccessor: Requested index is outside the range of the buffer.");const a=this.properties[e],s=a.type;if(a){if(!this.definition.properties[e])return a.resolveDefault(r)}else throw new Error("PropertyAttributeAccessor: Requested class property does not exist.");r=a.shapeToProperty(r);const o=i.getAttribute(a.attribute.toLowerCase());if(yv(s)){const l=r.elements;for(let u=0,d=l.length;u>x&1)===1}return r}getPropertyValue(e,t,i=null){if(t>=this.count)throw new Error("PropertyTableAccessor: Requested index is outside the range of the table.");const r=this.properties[e];if(r){if(!this.definition.properties[e])return r.resolveDefault(i)}else throw new Error("PropertyTableAccessor: Requested property does not exist.");const a=r.array,s=this.data,o=r.getArrayLengthFromId(s,t);if(i=r.shapeToProperty(i,o),a)for(let l=0,u=i.length;l{e!=="constructor"&&(this[e]=(...t)=>(n=n||new xU,n[e](...t)))})}},yU=new re,SU=new re,TU=new re;function Uue(n,e){return e===0?n.getAttribute("uv"):n.getAttribute(`uv${e}`)}function PF(n,e,t=new Array(3)){let i=3*e,r=3*e+1,a=3*e+2;return n.index&&(i=n.index.getX(i),r=n.index.getX(r),a=n.index.getX(a)),t[0]=i,t[1]=r,t[2]=a,t}function zF(n,e,t,i,r){const[a,s,o]=i,l=Uue(n,e);yU.fromBufferAttribute(l,a),SU.fromBufferAttribute(l,s),TU.fromBufferAttribute(l,o),r.set(0,0,0).addScaledVector(yU,t.x).addScaledVector(SU,t.y).addScaledVector(TU,t.z)}function BF(n,e,t,i){const r=n.x-Math.floor(n.x),a=n.y-Math.floor(n.y),s=Math.floor(r*e%e),o=Math.floor(a*t%t);return i.set(s,o),i}const EU=new re,bU=new re,MU=new re;class Pue extends RT{constructor(e,t,i=null){super(e,t,i),this.channels=lr(i,"channels",[0]),this.index=lr(i,"index",null),this.texCoord=lr(i,"texCoord",null),this.valueLength=parseInt(this.type.replace(/[^0-9]/g,""))||1}readDataFromBuffer(e,t,i=null){const r=this.type;if(r==="BOOLEAN"||r==="STRING")throw new Error("PropertyTextureAccessor: BOOLEAN and STRING types not supported.");return UF(e,t*this.valueLength,r,i)}}class zue extends fC{constructor(...e){super(...e),this.isPropertyTextureAccessor=!0,this._asyncRead=!1,this._initProperties(Pue)}getData(e,t,i,r={}){const a=this.properties;iS(a,r);const s=Object.keys(a),o=s.map(l=>r[l]);return this.getPropertyValuesAtTexel(s,e,t,i,o),s.forEach((l,u)=>r[l]=o[u]),r}async getDataAsync(e,t,i,r={}){const a=this.properties;iS(a,r);const s=Object.keys(a),o=s.map(l=>r[l]);return await this.getPropertyValuesAtTexelAsync(s,e,t,i,o),s.forEach((l,u)=>r[l]=o[u]),r}getPropertyValuesAtTexelAsync(...e){this._asyncRead=!0;const t=this.getPropertyValuesAtTexel(...e);return this._asyncRead=!1,t}getPropertyValuesAtTexel(e,t,i,r,a=[]){for(;a.length(f.call(this),a));return Pc.readData(d),f.call(this),a;function f(){for(let p=0,m=e.length;pd[4*p+w]),E=x.componentType,b=Fg(E,S),R=new b(_);if(new Uint8Array(R.buffer).set(T),x.array){const w=a[p];for(let L=0,U=w.length;L{e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())})}}class AU{constructor(e,t,i,r=null,a=null){const{schema:s,propertyTables:o=[],propertyTextures:l=[],propertyAttributes:u=[]}=e,{enums:d,classes:f}=s,p=o.map(x=>new Iue(x,f,d,i));let m=[],v=[];r&&(r.propertyTextures&&(m=r.propertyTextures.map(x=>new zue(l[x],f,d,t))),r.propertyAttributes&&(v=r.propertyAttributes.map(x=>new Oue(u[x],f,d)))),this.schema=s,this.tableAccessors=p,this.textureAccessors=m,this.attributeAccessors=v,this.object=a,this.textures=t,this.nodeMetadata=r}getPropertyTableData(e,t,i=null){if(!Array.isArray(e)||!Array.isArray(t))i=i||{},i=this.tableAccessors[e].getData(t,i);else{i=i||[];const r=Math.min(e.length,t.length);i.length=r;for(let a=0;ai)),Array.isArray(e))return e.map(t=>{const i=this.tableAccessors[t];return{name:i.name,className:i.definition.class}});{const t=this.tableAccessors[e];return{name:t.name,className:t.definition.class}}}getPropertyTextureData(e,t,i=[]){const r=this.textureAccessors;i.length=r.length;for(let a=0;a{i[s]=l});a.push(o)}return await Promise.all(a),i}getPropertyTextureInfo(){return this.textureAccessors}getPropertyAttributeData(e,t=[]){const i=this.attributeAccessors;t.length=i.length;for(let r=0;r({name:e.name,className:e.definition.class}))}dispose(){this.textureAccessors.forEach(e=>e.dispose()),this.tableAccessors.forEach(e=>e.dispose()),this.attributeAccessors.forEach(e=>e.dispose())}}const y0="EXT_structural_metadata";function Bue(n,e=[]){var t;const i=((t=n.json.textures)==null?void 0:t.length)||0,r=new Array(i).fill(null);return e.forEach(({properties:a})=>{for(const s in a){const{index:o}=a[s];r[o]===null&&(r[o]=n.loadTexture(o))}}),Promise.all(r)}function Fue(n,e=[]){var t;const i=((t=n.json.bufferViews)==null?void 0:t.length)||0,r=new Array(i).fill(null);return e.forEach(({properties:a})=>{for(const s in a){const{values:o,arrayOffsets:l,stringOffsets:u}=a[s];r[o]===null&&(r[o]=n.loadBufferView(o)),r[l]===null&&(r[l]=n.loadBufferView(l)),r[u]===null&&(r[u]=n.loadBufferView(u))}}),Promise.all(r)}class Hue{constructor(e){this.parser=e,this.name=y0}async afterRoot({scene:e,parser:t}){const i=t.json.extensionsUsed;if(!i||!i.includes(y0))return;let r=null,a=t.json.extensions[y0];if(a.schemaUri){const{manager:u,path:d,requestHeader:f,crossOrigin:p}=t.options,m=new URL(a.schemaUri,d).toString(),v=new jr(u);v.setCrossOrigin(p),v.setResponseType("json"),v.setRequestHeader(f),r=v.loadAsync(m).then(x=>{a={...a,schema:x}})}const[s,o]=await Promise.all([Bue(t,a.propertyTextures),Fue(t,a.propertyTables),r]),l=new AU(a,s,o);e.userData.structuralMetadata=l,e.traverse(u=>{var d;if(t.associations.has(u)){const{meshes:f,primitives:p}=t.associations.get(u),m=(d=t.json.meshes[f])==null?void 0:d.primitives[p];if(m&&m.extensions&&m.extensions[y0]){const v=m.extensions[y0];u.userData.structuralMetadata=new AU(a,s,o,v,u)}else u.userData.structuralMetadata=l}})}}const wU=new re,RU=new re,CU=new re;function Vue(n){return n.x>n.y&&n.x>n.z?0:n.y>n.z?1:2}class Gue{constructor(e,t,i){this.geometry=e,this.textures=t,this.data=i,this._asyncRead=!1,this.featureIds=i.featureIds.map(r=>{const{texture:a,...s}=r,o={label:null,propertyTable:null,nullFeatureId:null,...s};return a&&(o.texture={texCoord:0,channels:[0],...a}),o})}getTextures(){return this.textures}getFeatureInfo(){return this.featureIds}getFeaturesAsync(...e){this._asyncRead=!0;const t=this.getFeatures(...e);return this._asyncRead=!1,t}getFeatures(e,t){const{geometry:i,textures:r,featureIds:a}=this,s=new Array(a.length).fill(null),o=a.length;Pc.increaseSizeTo(o);const l=PF(i,e),u=l[Vue(t)];for(let p=0,m=a.length;p(f(),s));return Pc.readData(d),f(),s;function f(){const p=new Uint32Array(1);for(let m=0,v=a.length;md[4*m+b]);new Uint8Array(p.buffer).set(T);const E=p[0];E!==S&&(s[m]=E)}}}}dispose(){this.textures.forEach(e=>{e&&(e.dispose(),e.image instanceof ImageBitmap&&e.image.close())})}}const rS="EXT_mesh_features";function DU(n,e,t){n.traverse(i=>{var r;if(e.associations.has(i)){const{meshes:a,primitives:s}=e.associations.get(i),o=(r=e.json.meshes[a])==null?void 0:r.primitives[s];o&&o.extensions&&o.extensions[rS]&&t(i,o.extensions[rS])}})}class kue{constructor(e){this.parser=e,this.name=rS}async afterRoot({scene:e,parser:t}){var i;const r=t.json.extensionsUsed;if(!r||!r.includes(rS))return;const a=((i=t.json.textures)==null?void 0:i.length)||0,s=new Array(a).fill(null);DU(e,t,(l,{featureIds:u})=>{u.forEach(d=>{if(d.texture&&s[d.texture.index]===null){const f=d.texture.index;s[f]=t.loadTexture(f)}})});const o=await Promise.all(s);DU(e,t,(l,u)=>{l.userData.meshFeatures=new Gue(l.geometry,o,u)})}}class Wue{constructor(){this.name="CESIUM_RTC"}afterRoot(e){if(e.parser.json.extensions&&e.parser.json.extensions.CESIUM_RTC){const{center:t}=e.parser.json.extensions.CESIUM_RTC;t&&(e.scene.position.x+=t[0],e.scene.position.y+=t[1],e.scene.position.z+=t[2])}}}class Xue{constructor(e){e={metadata:!0,rtc:!0,plugins:[],dracoLoader:null,ktxLoader:null,meshoptDecoder:null,autoDispose:!0,...e},this.tiles=null,this.metadata=e.metadata,this.rtc=e.rtc,this.plugins=e.plugins,this.dracoLoader=e.dracoLoader,this.ktxLoader=e.ktxLoader,this.meshoptDecoder=e.meshoptDecoder,this._gltfRegex=/\.(gltf|glb)$/g,this._dracoRegex=/\.drc$/g,this._loader=null}init(e){const t=new Lp(e.manager);this.dracoLoader&&(t.setDRACOLoader(this.dracoLoader),e.manager.addHandler(this._dracoRegex,this.dracoLoader)),this.ktxLoader&&t.setKTX2Loader(this.ktxLoader),this.meshoptDecoder&&t.setMeshoptDecoder(this.meshoptDecoder),this.rtc&&t.register(()=>new Wue),this.metadata&&(t.register(()=>new Hue),t.register(()=>new kue)),this.plugins.forEach(i=>t.register(i)),e.manager.addHandler(this._gltfRegex,t),this.tiles=e,this._loader=t}dispose(){this.tiles.manager.removeHandler(this._gltfRegex),this.tiles.manager.removeHandler(this._dracoRegex),this.autoDispose&&(this.ktxLoader.dispose(),this.dracoLoader.dispose())}}const{clamp:UM}=lt;class que{constructor(){this.duration=250,this.fadeCount=0,this._lastTick=-1,this._fadeState=new Map,this.onFadeComplete=null,this.onFadeStart=null,this.onFadeSetComplete=null,this.onFadeSetStart=null}deleteObject(e){e&&this.completeFade(e)}guaranteeState(e){const t=this._fadeState;if(t.has(e))return!1;const i={fadeInTarget:0,fadeOutTarget:0,fadeIn:0,fadeOut:0};return t.set(e,i),!0}completeFade(e){const t=this._fadeState;if(!t.has(e))return;const i=t.get(e).fadeOutTarget===0;t.delete(e),this.fadeCount--,this.onFadeComplete&&this.onFadeComplete(e,i),this.fadeCount===0&&this.onFadeSetComplete&&this.onFadeSetComplete()}completeAllFades(){this._fadeState.forEach((e,t)=>{this.completeFade(t)})}forEachObject(e){this._fadeState.forEach((t,i)=>{e(i,t)})}fadeIn(e){const t=this.guaranteeState(e),i=this._fadeState.get(e);i.fadeInTarget=1,i.fadeOutTarget=0,i.fadeOut=0,t&&(this.fadeCount++,this.fadeCount===1&&this.onFadeSetStart&&this.onFadeSetStart(),this.onFadeStart&&this.onFadeStart(e))}fadeOut(e){const t=this.guaranteeState(e),i=this._fadeState.get(e);i.fadeOutTarget=1,t&&(i.fadeInTarget=1,i.fadeIn=1,this.fadeCount++,this.fadeCount===1&&this.onFadeSetStart&&this.onFadeSetStart(),this.onFadeStart&&this.onFadeStart(e))}isFading(e){return this._fadeState.has(e)}isFadingOut(e){const t=this._fadeState.get(e);return t&&t.fadeOutTarget===1}update(){const e=window.performance.now();this._lastTick===-1&&(this._lastTick=e);const t=UM((e-this._lastTick)/this.duration,0,1);this._lastTick=e,this._fadeState.forEach((i,r)=>{const{fadeOutTarget:a,fadeInTarget:s}=i;let{fadeOut:o,fadeIn:l}=i;const u=Math.sign(s-l);l=UM(l+u*t,0,1);const d=Math.sign(a-o);o=UM(o+d*t,0,1),i.fadeIn=l,i.fadeOut=o,((o===1||o===0)&&(l===1||l===0)||o>=l)&&this.completeFade(r)})}}const PM=Symbol("FADE_PARAMS");function FF(n,e){if(n[PM])return n[PM];const t={fadeIn:{value:0},fadeOut:{value:0},fadeTexture:{value:null}};return n[PM]=t,n.defines={...n.defines||{},FEATURE_FADE:0},n.onBeforeCompile=i=>{e&&e(i),i.uniforms={...i.uniforms,...t},i.vertexShader=i.vertexShader.replace(/void\s+main\(\)\s+{/,r=>` + #ifdef USE_BATCHING_FRAG + + varying float vBatchId; + + #endif + + ${r} + + #ifdef USE_BATCHING_FRAG + + // add 0.5 to the value to avoid floating error that may cause flickering + vBatchId = getIndirectIndex( gl_DrawID ) + 0.5; + + #endif + `),i.fragmentShader=i.fragmentShader.replace(/void main\(/,r=>` + #if FEATURE_FADE + + // adapted from https://www.shadertoy.com/view/Mlt3z8 + float bayerDither2x2( vec2 v ) { + + return mod( 3.0 * v.y + 2.0 * v.x, 4.0 ); + + } + + float bayerDither4x4( vec2 v ) { + + vec2 P1 = mod( v, 2.0 ); + vec2 P2 = floor( 0.5 * mod( v, 4.0 ) ); + return 4.0 * bayerDither2x2( P1 ) + bayerDither2x2( P2 ); + + } + + // the USE_BATCHING define is not available in fragment shaders + #ifdef USE_BATCHING_FRAG + + // functions for reading the fade state of a given batch id + uniform sampler2D fadeTexture; + varying float vBatchId; + vec2 getFadeValues( const in float i ) { + + int size = textureSize( fadeTexture, 0 ).x; + int j = int( i ); + int x = j % size; + int y = j / size; + return texelFetch( fadeTexture, ivec2( x, y ), 0 ).rg; + + } + + #else + + uniform float fadeIn; + uniform float fadeOut; + + #endif + + #endif + + ${r} + `).replace(/#include /,r=>` + + ${r} + + #if FEATURE_FADE + + #ifdef USE_BATCHING_FRAG + + vec2 fadeValues = getFadeValues( vBatchId ); + float fadeIn = fadeValues.r; + float fadeOut = fadeValues.g; + + #endif + + float bayerValue = bayerDither4x4( floor( mod( gl_FragCoord.xy, 4.0 ) ) ); + float bayerBins = 16.0; + float dither = ( 0.5 + bayerValue ) / bayerBins; + if ( dither >= fadeIn ) { + + discard; + + } + + if ( dither < fadeOut ) { + + discard; + + } + + #endif + + `)},t}class Yue{constructor(){this._fadeParams=new WeakMap,this.fading=0}setFade(e,t,i){if(!e)return;const r=this._fadeParams;e.traverse(a=>{const s=a.material;if(s&&r.has(s)){const o=r.get(s);o.fadeIn.value=t,o.fadeOut.value=i;const l=+(!(t===0||t===1)||!(i===0||i===1));s.defines.FEATURE_FADE!==l&&(this.fading+=l===1?1:-1,s.defines.FEATURE_FADE=l,s.needsUpdate=!0)}})}prepareScene(e){e.traverse(t=>{t.material&&this.prepareMaterial(t.material)})}deleteScene(e){if(!e)return;this.setFade(e,1,0);const t=this._fadeParams;e.traverse(i=>{const r=i.material;r&&t.delete(r)})}prepareMaterial(e){const t=this._fadeParams;t.has(e)||t.set(e,FF(e,e.onBeforeCompile))}}class jue{constructor(e,t=new Sr){this.other=e,this.material=t,this.visible=!0,this.parent=null,this._instanceInfo=[],this._visibilityChanged=!0;const i=new Proxy(this,{get(r,a){if(a in r)return r[a];{const s=e[a];return s instanceof Function?(...o)=>(r.syncInstances(),s.call(i,...o)):e[a]}},set(r,a,s){return a in r?r[a]=s:e[a]=s,!0},deleteProperty(r,a){return a in r?delete r[a]:delete e[a]}});return i}syncInstances(){const e=this._instanceInfo,t=this.other._instanceInfo;for(;t.length>e.length;){const i=e.length;e.push(new Proxy({visible:!1},{get(r,a){return a in r?r[a]:t[i][a]},set(r,a,s){return a in r?r[a]=s:t[i][a]=s,!0}}))}}}class Zue extends jue{constructor(...e){super(...e);const t=this.material,i=FF(t,t.onBeforeCompile);t.defines.FEATURE_FADE=1,t.defines.USE_BATCHING_FRAG=1,t.needsUpdate=!0,this.fadeTexture=null,this._fadeParams=i}setFadeAt(e,t,i){this._initFadeTexture(),this.fadeTexture.setValueAt(e,t*255,i*255)}_initFadeTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);const t=e*e*2,i=this.fadeTexture;if(!i||i.image.data.length!==t){const r=new Uint8Array(t),a=new Que(r,e,e,Mo,Ni);if(i){i.dispose();const s=i.image.data,o=this.fadeTexture.image.data,l=Math.min(s.length,o.length);o.set(new s.constructor(s.buffer,0,l))}this.fadeTexture=a,this._fadeParams.fadeTexture.value=a,a.needsUpdate=!0}}dispose(){this.fadeTexture&&this.fadeTexture.dispose()}}class Que extends Ur{setValueAt(e,...t){const{data:i,width:r,height:a}=this.image,s=Math.floor(i.length/(r*a));let o=!1;for(let l=0;l{const f=d.cached.scene;f&&(f.visible=d.__inFrustum),this.forEachBatchIds(d,(p,m,v)=>{m.setVisibleAt(p,d.__inFrustum),v.batchedMesh.setVisibleAt(p,d.__inFrustum)})}),s{if(!r.has(f))return;const p=f.matrixWorld,m=r.get(f);p.decompose(LU,UU,PU),m.decompose(OU,IU,PU);const v=UU.angleTo(IU),x=LU.distanceTo(OU);d=d&&(v>.25||x>.1)}),d&&n.completeAllFades()}if(l.forEach(d=>{r.get(d).copy(d.matrixWorld)}),n.forEachObject((d,{fadeIn:f,fadeOut:p})=>{const m=d.cached.scene,v=n.isFadingOut(d);a.markTileUsed(d),m&&(e.setFade(m,f,p),v&&(m.visible=!0)),this.forEachBatchIds(d,(x,S,_)=>{S.setFadeAt(x,f,p),S.setVisibleAt(x,!0),_.batchedMesh.setVisibleAt(x,!1)})}),o){const d=a.getPluginByName("BATCHED_TILES_PLUGIN").batchedMesh.material;o.material.map=d.map}}class $ue{get fadeDuration(){return this._fadeManager.duration}set fadeDuration(e){this._fadeManager.duration=Number(e)}get fadingTiles(){return this._fadeManager.fadeCount}constructor(e){e={maximumFadeOutTiles:50,fadeRootTiles:!1,fadeDuration:250,...e},this.name="FADE_TILES_PLUGIN",this.priority=-2,this.tiles=null,this.batchedMesh=null,this._quickFadeTiles=new Set,this._fadeManager=new que,this._fadeMaterialManager=new Yue,this._prevCameraTransforms=null,this._fadingOutCount=0,this.maximumFadeOutTiles=e.maximumFadeOutTiles,this.fadeRootTiles=e.fadeRootTiles,this.fadeDuration=e.fadeDuration}init(e){this._onLoadModel=({scene:r})=>{this._fadeMaterialManager.prepareScene(r)},this._onDisposeModel=({tile:r,scene:a})=>{this.tiles.visibleTiles.has(r)&&this._quickFadeTiles.add(r.parent),this._fadeManager.deleteObject(r),this._fadeMaterialManager.deleteScene(a)},this._onAddCamera=({camera:r})=>{this._prevCameraTransforms.set(r,new Me)},this._onDeleteCamera=({camera:r})=>{this._prevCameraTransforms.delete(r)},this._onTileVisibilityChange=({tile:r,visible:a})=>{const s=r.cached.scene;s&&(s.visible=!0),this.forEachBatchIds(r,(o,l,u)=>{l.setFadeAt(o,0,0),l.setVisibleAt(o,!1),u.batchedMesh.setVisibleAt(o,!1)})},this._onUpdateBefore=()=>{Kue.call(this)},this._onUpdateAfter=()=>{Jue.call(this)},e.addEventListener("load-model",this._onLoadModel),e.addEventListener("dispose-model",this._onDisposeModel),e.addEventListener("add-camera",this._onAddCamera),e.addEventListener("delete-camera",this._onDeleteCamera),e.addEventListener("update-before",this._onUpdateBefore),e.addEventListener("update-after",this._onUpdateAfter),e.addEventListener("tile-visibility-change",this._onTileVisibilityChange);const t=this._fadeManager;t.onFadeSetStart=()=>{e.dispatchEvent({type:"fade-start"}),e.dispatchEvent({type:"needs-render"})},t.onFadeSetComplete=()=>{e.dispatchEvent({type:"fade-end"}),e.dispatchEvent({type:"needs-render"})},t.onFadeComplete=(r,a)=>{this._fadeMaterialManager.setFade(r.cached.scene,0,0),this.forEachBatchIds(r,(s,o,l)=>{o.setFadeAt(s,0,0),o.setVisibleAt(s,!1),l.batchedMesh.setVisibleAt(s,a)}),a||(e.invokeOnePlugin(s=>s!==this&&s.setTileVisible&&s.setTileVisible(r,!1)),this._fadingOutCount--)};const i=new Map;e.cameras.forEach(r=>{i.set(r,new Me)}),e.forEachLoadedModel((r,a)=>{this._onLoadModel({scene:r})}),this.tiles=e,this._fadeManager=t,this._prevCameraTransforms=i}initBatchedMesh(){var e;const t=(e=this.tiles.getPluginByName("BATCHED_TILES_PLUGIN"))==null?void 0:e.batchedMesh;if(t){if(this.batchedMesh===null){this._onBatchedMeshDispose=()=>{this.batchedMesh.dispose(),this.batchedMesh.removeFromParent(),this.batchedMesh=null,t.removeEventListener("dispose",this._onBatchedMeshDispose)};const i=t.material.clone();i.onBeforeCompile=t.material.onBeforeCompile,this.batchedMesh=new Zue(t,i),this.tiles.group.add(this.batchedMesh)}}else this.batchedMesh!==null&&(this._onBatchedMeshDispose(),this._onBatchedMeshDispose=null)}setTileVisible(e,t){const i=this._fadeManager,r=i.isFading(e);if(i.isFadingOut(e)&&this._fadingOutCount--,t?e.__depthFromRenderedParent===1?((e[NU]||this.fadeRootTiles)&&this._fadeManager.fadeIn(e),e[NU]=!0):this._fadeManager.fadeIn(e):(this._fadingOutCount++,i.fadeOut(e)),this._quickFadeTiles.has(e)&&(this._fadeManager.completeFade(e),this._quickFadeTiles.delete(e)),r)return!0;const a=this._fadeManager.isFading(e);return!!(!t&&a)}dispose(){const e=this.tiles;this._fadeManager.completeAllFades(),this.batchedMesh!==null&&this._onBatchedMeshDispose(),e.removeEventListener("load-model",this._onLoadModel),e.removeEventListener("dispose-model",this._onDisposeModel),e.removeEventListener("add-camera",this._onAddCamera),e.removeEventListener("delete-camera",this._onDeleteCamera),e.removeEventListener("update-before",this._onUpdateBefore),e.removeEventListener("update-after",this._onUpdateAfter),e.removeEventListener("tile-visibility-change",this._onTileVisibilityChange),e.forEachLoadedModel((t,i)=>{this._fadeManager.deleteObject(i),t&&(t.visible=!0)})}forEachBatchIds(e,t){if(this.initBatchedMesh(),this.batchedMesh){const i=this.tiles.getPluginByName("BATCHED_TILES_PLUGIN"),r=i.getTileBatchIds(e);r&&r.forEach(a=>{t(a,this.batchedMesh,i)})}}}new Me;new D;new D;new jn;new Gz(new Sr);const ehe=new Ur(new Uint8Array([255,255,255,255]),1,1);ehe.needsUpdate=!0;new D;const zM=new WeakMap;class the extends wi{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,i,r){const a=new jr(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,s=>{this.parse(s,t,r)},i,r)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,mn,i).catch(i)}decodeDracoFile(e,t,i,r,a=Xn,s=()=>{}){const o={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:r||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:a};return this.decodeGeometry(e,o).then(t).catch(s)}decodeGeometry(e,t){const i=JSON.stringify(t);if(zM.has(e)){const l=zM.get(e);if(l.key===i)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let r;const a=this.workerNextTaskID++,s=e.byteLength,o=this._getWorker(a,s).then(l=>(r=l,new Promise((u,d)=>{r._callbacks[a]={resolve:u,reject:d},r.postMessage({type:"decode",id:a,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{r&&a&&this._releaseTask(r,a)}),zM.set(e,{key:i,promise:o}),o}_createGeometry(e){const t=new Ct;e.index&&t.setIndex(new bt(e.index.array,1));for(let i=0;i{i.load(e,r,void 0,a)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const r=i[0];e||(this.decoderConfig.wasmBinary=i[1]);const a=nhe.toString(),s=["/* draco decoder */",r,"","/* worker */",a.substring(a.indexOf("{")+1,a.lastIndexOf("}"))].join(` +`);this.workerSourceURL=URL.createObjectURL(new Blob([s]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.lengtha._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e{const f=d.draco,p=new f.Decoder;try{const m=t(f,p,new Int8Array(l),u),v=m.attributes.map(x=>x.array.buffer);m.index&&v.push(m.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:m},v)}catch(m){console.error(m),self.postMessage({type:"error",id:o.id,error:m.message})}finally{f.destroy(p)}});break}};function t(s,o,l,u){const d=u.attributeIDs,f=u.attributeTypes;let p,m;const v=o.GetEncodedGeometryType(l);if(v===s.TRIANGULAR_MESH)p=new s.Mesh,m=o.DecodeArrayToMesh(l,l.byteLength,p);else if(v===s.POINT_CLOUD)p=new s.PointCloud,m=o.DecodeArrayToPointCloud(l,l.byteLength,p);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!m.ok()||p.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+m.error_msg());const x={index:null,attributes:[]};for(const S in d){const _=self[f[S]];let T,E;if(u.useUniqueIDs)E=d[S],T=o.GetAttributeByUniqueId(p,E);else{if(E=o.GetAttributeId(p,s[d[S]]),E===-1)continue;T=o.GetAttribute(p,E)}const b=r(s,o,p,S,_,T);S==="color"&&(b.vertexColorSpace=u.vertexColorSpace),x.attributes.push(b)}return v===s.TRIANGULAR_MESH&&(x.index=i(s,o,p)),s.destroy(p),x}function i(s,o,l){const d=l.num_faces()*3,f=d*4,p=s._malloc(f);o.GetTrianglesUInt32Array(l,f,p);const m=new Uint32Array(s.HEAPF32.buffer,p,d).slice();return s._free(p),{array:m,itemSize:1}}function r(s,o,l,u,d,f){const p=l.num_points(),m=f.num_components(),v=a(s,d),x=m*d.BYTES_PER_ELEMENT,S=Math.ceil(x/4)*4,_=S/d.BYTES_PER_ELEMENT,T=p*x,E=p*S,b=s._malloc(T);o.GetAttributeDataArrayForAllPoints(l,f,v,T,b);const R=new d(s.HEAPF32.buffer,b,T/d.BYTES_PER_ELEMENT);let w;if(x===S)w=R.slice();else{w=new d(E/d.BYTES_PER_ELEMENT);let L=0;for(let U=0,N=R.length;U Altitude: ${a}, TruePosLength: ${u.length()}`),Or.position.copy(u);const f=pC(u).clone().invert();Or.quaternion.copy(f.multiply(o))}const On={w:!1,a:!1,s:!1,d:!1,q:!1,e:!1,Shift:!1,Space:!1};typeof window<"u"&&(window.addEventListener("keydown",n=>{const e=n.key.toLowerCase();On.hasOwnProperty(e)&&(On[e]=!0),n.key==="Shift"&&(On.Shift=!0),n.key===" "&&(On.Space=!0)}),window.addEventListener("keyup",n=>{const e=n.key.toLowerCase();On.hasOwnProperty(e)&&(On[e]=!1),n.key==="Shift"&&(On.Shift=!1),n.key===" "&&(On.Space=!1)}));const HF=new the;HF.setDecoderPath("https://www.gstatic.com/draco/v1/decoders/");function hhe(){const n="AIzaSyB1HccB6XdNjxbYcbbmMWRyxv4CTYfxXpM";return ot.jsxs(fue,{url:`https://tile.googleapis.com/v1/3dtiles/root.json?key=${n}`,children:[ot.jsx(g0,{plugin:Sue,args:{apiToken:n}}),ot.jsx(g0,{plugin:Xue,dracoLoader:HF}),ot.jsx(g0,{plugin:bue}),ot.jsx(g0,{plugin:Tue}),ot.jsx(g0,{plugin:$ue})]})}function dhe(){const{gl:n}=pn(),e=ie.useRef(),t=ie.useRef(),i=ie.useRef(new Date(ohe)),[r,a]=ie.useState(zU[1]);return ie.useEffect(()=>{n.toneMapping=As,n.toneMappingExposure=10},[n]),ie.useEffect(()=>{const s=setInterval(()=>{a(o=>{const l=zU.filter(d=>d.name!==o.name),u=l[Math.floor(Math.random()*l.length)];return console.log(`[Weather] Changing to: ${u.name}`),u})},ahe);return()=>clearInterval(s)},[]),_a((s,o)=>{const l=i.current,u=o*she*1e3;if(l.setTime(l.getTime()+u),t.current&&t.current.updateByDate(l),e.current){const d=l.getHours()+l.getMinutes()/60+l.getSeconds()/3600,f=lt.mapLinear(d,6,18,0,Math.PI),p=-Math.cos(f),m=Math.sin(f);d<6||d>18?(e.current.position.set(0,-1,0),e.current.intensity=10):(e.current.position.set(p,m,.2),e.current.intensity=lt.lerp(.5,3,m))}}),ot.jsxs(ot.Fragment,{children:[ot.jsx(Bz,{makeDefault:!0,near:1,far:1e7,fov:45}),ot.jsx(fhe,{}),ot.jsx("directionalLight",{ref:e,position:[0,1,0],intensity:3,castShadow:!0}),ot.jsxs(lle,{ref:t,children:[ot.jsx(hhe,{}),ot.jsxs(Vre,{multisampling:0,disableNormalPass:!1,children:[ot.jsx(mce,{disableDefaultLayers:!0,coverage:r.coverage,children:r.layers.map((s,o)=>ot.jsx(gce,{channel:s.channel,altitude:s.altitude,height:s.height,densityScale:s.densityScale,shapeAmount:.5},o))}),ot.jsx(ule,{sky:!0,sunLight:!0,skyLight:!0}),ot.jsx(Wre,{mode:ca.AGX})]})]})]})}function fhe(){return _a(n=>{if(!Or.position)return;const e=pC(Or.position);n.camera.position.copy(Or.position),n.camera.quaternion.copy(e).multiply(Or.quaternion)}),null}function phe(){const n=ie.useRef(null),e=ie.useRef(null),{camera:t}=pn(),i=ie.useRef({}),r=ie.useRef(null),a=By(Lp,ihe,u=>{u.register(d=>new Ine(d))}),[s,o,l]=By(Lp,[`${v1}fly.vrma`,`${v1}fly_stop.vrma`,`${v1}fly_idle.vrma`],u=>{u.register(d=>new gie(d))});return ie.useEffect(()=>{const u=a.userData.vrm;e.current=u,rd.removeUnnecessaryJoints(u.scene),u.humanoid.resetPose(),u.scene.rotation.y=Math.PI;const d=new b7(u.scene);n.current=d;const f=(S,_)=>{var T;if((T=S.userData.vrmAnimations)!=null&&T[0]){const E=uie(S.userData.vrmAnimations[0],u),b=d.clipAction(E);return b.name=_,b}return null},p=f(s,"fly"),m=f(o,"fly_stop"),v=f(l,"fly_idle");i.current={fly:p,fly_stop:m,fly_idle:v},m&&(m.setLoop($w),m.clampWhenFinished=!0),v?(v.play(),r.current="fly_idle"):p&&(p.play(),r.current="fly");const x=S=>{S.action===m&&i.current.fly_idle&&(m.fadeOut(.5),i.current.fly_idle.reset().fadeIn(.5).play(),r.current="fly_idle")};return d.addEventListener("finished",x),()=>{d.removeEventListener("finished",x)}},[a,s,o,l]),_a((u,d)=>{var v,x;(v=n.current)==null||v.update(d),(x=e.current)==null||x.update(d);const f=On.w||On.s||On.a||On.d,p=i.current,m=r.current;if(p.fly&&p.fly_stop&&p.fly_idle)if(f){if(m!=="fly"){const S=p[m];S&&S.fadeOut(.5),p.fly.reset().fadeIn(.5).play(),r.current="fly"}}else m==="fly"&&(p.fly.fadeOut(.5),p.fly_stop.reset().fadeIn(.5).play(),r.current="fly_stop");if(e.current){const S=e.current.scene,_=new D(0,0,0);if(On.w&&(_.z-=1),On.s&&(_.z+=1),On.a&&(_.x-=1),On.d&&(_.x+=1),_.lengthSq()>0){_.normalize();const T=t.quaternion.clone();_.applyQuaternion(T);const E=S.position.clone().sub(_),b=new Xt;b.position.copy(S.position),b.lookAt(E),S.quaternion.slerp(b.quaternion,10*d)}}}),ot.jsx("primitive",{object:a.scene})}function mhe(){const{camera:n}=pn();new D;const e=ie.useRef(0),t=10,i=2;return _a((r,a)=>{Or.quaternion.copy(n.quaternion);const s=pC(Or.position),o=On.w||On.s||On.a||On.d||On.q||On.e,l=Or.speed*(On.Shift?2:1)*a,u=new D;On.w&&(u.z-=1),On.s&&(u.z+=1),On.a&&(u.x-=1),On.d&&(u.x+=1);const d=Or.position.clone().normalize();On.e&&Or.position.addScaledVector(d,l),On.q&&Or.position.addScaledVector(d,-l),u.lengthSq()>0&&(u.normalize(),u.applyQuaternion(n.quaternion),u.applyQuaternion(s),Or.position.addScaledVector(u,l));const f=Or.position.length(),p=che(Or.position),m=p+10;r.clock.elapsedTime%1<.02&&console.log(`[CameraSync] Dist: ${f.toFixed(1)}, LocalR: ${p.toFixed(1)}, Alt: ${(f-p).toFixed(1)}`),fot.jsx("button",{onClick:()=>uhe(n),style:{padding:"10px 20px",background:"rgba(0, 0, 0, 0.6)",color:"white",border:"1px solid rgba(255, 255, 255, 0.3)",borderRadius:"8px",cursor:"pointer",fontSize:"14px",backdropFilter:"blur(4px)",transition:"background 0.2s"},onMouseOver:e=>e.currentTarget.style.background="rgba(0, 0, 0, 0.8)",onMouseOut:e=>e.currentTarget.style.background="rgba(0, 0, 0, 0.6)",children:n.name},n.name))})}function _he(){return ot.jsx(hz,{children:ot.jsx(dhe,{})})}function xhe(){const n={position:"absolute",top:0,left:0,width:"100%",height:"100%"};return ot.jsxs("div",{style:{position:"relative",width:"100vw",height:"100vh",background:"#000"},children:[ot.jsx(vhe,{}),ot.jsx("div",{style:{...n,zIndex:0},children:ot.jsx(_he,{})}),ot.jsx("div",{style:{...n,zIndex:1,pointerEvents:"none"},children:ot.jsx("div",{style:{width:"100%",height:"100%",pointerEvents:"auto"},children:ot.jsx(ghe,{})})})]})}zW.createRoot(document.getElementById("root")).render(ot.jsx(QA.StrictMode,{children:ot.jsx(xhe,{})})); diff --git a/static/pkg/atmosphere/assets/index-Cc80FqGU.js b/static/pkg/atmosphere/assets/index-Cc80FqGU.js deleted file mode 100644 index be0980e5..00000000 --- a/static/pkg/atmosphere/assets/index-Cc80FqGU.js +++ /dev/null @@ -1,10326 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))i(a);new MutationObserver(a=>{for(const r of a)if(r.type==="childList")for(const s of r.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&i(s)}).observe(document,{childList:!0,subtree:!0});function t(a){const r={};return a.integrity&&(r.integrity=a.integrity),a.referrerPolicy&&(r.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?r.credentials="include":a.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(a){if(a.ep)return;a.ep=!0;const r=t(a);fetch(a.href,r)}})();function l1(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var WO={exports:{}},c1={};/** - * @license React - * react-jsx-runtime.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var hz=Symbol.for("react.transitional.element"),fz=Symbol.for("react.fragment");function XO(n,e,t){var i=null;if(t!==void 0&&(i=""+t),e.key!==void 0&&(i=""+e.key),"key"in e){t={};for(var a in e)a!=="key"&&(t[a]=e[a])}else t=e;return e=t.ref,{$$typeof:hz,type:n,key:i,ref:e!==void 0?e:null,props:t}}c1.Fragment=fz;c1.jsx=XO;c1.jsxs=XO;WO.exports=c1;var Rt=WO.exports,YO={exports:{}},Xt={};/** - * @license React - * react.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var lM=Symbol.for("react.transitional.element"),dz=Symbol.for("react.portal"),pz=Symbol.for("react.fragment"),mz=Symbol.for("react.strict_mode"),gz=Symbol.for("react.profiler"),vz=Symbol.for("react.consumer"),_z=Symbol.for("react.context"),xz=Symbol.for("react.forward_ref"),yz=Symbol.for("react.suspense"),Sz=Symbol.for("react.memo"),qO=Symbol.for("react.lazy"),Tz=Symbol.for("react.activity"),UR=Symbol.iterator;function Ez(n){return n===null||typeof n!="object"?null:(n=UR&&n[UR]||n["@@iterator"],typeof n=="function"?n:null)}var jO={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ZO=Object.assign,KO={};function zd(n,e,t){this.props=n,this.context=e,this.refs=KO,this.updater=t||jO}zd.prototype.isReactComponent={};zd.prototype.setState=function(n,e){if(typeof n!="object"&&typeof n!="function"&&n!=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,n,e,"setState")};zd.prototype.forceUpdate=function(n){this.updater.enqueueForceUpdate(this,n,"forceUpdate")};function QO(){}QO.prototype=zd.prototype;function cM(n,e,t){this.props=n,this.context=e,this.refs=KO,this.updater=t||jO}var uM=cM.prototype=new QO;uM.constructor=cM;ZO(uM,zd.prototype);uM.isPureReactComponent=!0;var PR=Array.isArray;function r3(){}var ti={H:null,A:null,T:null,S:null},JO=Object.prototype.hasOwnProperty;function hM(n,e,t){var i=t.ref;return{$$typeof:lM,type:n,key:e,ref:i!==void 0?i:null,props:t}}function Mz(n,e){return hM(n.type,e,n.props)}function fM(n){return typeof n=="object"&&n!==null&&n.$$typeof===lM}function bz(n){var e={"=":"=0",":":"=2"};return"$"+n.replace(/[=:]/g,function(t){return e[t]})}var zR=/\/+/g;function WS(n,e){return typeof n=="object"&&n!==null&&n.key!=null?bz(""+n.key):e.toString(36)}function Az(n){switch(n.status){case"fulfilled":return n.value;case"rejected":throw n.reason;default:switch(typeof n.status=="string"?n.then(r3,r3):(n.status="pending",n.then(function(e){n.status==="pending"&&(n.status="fulfilled",n.value=e)},function(e){n.status==="pending"&&(n.status="rejected",n.reason=e)})),n.status){case"fulfilled":return n.value;case"rejected":throw n.reason}}throw n}function Af(n,e,t,i,a){var r=typeof n;(r==="undefined"||r==="boolean")&&(n=null);var s=!1;if(n===null)s=!0;else switch(r){case"bigint":case"string":case"number":s=!0;break;case"object":switch(n.$$typeof){case lM:case dz:s=!0;break;case qO:return s=n._init,Af(s(n._payload),e,t,i,a)}}if(s)return a=a(n),s=i===""?"."+WS(n,0):i,PR(a)?(t="",s!=null&&(t=s.replace(zR,"$&/")+"/"),Af(a,e,t,"",function(h){return h})):a!=null&&(fM(a)&&(a=Mz(a,t+(a.key==null||n&&n.key===a.key?"":(""+a.key).replace(zR,"$&/")+"/")+s)),e.push(a)),1;s=0;var o=i===""?".":i+":";if(PR(n))for(var c=0;c>>1,ie=W[oe];if(0>>1;oea(nt,K))tta(gt,nt)?(W[oe]=gt,W[tt]=K,oe=tt):(W[oe]=nt,W[Xe]=K,oe=Xe);else if(tta(gt,K))W[oe]=gt,W[tt]=K,oe=tt;else break e}}return te}function a(W,te){var K=W.sortIndex-te.sortIndex;return K!==0?K:W.id-te.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var r=performance;n.unstable_now=function(){return r.now()}}else{var s=Date,o=s.now();n.unstable_now=function(){return s.now()-o}}var c=[],h=[],f=1,d=null,m=3,g=!1,x=!1,T=!1,y=!1,v=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,E=typeof setImmediate<"u"?setImmediate:null;function b(W){for(var te=t(h);te!==null;){if(te.callback===null)i(h);else if(te.startTime<=W)i(h),te.sortIndex=te.expirationTime,e(c,te);else break;te=t(h)}}function D(W){if(T=!1,b(W),!x)if(t(c)!==null)x=!0,C||(C=!0,j());else{var te=t(h);te!==null&&re(D,te.startTime-W)}}var C=!1,I=-1,P=5,O=-1;function w(){return y?!0:!(n.unstable_now()-OW&&w());){var oe=d.callback;if(typeof oe=="function"){d.callback=null,m=d.priorityLevel;var ie=oe(d.expirationTime<=W);if(W=n.unstable_now(),typeof ie=="function"){d.callback=ie,b(W),te=!0;break t}d===t(c)&&i(c),b(W)}else i(c);d=t(c)}if(d!==null)te=!0;else{var Ce=t(h);Ce!==null&&re(D,Ce.startTime-W),te=!1}}break e}finally{d=null,m=K,g=!1}te=void 0}}finally{te?j():C=!1}}}var j;if(typeof E=="function")j=function(){E(B)};else if(typeof MessageChannel<"u"){var ee=new MessageChannel,se=ee.port2;ee.port1.onmessage=B,j=function(){se.postMessage(null)}}else j=function(){v(B,0)};function re(W,te){I=v(function(){W(n.unstable_now())},te)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(W){W.callback=null},n.unstable_forceFrameRate=function(W){0>W||125oe?(W.sortIndex=K,e(h,W),t(c)===null&&W===t(h)&&(T?(S(I),I=-1):T=!0,re(D,K-oe))):(W.sortIndex=ie,e(c,W),x||g||(x=!0,C||(C=!0,j()))),W},n.unstable_shouldYield=w,n.unstable_wrapCallback=function(W){var te=m;return function(){var K=m;m=te;try{return W.apply(this,arguments)}finally{m=K}}}})(tL);eL.exports=tL;var Cz=eL.exports,nL={exports:{}},Pa={};/** - * @license React - * react-dom.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Nz=Me;function iL(n){var e="https://react.dev/errors/"+n;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(aL)}catch(n){console.error(n)}}aL(),nL.exports=Pa;var Lz=nL.exports;/** - * @license React - * react-dom-client.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Gi=Cz,rL=Me,Iz=Lz;function Ue(n){var e="https://react.dev/errors/"+n;if(1Of||(n.current=h3[Of],h3[Of]=null,Of--)}function Yn(n,e){Of++,h3[Of]=n.current,n.current=e}var io=lo(null),Xm=lo(null),tc=lo(null),b_=lo(null);function A_(n,e){switch(Yn(tc,e),Yn(Xm,n),Yn(io,null),e.nodeType){case 9:case 11:n=(n=e.documentElement)&&(n=n.namespaceURI)?YC(n):0;break;default:if(n=e.tagName,e=e.namespaceURI)e=YC(e),n=DI(e,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}ea(io),Yn(io,n)}function ld(){ea(io),ea(Xm),ea(tc)}function f3(n){n.memoizedState!==null&&Yn(b_,n);var e=io.current,t=DI(e,n.type);e!==t&&(Yn(Xm,n),Yn(io,t))}function w_(n){Xm.current===n&&(ea(io),ea(Xm)),b_.current===n&&(ea(b_),n0._currentValue=Cu)}var XS,GR;function du(n){if(XS===void 0)try{throw Error()}catch(t){var e=t.stack.trim().match(/\n( *(at )?)/);XS=e&&e[1]||"",GR=-1)":-1a||c[i]!==h[a]){var f=` -`+c[i].replace(" at new "," at ");return n.displayName&&f.includes("")&&(f=f.replace("",n.displayName)),f}while(1<=i&&0<=a);break}}}finally{YS=!1,Error.prepareStackTrace=t}return(t=n?n.displayName||n.name:"")?du(t):""}function Hz(n,e){switch(n.tag){case 26:case 27:case 5:return du(n.type);case 16:return du("Lazy");case 13:return n.child!==e&&e!==null?du("Suspense Fallback"):du("Suspense");case 19:return du("SuspenseList");case 0:case 15:return qS(n.type,!1);case 11:return qS(n.type.render,!1);case 1:return qS(n.type,!0);case 31:return du("Activity");default:return""}}function VR(n){try{var e="",t=null;do e+=Hz(n,t),t=n,n=n.return;while(n);return e}catch(i){return` -Error generating stack: `+i.message+` -`+i.stack}}var d3=Object.prototype.hasOwnProperty,gM=Gi.unstable_scheduleCallback,jS=Gi.unstable_cancelCallback,Fz=Gi.unstable_shouldYield,Gz=Gi.unstable_requestPaint,Ar=Gi.unstable_now,Vz=Gi.unstable_getCurrentPriorityLevel,fL=Gi.unstable_ImmediatePriority,dL=Gi.unstable_UserBlockingPriority,R_=Gi.unstable_NormalPriority,kz=Gi.unstable_LowPriority,pL=Gi.unstable_IdlePriority,Wz=Gi.log,Xz=Gi.unstable_setDisableYieldValue,S0=null,wr=null;function ql(n){if(typeof Wz=="function"&&Xz(n),wr&&typeof wr.setStrictMode=="function")try{wr.setStrictMode(S0,n)}catch{}}var Rr=Math.clz32?Math.clz32:jz,Yz=Math.log,qz=Math.LN2;function jz(n){return n>>>=0,n===0?32:31-(Yz(n)/qz|0)|0}var Og=256,Lg=262144,Ig=4194304;function pu(n){var e=n&42;if(e!==0)return e;switch(n&-n){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 n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function f1(n,e,t){var i=n.pendingLanes;if(i===0)return 0;var a=0,r=n.suspendedLanes,s=n.pingedLanes;n=n.warmLanes;var o=i&134217727;return o!==0?(i=o&~r,i!==0?a=pu(i):(s&=o,s!==0?a=pu(s):t||(t=o&~n,t!==0&&(a=pu(t))))):(o=i&~r,o!==0?a=pu(o):s!==0?a=pu(s):t||(t=i&~n,t!==0&&(a=pu(t)))),a===0?0:e!==0&&e!==a&&!(e&r)&&(r=a&-a,t=e&-e,r>=t||r===32&&(t&4194048)!==0)?e:a}function T0(n,e){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&e)===0}function Zz(n,e){switch(n){case 1:case 2:case 4:case 8:case 64:return e+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 e+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 mL(){var n=Ig;return Ig<<=1,!(Ig&62914560)&&(Ig=4194304),n}function ZS(n){for(var e=[],t=0;31>t;t++)e.push(n);return e}function E0(n,e){n.pendingLanes|=e,e!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function Kz(n,e,t,i,a,r){var s=n.pendingLanes;n.pendingLanes=t,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=t,n.entangledLanes&=t,n.errorRecoveryDisabledLanes&=t,n.shellSuspendCounter=0;var o=n.entanglements,c=n.expirationTimes,h=n.hiddenUpdates;for(t=s&~t;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var nB=/[\n"\\]/g;function Qr(n){return n.replace(nB,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function g3(n,e,t,i,a,r,s,o){n.name="",s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"?n.type=s:n.removeAttribute("type"),e!=null?s==="number"?(e===0&&n.value===""||n.value!=e)&&(n.value=""+jr(e)):n.value!==""+jr(e)&&(n.value=""+jr(e)):s!=="submit"&&s!=="reset"||n.removeAttribute("value"),e!=null?v3(n,s,jr(e)):t!=null?v3(n,s,jr(t)):i!=null&&n.removeAttribute("value"),a==null&&r!=null&&(n.defaultChecked=!!r),a!=null&&(n.checked=a&&typeof a!="function"&&typeof a!="symbol"),o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"?n.name=""+jr(o):n.removeAttribute("name")}function ML(n,e,t,i,a,r,s,o){if(r!=null&&typeof r!="function"&&typeof r!="symbol"&&typeof r!="boolean"&&(n.type=r),e!=null||t!=null){if(!(r!=="submit"&&r!=="reset"||e!=null)){m3(n);return}t=t!=null?""+jr(t):"",e=e!=null?""+jr(e):t,o||e===n.value||(n.value=e),n.defaultValue=e}i=i??a,i=typeof i!="function"&&typeof i!="symbol"&&!!i,n.checked=o?n.checked:!!i,n.defaultChecked=!!i,s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"&&(n.name=s),m3(n)}function v3(n,e,t){e==="number"&&C_(n.ownerDocument)===n||n.defaultValue===""+t||(n.defaultValue=""+t)}function Qf(n,e,t,i){if(n=n.options,e){e={};for(var a=0;a"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),x3=!1;if(el)try{var wp={};Object.defineProperty(wp,"passive",{get:function(){x3=!0}}),window.addEventListener("test",wp,wp),window.removeEventListener("test",wp,wp)}catch{x3=!1}var jl=null,TM=null,t_=null;function CL(){if(t_)return t_;var n,e=TM,t=e.length,i,a="value"in jl?jl.value:jl.textContent,r=a.length;for(n=0;n=_m),$R=" ",eC=!1;function DL(n,e){switch(n){case"keyup":return NB.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function OL(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Uf=!1;function OB(n,e){switch(n){case"compositionend":return OL(e);case"keypress":return e.which!==32?null:(eC=!0,$R);case"textInput":return n=e.data,n===$R&&eC?null:n;default:return null}}function LB(n,e){if(Uf)return n==="compositionend"||!MM&&DL(n,e)?(n=CL(),t_=TM=jl=null,Uf=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:t,offset:e-n};n=i}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=rC(t)}}function PL(n,e){return n&&e?n===e?!0:n&&n.nodeType===3?!1:e&&e.nodeType===3?PL(n,e.parentNode):"contains"in n?n.contains(e):n.compareDocumentPosition?!!(n.compareDocumentPosition(e)&16):!1:!1}function zL(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var e=C_(n.document);e instanceof n.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)n=e.contentWindow;else break;e=C_(n.document)}return e}function bM(n){var e=n&&n.nodeName&&n.nodeName.toLowerCase();return e&&(e==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||e==="textarea"||n.contentEditable==="true")}var GB=el&&"documentMode"in document&&11>=document.documentMode,Pf=null,y3=null,ym=null,S3=!1;function oC(n,e,t){var i=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;S3||Pf==null||Pf!==C_(i)||(i=Pf,"selectionStart"in i&&bM(i)?i={start:i.selectionStart,end:i.selectionEnd}:(i=(i.ownerDocument&&i.ownerDocument.defaultView||window).getSelection(),i={anchorNode:i.anchorNode,anchorOffset:i.anchorOffset,focusNode:i.focusNode,focusOffset:i.focusOffset}),ym&&jm(ym,i)||(ym=i,i=q_(y3,"onSelect"),0>=s,a-=s,$s=1<<32-Rr(e)+a|t<P?(O=I,I=null):O=I.sibling;var w=m(v,I,E[P],b);if(w===null){I===null&&(I=O);break}n&&I&&w.alternate===null&&e(v,I),S=r(w,S,P),C===null?D=w:C.sibling=w,C=w,I=O}if(P===E.length)return t(v,I),un&&Fo(v,P),D;if(I===null){for(;PP?(O=I,I=null):O=I.sibling;var B=m(v,I,w.value,b);if(B===null){I===null&&(I=O);break}n&&I&&B.alternate===null&&e(v,I),S=r(B,S,P),C===null?D=B:C.sibling=B,C=B,I=O}if(w.done)return t(v,I),un&&Fo(v,P),D;if(I===null){for(;!w.done;P++,w=E.next())w=d(v,w.value,b),w!==null&&(S=r(w,S,P),C===null?D=w:C.sibling=w,C=w);return un&&Fo(v,P),D}for(I=i(I);!w.done;P++,w=E.next())w=g(I,v,P,w.value,b),w!==null&&(n&&w.alternate!==null&&I.delete(w.key===null?P:w.key),S=r(w,S,P),C===null?D=w:C.sibling=w,C=w);return n&&I.forEach(function(j){return e(v,j)}),un&&Fo(v,P),D}function y(v,S,E,b){if(typeof E=="object"&&E!==null&&E.type===Df&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case Dg:e:{for(var D=E.key;S!==null;){if(S.key===D){if(D=E.type,D===Df){if(S.tag===7){t(v,S.sibling),b=a(S,E.props.children),b.return=v,v=b;break e}}else if(S.elementType===D||typeof D=="object"&&D!==null&&D.$$typeof===Hl&&mu(D)===S.type){t(v,S.sibling),b=a(S,E.props),Cp(b,E),b.return=v,v=b;break e}t(v,S);break}else e(v,S);S=S.sibling}E.type===Df?(b=Nu(E.props.children,v.mode,b,E.key),b.return=v,v=b):(b=i_(E.type,E.key,E.props,null,v.mode,b),Cp(b,E),b.return=v,v=b)}return s(v);case am:e:{for(D=E.key;S!==null;){if(S.key===D)if(S.tag===4&&S.stateNode.containerInfo===E.containerInfo&&S.stateNode.implementation===E.implementation){t(v,S.sibling),b=a(S,E.children||[]),b.return=v,v=b;break e}else{t(v,S);break}else e(v,S);S=S.sibling}b=aT(E,v.mode,b),b.return=v,v=b}return s(v);case Hl:return E=mu(E),y(v,S,E,b)}if(rm(E))return x(v,S,E,b);if(Ap(E)){if(D=Ap(E),typeof D!="function")throw Error(Ue(150));return E=D.call(E),T(v,S,E,b)}if(typeof E.then=="function")return y(v,S,Bg(E),b);if(E.$$typeof===Yo)return y(v,S,zg(v,E),b);Hg(v,E)}return typeof E=="string"&&E!==""||typeof E=="number"||typeof E=="bigint"?(E=""+E,S!==null&&S.tag===6?(t(v,S.sibling),b=a(S,E),b.return=v,v=b):(t(v,S),b=iT(E,v.mode,b),b.return=v,v=b),s(v)):t(v,S)}return function(v,S,E,b){try{Qm=0;var D=y(v,S,E,b);return ed=null,D}catch(I){if(I===Gd||I===_1)throw I;var C=Tr(29,I,null,v.mode);return C.lanes=b,C.return=v,C}finally{}}}var Vu=JL(!0),$L=JL(!1),Fl=!1;function IM(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function R3(n,e){n=n.updateQueue,e.updateQueue===n&&(e.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function ic(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function ac(n,e,t){var i=n.updateQueue;if(i===null)return null;if(i=i.shared,xn&2){var a=i.pending;return a===null?e.next=e:(e.next=a.next,a.next=e),i.pending=e,e=D_(n),WL(n,null,t),e}return v1(n,i,e,t),D_(n)}function Tm(n,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194048)!==0)){var i=e.lanes;i&=n.pendingLanes,t|=i,e.lanes=t,vL(n,t)}}function sT(n,e){var t=n.updateQueue,i=n.alternate;if(i!==null&&(i=i.updateQueue,t===i)){var a=null,r=null;if(t=t.firstBaseUpdate,t!==null){do{var s={lane:t.lane,tag:t.tag,payload:t.payload,callback:null,next:null};r===null?a=r=s:r=r.next=s,t=t.next}while(t!==null);r===null?a=r=e:r=r.next=e}else a=r=e;t={baseState:i.baseState,firstBaseUpdate:a,lastBaseUpdate:r,shared:i.shared,callbacks:i.callbacks},n.updateQueue=t;return}n=t.lastBaseUpdate,n===null?t.firstBaseUpdate=e:n.next=e,t.lastBaseUpdate=e}var C3=!1;function Em(){if(C3){var n=$f;if(n!==null)throw n}}function Mm(n,e,t,i){C3=!1;var a=n.updateQueue;Fl=!1;var r=a.firstBaseUpdate,s=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,h=c.next;c.next=null,s===null?r=h:s.next=h,s=c;var f=n.alternate;f!==null&&(f=f.updateQueue,o=f.lastBaseUpdate,o!==s&&(o===null?f.firstBaseUpdate=h:o.next=h,f.lastBaseUpdate=c))}if(r!==null){var d=a.baseState;s=0,f=h=c=null,o=r;do{var m=o.lane&-536870913,g=m!==o.lane;if(g?(cn&m)===m:(i&m)===m){m!==0&&m===hd&&(C3=!0),f!==null&&(f=f.next={lane:0,tag:o.tag,payload:o.payload,callback:null,next:null});e:{var x=n,T=o;m=e;var y=t;switch(T.tag){case 1:if(x=T.payload,typeof x=="function"){d=x.call(y,d,m);break e}d=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=T.payload,m=typeof x=="function"?x.call(y,d,m):x,m==null)break e;d=ni({},d,m);break e;case 2:Fl=!0}}m=o.callback,m!==null&&(n.flags|=64,g&&(n.flags|=8192),g=a.callbacks,g===null?a.callbacks=[m]:g.push(m))}else g={lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},f===null?(h=f=g,c=d):f=f.next=g,s|=m;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;g=o,o=g.next,g.next=null,a.lastBaseUpdate=g,a.shared.pending=null}}while(!0);f===null&&(c=d),a.baseState=c,a.firstBaseUpdate=h,a.lastBaseUpdate=f,r===null&&(a.shared.lanes=0),mc|=s,n.lanes=s,n.memoizedState=d}}function e5(n,e){if(typeof n!="function")throw Error(Ue(191,n));n.call(e)}function t5(n,e){var t=n.callbacks;if(t!==null)for(n.callbacks=null,n=0;nr?r:8;var s=Ut.T,o={};Ut.T=o,qM(n,!1,e,t);try{var c=a(),h=Ut.S;if(h!==null&&h(o,c),c!==null&&typeof c=="object"&&typeof c.then=="function"){var f=KB(c,i);bm(n,e,f,Cr(n))}else bm(n,e,i,Cr(n))}catch(d){bm(n,e,{then:function(){},status:"rejected",reason:d},Cr())}finally{yn.p=r,s!==null&&o.types!==null&&(s.types=o.types),Ut.T=s}}function nH(){}function I3(n,e,t,i){if(n.tag!==5)throw Error(Ue(476));var a=A5(n).queue;b5(n,a,e,Cu,t===null?nH:function(){return w5(n),t(i)})}function A5(n){var e=n.memoizedState;if(e!==null)return e;e={memoizedState:Cu,baseState:Cu,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:nl,lastRenderedState:Cu},next:null};var t={};return e.next={memoizedState:t,baseState:t,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:nl,lastRenderedState:t},next:null},n.memoizedState=e,n=n.alternate,n!==null&&(n.memoizedState=e),e}function w5(n){var e=A5(n);e.next===null&&(e=n.alternate.memoizedState),bm(n,e.next.queue,{},Cr())}function YM(){return ua(n0)}function R5(){return Ti().memoizedState}function C5(){return Ti().memoizedState}function iH(n){for(var e=n.return;e!==null;){switch(e.tag){case 24:case 3:var t=Cr();n=ic(t);var i=ac(e,n,t);i!==null&&(Ja(i,e,t),Tm(i,e,t)),e={cache:DM()},n.payload=e;return}e=e.return}}function aH(n,e,t){var i=Cr();t={lane:i,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null},T1(n)?D5(e,t):(t=wM(n,e,t,i),t!==null&&(Ja(t,n,i),O5(t,e,i)))}function N5(n,e,t){var i=Cr();bm(n,e,t,i)}function bm(n,e,t,i){var a={lane:i,revertLane:0,gesture:null,action:t,hasEagerState:!1,eagerState:null,next:null};if(T1(n))D5(e,a);else{var r=n.alternate;if(n.lanes===0&&(r===null||r.lanes===0)&&(r=e.lastRenderedReducer,r!==null))try{var s=e.lastRenderedState,o=r(s,t);if(a.hasEagerState=!0,a.eagerState=o,Dr(o,s))return v1(n,e,a,0),Hn===null&&g1(),!1}catch{}finally{}if(t=wM(n,e,a,i),t!==null)return Ja(t,n,i),O5(t,e,i),!0}return!1}function qM(n,e,t,i){if(i={lane:2,revertLane:nb(),gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},T1(n)){if(e)throw Error(Ue(479))}else e=wM(n,t,i,2),e!==null&&Ja(e,n,2)}function T1(n){var e=n.alternate;return n===Zt||e!==null&&e===Zt}function D5(n,e){td=z_=!0;var t=n.pending;t===null?e.next=e:(e.next=t.next,t.next=e),n.pending=e}function O5(n,e,t){if(t&4194048){var i=e.lanes;i&=n.pendingLanes,t|=i,e.lanes=t,vL(n,t)}}var $m={readContext:ua,use:y1,useCallback:vi,useContext:vi,useEffect:vi,useImperativeHandle:vi,useLayoutEffect:vi,useInsertionEffect:vi,useMemo:vi,useReducer:vi,useRef:vi,useState:vi,useDebugValue:vi,useDeferredValue:vi,useTransition:vi,useSyncExternalStore:vi,useId:vi,useHostTransitionStatus:vi,useFormState:vi,useActionState:vi,useOptimistic:vi,useMemoCache:vi,useCacheRefresh:vi};$m.useEffectEvent=vi;var L5={readContext:ua,use:y1,useCallback:function(n,e){return Ra().memoizedState=[n,e===void 0?null:e],n},useContext:ua,useEffect:TC,useImperativeHandle:function(n,e,t){t=t!=null?t.concat([n]):null,s_(4194308,4,y5.bind(null,e,n),t)},useLayoutEffect:function(n,e){return s_(4194308,4,n,e)},useInsertionEffect:function(n,e){s_(4,2,n,e)},useMemo:function(n,e){var t=Ra();e=e===void 0?null:e;var i=n();if(ku){ql(!0);try{n()}finally{ql(!1)}}return t.memoizedState=[i,e],i},useReducer:function(n,e,t){var i=Ra();if(t!==void 0){var a=t(e);if(ku){ql(!0);try{t(e)}finally{ql(!1)}}}else a=e;return i.memoizedState=i.baseState=a,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:a},i.queue=n,n=n.dispatch=aH.bind(null,Zt,n),[i.memoizedState,n]},useRef:function(n){var e=Ra();return n={current:n},e.memoizedState=n},useState:function(n){n=O3(n);var e=n.queue,t=N5.bind(null,Zt,e);return e.dispatch=t,[n.memoizedState,t]},useDebugValue:WM,useDeferredValue:function(n,e){var t=Ra();return XM(t,n,e)},useTransition:function(){var n=O3(!1);return n=b5.bind(null,Zt,n.queue,!0,!1),Ra().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,e,t){var i=Zt,a=Ra();if(un){if(t===void 0)throw Error(Ue(407));t=t()}else{if(t=e(),Hn===null)throw Error(Ue(349));cn&127||s5(i,e,t)}a.memoizedState=t;var r={value:t,getSnapshot:e};return a.queue=r,TC(l5.bind(null,i,r,n),[n]),i.flags|=2048,dd(9,{destroy:void 0},o5.bind(null,i,r,t,e),null),t},useId:function(){var n=Ra(),e=Hn.identifierPrefix;if(un){var t=eo,i=$s;t=(i&~(1<<32-Rr(i)-1)).toString(32)+t,e="_"+e+"R_"+t,t=B_++,0<\/script>",r=r.removeChild(r.firstChild);break;case"select":r=typeof i.is=="string"?s.createElement("select",{is:i.is}):s.createElement("select"),i.multiple?r.multiple=!0:i.size&&(r.size=i.size);break;default:r=typeof i.is=="string"?s.createElement(a,{is:i.is}):s.createElement(a)}}r[oa]=e,r[er]=i;e:for(s=e.child;s!==null;){if(s.tag===5||s.tag===6)r.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===e)break e;for(;s.sibling===null;){if(s.return===null||s.return===e)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}e.stateNode=r;e:switch(ha(r,a,i),a){case"button":case"input":case"select":case"textarea":i=!!i.autoFocus;break e;case"img":i=!0;break e;default:i=!1}i&&bo(e)}}return Kn(e),pT(e,e.type,n===null?null:n.memoizedProps,e.pendingProps,t),null;case 6:if(n&&e.stateNode!=null)n.memoizedProps!==i&&bo(e);else{if(typeof i!="string"&&e.stateNode===null)throw Error(Ue(166));if(n=tc.current,kh(e)){if(n=e.stateNode,t=e.memoizedProps,i=null,a=la,a!==null)switch(a.tag){case 27:case 5:i=a.memoizedProps}n[oa]=e,n=!!(n.nodeValue===t||i!==null&&i.suppressHydrationWarning===!0||NI(n.nodeValue,t)),n||dc(e,!0)}else n=j_(n).createTextNode(i),n[oa]=e,e.stateNode=n}return Kn(e),null;case 31:if(t=e.memoizedState,n===null||n.memoizedState!==null){if(i=kh(e),t!==null){if(n===null){if(!i)throw Error(Ue(318));if(n=e.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(Ue(557));n[oa]=e}else Fu(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;Kn(e),n=!1}else t=rT(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=t),n=!0;if(!n)return e.flags&256?(Sr(e),e):(Sr(e),null);if(e.flags&128)throw Error(Ue(558))}return Kn(e),null;case 13:if(i=e.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(a=kh(e),i!==null&&i.dehydrated!==null){if(n===null){if(!a)throw Error(Ue(318));if(a=e.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(Ue(317));a[oa]=e}else Fu(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;Kn(e),a=!1}else a=rT(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=a),a=!0;if(!a)return e.flags&256?(Sr(e),e):(Sr(e),null)}return Sr(e),e.flags&128?(e.lanes=t,e):(t=i!==null,n=n!==null&&n.memoizedState!==null,t&&(i=e.child,a=null,i.alternate!==null&&i.alternate.memoizedState!==null&&i.alternate.memoizedState.cachePool!==null&&(a=i.alternate.memoizedState.cachePool.pool),r=null,i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(r=i.memoizedState.cachePool.pool),r!==a&&(i.flags|=2048)),t!==n&&t&&(e.child.flags|=8192),Fg(e,e.updateQueue),Kn(e),null);case 4:return ld(),n===null&&ib(e.stateNode.containerInfo),Kn(e),null;case 10:return Ko(e.type),Kn(e),null;case 19:if(ea(Si),i=e.memoizedState,i===null)return Kn(e),null;if(a=(e.flags&128)!==0,r=i.rendering,r===null)if(a)Np(i,!1);else{if(_i!==0||n!==null&&n.flags&128)for(n=e.child;n!==null;){if(r=P_(n),r!==null){for(e.flags|=128,Np(i,!1),n=r.updateQueue,e.updateQueue=n,Fg(e,n),e.subtreeFlags=0,n=t,t=e.child;t!==null;)XL(t,n),t=t.sibling;return Yn(Si,Si.current&1|2),un&&Fo(e,i.treeForkCount),e.child}n=n.sibling}i.tail!==null&&Ar()>V_&&(e.flags|=128,a=!0,Np(i,!1),e.lanes=4194304)}else{if(!a)if(n=P_(r),n!==null){if(e.flags|=128,a=!0,n=n.updateQueue,e.updateQueue=n,Fg(e,n),Np(i,!0),i.tail===null&&i.tailMode==="hidden"&&!r.alternate&&!un)return Kn(e),null}else 2*Ar()-i.renderingStartTime>V_&&t!==536870912&&(e.flags|=128,a=!0,Np(i,!1),e.lanes=4194304);i.isBackwards?(r.sibling=e.child,e.child=r):(n=i.last,n!==null?n.sibling=r:e.child=r,i.last=r)}return i.tail!==null?(n=i.tail,i.rendering=n,i.tail=n.sibling,i.renderingStartTime=Ar(),n.sibling=null,t=Si.current,Yn(Si,a?t&1|2:t&1),un&&Fo(e,i.treeForkCount),n):(Kn(e),null);case 22:case 23:return Sr(e),UM(),i=e.memoizedState!==null,n!==null?n.memoizedState!==null!==i&&(e.flags|=8192):i&&(e.flags|=8192),i?t&536870912&&!(e.flags&128)&&(Kn(e),e.subtreeFlags&6&&(e.flags|=8192)):Kn(e),t=e.updateQueue,t!==null&&Fg(e,t.retryQueue),t=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(t=n.memoizedState.cachePool.pool),i=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(i=e.memoizedState.cachePool.pool),i!==t&&(e.flags|=2048),n!==null&&ea(Du),null;case 24:return t=null,n!==null&&(t=n.memoizedState.cache),e.memoizedState.cache!==t&&(e.flags|=2048),Ko(Li),Kn(e),null;case 25:return null;case 30:return null}throw Error(Ue(156,e.tag))}function cH(n,e){switch(NM(e),e.tag){case 1:return n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 3:return Ko(Li),ld(),n=e.flags,n&65536&&!(n&128)?(e.flags=n&-65537|128,e):null;case 26:case 27:case 5:return w_(e),null;case 31:if(e.memoizedState!==null){if(Sr(e),e.alternate===null)throw Error(Ue(340));Fu()}return n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 13:if(Sr(e),n=e.memoizedState,n!==null&&n.dehydrated!==null){if(e.alternate===null)throw Error(Ue(340));Fu()}return n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 19:return ea(Si),null;case 4:return ld(),null;case 10:return Ko(e.type),null;case 22:case 23:return Sr(e),UM(),n!==null&&ea(Du),n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 24:return Ko(Li),null;case 25:return null;default:return null}}function X5(n,e){switch(NM(e),e.tag){case 3:Ko(Li),ld();break;case 26:case 27:case 5:w_(e);break;case 4:ld();break;case 31:e.memoizedState!==null&&Sr(e);break;case 13:Sr(e);break;case 19:ea(Si);break;case 10:Ko(e.type);break;case 22:case 23:Sr(e),UM(),n!==null&&ea(Du);break;case 24:Ko(Li)}}function R0(n,e){try{var t=e.updateQueue,i=t!==null?t.lastEffect:null;if(i!==null){var a=i.next;t=a;do{if((t.tag&n)===n){i=void 0;var r=t.create,s=t.inst;i=r(),s.destroy=i}t=t.next}while(t!==a)}}catch(o){Cn(e,e.return,o)}}function pc(n,e,t){try{var i=e.updateQueue,a=i!==null?i.lastEffect:null;if(a!==null){var r=a.next;i=r;do{if((i.tag&n)===n){var s=i.inst,o=s.destroy;if(o!==void 0){s.destroy=void 0,a=e;var c=t,h=o;try{h()}catch(f){Cn(a,c,f)}}}i=i.next}while(i!==r)}}catch(f){Cn(e,e.return,f)}}function Y5(n){var e=n.updateQueue;if(e!==null){var t=n.stateNode;try{t5(e,t)}catch(i){Cn(n,n.return,i)}}}function q5(n,e,t){t.props=Wu(n.type,n.memoizedProps),t.state=n.memoizedState;try{t.componentWillUnmount()}catch(i){Cn(n,e,i)}}function Am(n,e){try{var t=n.ref;if(t!==null){switch(n.tag){case 26:case 27:case 5:var i=n.stateNode;break;case 30:i=n.stateNode;break;default:i=n.stateNode}typeof t=="function"?n.refCleanup=t(i):t.current=i}}catch(a){Cn(n,e,a)}}function to(n,e){var t=n.ref,i=n.refCleanup;if(t!==null)if(typeof i=="function")try{i()}catch(a){Cn(n,e,a)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof t=="function")try{t(null)}catch(a){Cn(n,e,a)}else t.current=null}function j5(n){var e=n.type,t=n.memoizedProps,i=n.stateNode;try{e:switch(e){case"button":case"input":case"select":case"textarea":t.autoFocus&&i.focus();break e;case"img":t.src?i.src=t.src:t.srcSet&&(i.srcset=t.srcSet)}}catch(a){Cn(n,n.return,a)}}function mT(n,e,t){try{var i=n.stateNode;DH(i,n.type,t,e),i[er]=e}catch(a){Cn(n,n.return,a)}}function Z5(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Tc(n.type)||n.tag===4}function gT(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Z5(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&Tc(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function H3(n,e,t){var i=n.tag;if(i===5||i===6)n=n.stateNode,e?(t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t).insertBefore(n,e):(e=t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t,e.appendChild(n),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=qo));else if(i!==4&&(i===27&&Tc(n.type)&&(t=n.stateNode,e=null),n=n.child,n!==null))for(H3(n,e,t),n=n.sibling;n!==null;)H3(n,e,t),n=n.sibling}function G_(n,e,t){var i=n.tag;if(i===5||i===6)n=n.stateNode,e?t.insertBefore(n,e):t.appendChild(n);else if(i!==4&&(i===27&&Tc(n.type)&&(t=n.stateNode),n=n.child,n!==null))for(G_(n,e,t),n=n.sibling;n!==null;)G_(n,e,t),n=n.sibling}function K5(n){var e=n.stateNode,t=n.memoizedProps;try{for(var i=n.type,a=e.attributes;a.length;)e.removeAttributeNode(a[0]);ha(e,i,t),e[oa]=n,e[er]=t}catch(r){Cn(n,n.return,r)}}var Vo=!1,Di=!1,vT=!1,UC=typeof WeakSet=="function"?WeakSet:Set,Ji=null;function uH(n,e){if(n=n.containerInfo,Y3=J_,n=zL(n),bM(n)){if("selectionStart"in n)var t={start:n.selectionStart,end:n.selectionEnd};else e:{t=(t=n.ownerDocument)&&t.defaultView||window;var i=t.getSelection&&t.getSelection();if(i&&i.rangeCount!==0){t=i.anchorNode;var a=i.anchorOffset,r=i.focusNode;i=i.focusOffset;try{t.nodeType,r.nodeType}catch{t=null;break e}var s=0,o=-1,c=-1,h=0,f=0,d=n,m=null;t:for(;;){for(var g;d!==t||a!==0&&d.nodeType!==3||(o=s+a),d!==r||i!==0&&d.nodeType!==3||(c=s+i),d.nodeType===3&&(s+=d.nodeValue.length),(g=d.firstChild)!==null;)m=d,d=g;for(;;){if(d===n)break t;if(m===t&&++h===a&&(o=s),m===r&&++f===i&&(c=s),(g=d.nextSibling)!==null)break;d=m,m=d.parentNode}d=g}t=o===-1||c===-1?null:{start:o,end:c}}else t=null}t=t||{start:0,end:0}}else t=null;for(q3={focusedElem:n,selectionRange:t},J_=!1,Ji=e;Ji!==null;)if(e=Ji,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,Ji=n;else for(;Ji!==null;){switch(e=Ji,r=e.alternate,n=e.flags,e.tag){case 0:if(n&4&&(n=e.updateQueue,n=n!==null?n.events:null,n!==null))for(t=0;t title"))),ha(r,i,t),r[oa]=n,$i(r),i=r;break e;case"link":var s=t4("link","href",a).get(i+(t.href||""));if(s){for(var o=0;oy&&(s=y,y=T,T=s);var v=sC(o,T),S=sC(o,y);if(v&&S&&(g.rangeCount!==1||g.anchorNode!==v.node||g.anchorOffset!==v.offset||g.focusNode!==S.node||g.focusOffset!==S.offset)){var E=d.createRange();E.setStart(v.node,v.offset),g.removeAllRanges(),T>y?(g.addRange(E),g.extend(S.node,S.offset)):(E.setEnd(S.node,S.offset),g.addRange(E))}}}}for(d=[],g=o;g=g.parentNode;)g.nodeType===1&&d.push({element:g,left:g.scrollLeft,top:g.scrollTop});for(typeof o.focus=="function"&&o.focus(),o=0;ot?32:t,Ut.T=null,t=V3,V3=null;var r=sc,s=Qo;if(Fi=0,md=sc=null,Qo=0,xn&6)throw Error(Ue(331));var o=xn;if(xn|=4,oI(r.current),aI(r,r.current,s,t),xn=o,C0(0,!1),wr&&typeof wr.onPostCommitFiberRoot=="function")try{wr.onPostCommitFiberRoot(S0,r)}catch{}return!0}finally{yn.p=a,Ut.T=i,TI(n,e)}}function HC(n,e,t){e=Jr(t,e),e=P3(n.stateNode,e,2),n=ac(n,e,2),n!==null&&(E0(n,2),co(n))}function Cn(n,e,t){if(n.tag===3)HC(n,n,t);else for(;e!==null;){if(e.tag===3){HC(e,n,t);break}else if(e.tag===1){var i=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof i.componentDidCatch=="function"&&(rc===null||!rc.has(i))){n=Jr(t,n),t=B5(2),i=ac(e,t,2),i!==null&&(H5(t,i,e,n),E0(i,2),co(i));break}}e=e.return}}function xT(n,e,t){var i=n.pingCache;if(i===null){i=n.pingCache=new dH;var a=new Set;i.set(e,a)}else a=i.get(e),a===void 0&&(a=new Set,i.set(e,a));a.has(t)||($M=!0,a.add(t),n=_H.bind(null,n,e,t),e.then(n,n))}function _H(n,e,t){var i=n.pingCache;i!==null&&i.delete(e),n.pingedLanes|=n.suspendedLanes&t,n.warmLanes&=~t,Hn===n&&(cn&t)===t&&(_i===4||_i===3&&(cn&62914560)===cn&&300>Ar()-E1?!(xn&2)&&gd(n,0):eb|=t,pd===cn&&(pd=0)),co(n)}function MI(n,e){e===0&&(e=mL()),n=sh(n,e),n!==null&&(E0(n,e),co(n))}function xH(n){var e=n.memoizedState,t=0;e!==null&&(t=e.retryLane),MI(n,t)}function yH(n,e){var t=0;switch(n.tag){case 31:case 13:var i=n.stateNode,a=n.memoizedState;a!==null&&(t=a.retryLane);break;case 19:i=n.stateNode;break;case 22:i=n.stateNode._retryCache;break;default:throw Error(Ue(314))}i!==null&&i.delete(e),MI(n,t)}function SH(n,e){return gM(n,e)}var X_=null,Rf=null,W3=!1,Y_=!1,yT=!1,Ql=0;function co(n){n!==Rf&&n.next===null&&(Rf===null?X_=Rf=n:Rf=Rf.next=n),Y_=!0,W3||(W3=!0,EH())}function C0(n,e){if(!yT&&Y_){yT=!0;do for(var t=!1,i=X_;i!==null;){if(n!==0){var a=i.pendingLanes;if(a===0)var r=0;else{var s=i.suspendedLanes,o=i.pingedLanes;r=(1<<31-Rr(42|n)+1)-1,r&=a&~(s&~o),r=r&201326741?r&201326741|1:r?r|2:0}r!==0&&(t=!0,FC(i,r))}else r=cn,r=f1(i,i===Hn?r:0,i.cancelPendingCommit!==null||i.timeoutHandle!==-1),!(r&3)||T0(i,r)||(t=!0,FC(i,r));i=i.next}while(t);yT=!1}}function TH(){bI()}function bI(){Y_=W3=!1;var n=0;Ql!==0&&LH()&&(n=Ql);for(var e=Ar(),t=null,i=X_;i!==null;){var a=i.next,r=AI(i,e);r===0?(i.next=null,t===null?X_=a:t.next=a,a===null&&(Rf=t)):(t=i,(n!==0||r&3)&&(Y_=!0)),i=a}Fi!==0&&Fi!==5||C0(n),Ql!==0&&(Ql=0)}function AI(n,e){for(var t=n.suspendedLanes,i=n.pingedLanes,a=n.expirationTimes,r=n.pendingLanes&-62914561;0o)break;var f=c.transferSize,d=c.initiatorType;f&&XC(d)&&(c=c.responseEnd,s+=f*(c"u"?null:document;function UI(n,e,t){var i=kd;if(i&&typeof e=="string"&&e){var a=Qr(e);a='link[rel="'+n+'"][href="'+a+'"]',typeof t=="string"&&(a+='[crossorigin="'+t+'"]'),JC.has(a)||(JC.add(a),n={rel:n,crossOrigin:t,href:e},i.querySelector(a)===null&&(e=i.createElement("link"),ha(e,"link",n),$i(e),i.head.appendChild(e)))}}function VH(n){ol.D(n),UI("dns-prefetch",n,null)}function kH(n,e){ol.C(n,e),UI("preconnect",n,e)}function WH(n,e,t){ol.L(n,e,t);var i=kd;if(i&&n&&e){var a='link[rel="preload"][as="'+Qr(e)+'"]';e==="image"&&t&&t.imageSrcSet?(a+='[imagesrcset="'+Qr(t.imageSrcSet)+'"]',typeof t.imageSizes=="string"&&(a+='[imagesizes="'+Qr(t.imageSizes)+'"]')):a+='[href="'+Qr(n)+'"]';var r=a;switch(e){case"style":r=vd(n);break;case"script":r=Wd(n)}ss.has(r)||(n=ni({rel:"preload",href:e==="image"&&t&&t.imageSrcSet?void 0:n,as:e},t),ss.set(r,n),i.querySelector(a)!==null||e==="style"&&i.querySelector(N0(r))||e==="script"&&i.querySelector(D0(r))||(e=i.createElement("link"),ha(e,"link",n),$i(e),i.head.appendChild(e)))}}function XH(n,e){ol.m(n,e);var t=kd;if(t&&n){var i=e&&typeof e.as=="string"?e.as:"script",a='link[rel="modulepreload"][as="'+Qr(i)+'"][href="'+Qr(n)+'"]',r=a;switch(i){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":r=Wd(n)}if(!ss.has(r)&&(n=ni({rel:"modulepreload",href:n},e),ss.set(r,n),t.querySelector(a)===null)){switch(i){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(t.querySelector(D0(r)))return}i=t.createElement("link"),ha(i,"link",n),$i(i),t.head.appendChild(i)}}}function YH(n,e,t){ol.S(n,e,t);var i=kd;if(i&&n){var a=Kf(i).hoistableStyles,r=vd(n);e=e||"default";var s=a.get(r);if(!s){var o={loading:0,preload:null};if(s=i.querySelector(N0(r)))o.loading=5;else{n=ni({rel:"stylesheet",href:n,"data-precedence":e},t),(t=ss.get(r))&&ab(n,t);var c=s=i.createElement("link");$i(c),ha(c,"link",n),c._p=new Promise(function(h,f){c.onload=h,c.onerror=f}),c.addEventListener("load",function(){o.loading|=1}),c.addEventListener("error",function(){o.loading|=2}),o.loading|=4,u_(s,e,i)}s={type:"stylesheet",instance:s,count:1,state:o},a.set(r,s)}}}function qH(n,e){ol.X(n,e);var t=kd;if(t&&n){var i=Kf(t).hoistableScripts,a=Wd(n),r=i.get(a);r||(r=t.querySelector(D0(a)),r||(n=ni({src:n,async:!0},e),(e=ss.get(a))&&rb(n,e),r=t.createElement("script"),$i(r),ha(r,"link",n),t.head.appendChild(r)),r={type:"script",instance:r,count:1,state:null},i.set(a,r))}}function jH(n,e){ol.M(n,e);var t=kd;if(t&&n){var i=Kf(t).hoistableScripts,a=Wd(n),r=i.get(a);r||(r=t.querySelector(D0(a)),r||(n=ni({src:n,async:!0,type:"module"},e),(e=ss.get(a))&&rb(n,e),r=t.createElement("script"),$i(r),ha(r,"link",n),t.head.appendChild(r)),r={type:"script",instance:r,count:1,state:null},i.set(a,r))}}function $C(n,e,t,i){var a=(a=tc.current)?Z_(a):null;if(!a)throw Error(Ue(446));switch(n){case"meta":case"title":return null;case"style":return typeof t.precedence=="string"&&typeof t.href=="string"?(e=vd(t.href),t=Kf(a).hoistableStyles,i=t.get(e),i||(i={type:"style",instance:null,count:0,state:null},t.set(e,i)),i):{type:"void",instance:null,count:0,state:null};case"link":if(t.rel==="stylesheet"&&typeof t.href=="string"&&typeof t.precedence=="string"){n=vd(t.href);var r=Kf(a).hoistableStyles,s=r.get(n);if(s||(a=a.ownerDocument||a,s={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},r.set(n,s),(r=a.querySelector(N0(n)))&&!r._p&&(s.instance=r,s.state.loading=5),ss.has(n)||(t={rel:"preload",as:"style",href:t.href,crossOrigin:t.crossOrigin,integrity:t.integrity,media:t.media,hrefLang:t.hrefLang,referrerPolicy:t.referrerPolicy},ss.set(n,t),r||ZH(a,n,t,s.state))),e&&i===null)throw Error(Ue(528,""));return s}if(e&&i!==null)throw Error(Ue(529,""));return null;case"script":return e=t.async,t=t.src,typeof t=="string"&&e&&typeof e!="function"&&typeof e!="symbol"?(e=Wd(t),t=Kf(a).hoistableScripts,i=t.get(e),i||(i={type:"script",instance:null,count:0,state:null},t.set(e,i)),i):{type:"void",instance:null,count:0,state:null};default:throw Error(Ue(444,n))}}function vd(n){return'href="'+Qr(n)+'"'}function N0(n){return'link[rel="stylesheet"]['+n+"]"}function PI(n){return ni({},n,{"data-precedence":n.precedence,precedence:null})}function ZH(n,e,t,i){n.querySelector('link[rel="preload"][as="style"]['+e+"]")?i.loading=1:(e=n.createElement("link"),i.preload=e,e.addEventListener("load",function(){return i.loading|=1}),e.addEventListener("error",function(){return i.loading|=2}),ha(e,"link",t),$i(e),n.head.appendChild(e))}function Wd(n){return'[src="'+Qr(n)+'"]'}function D0(n){return"script[async]"+n}function e4(n,e,t){if(e.count++,e.instance===null)switch(e.type){case"style":var i=n.querySelector('style[data-href~="'+Qr(t.href)+'"]');if(i)return e.instance=i,$i(i),i;var a=ni({},t,{"data-href":t.href,"data-precedence":t.precedence,href:null,precedence:null});return i=(n.ownerDocument||n).createElement("style"),$i(i),ha(i,"style",a),u_(i,t.precedence,n),e.instance=i;case"stylesheet":a=vd(t.href);var r=n.querySelector(N0(a));if(r)return e.state.loading|=4,e.instance=r,$i(r),r;i=PI(t),(a=ss.get(a))&&ab(i,a),r=(n.ownerDocument||n).createElement("link"),$i(r);var s=r;return s._p=new Promise(function(o,c){s.onload=o,s.onerror=c}),ha(r,"link",i),e.state.loading|=4,u_(r,t.precedence,n),e.instance=r;case"script":return r=Wd(t.src),(a=n.querySelector(D0(r)))?(e.instance=a,$i(a),a):(i=t,(a=ss.get(r))&&(i=ni({},t),rb(i,a)),n=n.ownerDocument||n,a=n.createElement("script"),$i(a),ha(a,"link",i),n.head.appendChild(a),e.instance=a);case"void":return null;default:throw Error(Ue(443,e.type))}else e.type==="stylesheet"&&!(e.state.loading&4)&&(i=e.instance,e.state.loading|=4,u_(i,t.precedence,n));return e.instance}function u_(n,e,t){for(var i=t.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),a=i.length?i[i.length-1]:null,r=a,s=0;s title"):null)}function KH(n,e,t){if(t===1||e.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof e.precedence!="string"||typeof e.href!="string"||e.href==="")break;return!0;case"link":if(typeof e.rel!="string"||typeof e.href!="string"||e.href===""||e.onLoad||e.onError)break;switch(e.rel){case"stylesheet":return n=e.disabled,typeof e.precedence=="string"&&n==null;default:return!0}case"script":if(e.async&&typeof e.async!="function"&&typeof e.async!="symbol"&&!e.onLoad&&!e.onError&&e.src&&typeof e.src=="string")return!0}return!1}function zI(n){return!(n.type==="stylesheet"&&!(n.state.loading&3))}function QH(n,e,t,i){if(t.type==="stylesheet"&&(typeof i.media!="string"||matchMedia(i.media).matches!==!1)&&!(t.state.loading&4)){if(t.instance===null){var a=vd(i.href),r=e.querySelector(N0(a));if(r){e=r._p,e!==null&&typeof e=="object"&&typeof e.then=="function"&&(n.count++,n=K_.bind(n),e.then(n,n)),t.state.loading|=4,t.instance=r,$i(r);return}r=e.ownerDocument||e,i=PI(i),(a=ss.get(a))&&ab(i,a),r=r.createElement("link"),$i(r);var s=r;s._p=new Promise(function(o,c){s.onload=o,s.onerror=c}),ha(r,"link",i),t.instance=r}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(t,e),(e=t.state.preload)&&!(t.state.loading&3)&&(n.count++,t=K_.bind(n),e.addEventListener("load",t),e.addEventListener("error",t))}}var AT=0;function JH(n,e){return n.stylesheets&&n.count===0&&f_(n,n.stylesheets),0AT?50:800)+e);return n.unsuspend=t,function(){n.unsuspend=null,clearTimeout(i),clearTimeout(a)}}:null}function K_(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)f_(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Q_=null;function f_(n,e){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Q_=new Map,e.forEach($H,n),Q_=null,K_.call(n))}function $H(n,e){if(!(e.state.loading&4)){var t=Q_.get(n);if(t)var i=t.get(null);else{t=new Map,Q_.set(n,t);for(var a=n.querySelectorAll("link[data-precedence],style[data-precedence]"),r=0;r"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(XI)}catch(n){console.error(n)}}XI(),$O.exports=u1;var oF=$O.exports;const lF=l1(oF);var YI={exports:{}},Ec={};/** - * @license React - * react-reconciler-constants.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */Ec.ConcurrentRoot=1;Ec.ContinuousEventPriority=8;Ec.DefaultEventPriority=32;Ec.DiscreteEventPriority=2;Ec.IdleEventPriority=268435456;Ec.LegacyRoot=0;Ec.NoEventPriority=0;YI.exports=Ec;var p_=YI.exports;/** - * @license - * Copyright 2010-2025 Three.js Authors - * SPDX-License-Identifier: MIT - */const Cs="181",vu={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},_u={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},qI=0,tE=1,jI=2,cF=3,ZI=0,R1=1,Dm=2,Ss=3,Ns=0,Ui=1,ca=2,Ta=0,Iu=1,nE=2,iE=3,aE=4,ub=5,Js=100,KI=101,QI=102,JI=103,$I=104,eU=200,kf=201,tU=202,nU=203,ex=204,tx=205,iU=206,aU=207,rU=208,sU=209,oU=210,lU=211,cU=212,uU=213,hU=214,nx=0,r0=1,ix=2,Xu=3,ax=4,rx=5,sx=6,ox=7,O0=0,fU=1,dU=2,is=0,pU=1,mU=2,gU=3,hb=4,vU=5,_U=6,xU=7,rE="attached",yU="detached",C1=300,rl=301,gc=302,s0=303,o0=304,Xd=306,Ea=1e3,Pi=1001,xd=1002,Fn=1003,N1=1004,uF=1004,Tu=1005,hF=1005,Ht=1006,id=1007,fF=1007,Mr=1008,SU=1008,zi=1009,D1=1010,O1=1011,Yu=1012,L0=1013,Ds=1014,si=1015,Xn=1016,L1=1017,I1=1018,qu=1020,fb=35902,db=35899,pb=1021,mb=1022,$n=1023,yd=1026,ju=1027,As=1028,I0=1029,ko=1030,U1=1031,dF=1032,P1=1033,Om=33776,Lm=33777,Im=33778,Um=33779,lx=35840,cx=35841,ux=35842,hx=35843,fx=36196,dx=37492,px=37496,mx=37808,gx=37809,vx=37810,_x=37811,xx=37812,yx=37813,Sx=37814,Tx=37815,Ex=37816,Mx=37817,bx=37818,Ax=37819,wx=37820,Rx=37821,Cx=36492,Nx=36494,Dx=36495,Ox=36283,Lx=36284,Ix=36285,Ux=36286,gb=2200,TU=2201,EU=2202,Sd=2300,Td=2301,m_=2302,Eu=2400,Mu=2401,l0=2402,z1=2500,vb=2501,MU=0,_b=1,Px=2,Mc=3200,bU=3201,pF=3202,mF=3203,ll=0,AU=1,Da="",En="srgb",Wn="srgb-linear",c0="linear",wn="srgb",gF=0,xu=7680,vF=7681,_F=7682,xF=7683,yF=34055,SF=34056,TF=5386,EF=512,MF=513,bF=514,AF=515,wF=516,RF=517,CF=518,sE=519,wU=512,RU=513,CU=514,xb=515,NU=516,DU=517,OU=518,LU=519,u0=35044,IU=35048,NF=35040,DF=35045,OF=35049,LF=35041,IF=35046,UF=35050,PF=35042,zF="100",ro="300 es",br=2e3,Ed=2001,BF={COMPUTE:"compute",RENDER:"render"},HF={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},FF={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"};function UU(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}const GF={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function Wf(n,e){return new GF[n](e)}function h0(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function PU(){const n=h0("canvas");return n.style.display="block",n}const c4={};let vc=null;function VF(n){vc=n}function kF(){return vc}function f0(...n){const e="THREE."+n.shift();vc?vc("log",e,...n):console.log(e,...n)}function ut(...n){const e="THREE."+n.shift();vc?vc("warn",e,...n):console.warn(e,...n)}function Bt(...n){const e="THREE."+n.shift();vc?vc("error",e,...n):console.error(e,...n)}function Md(...n){const e=n.join(" ");e in c4||(c4[e]=!0,ut(...n))}function WF(n,e,t){return new Promise(function(i,a){function r(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:a();break;case n.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:i()}}setTimeout(r,t)})}let nr=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners;if(i===void 0)return;const a=i[e];if(a!==void 0){const r=a.indexOf(t);r!==-1&&a.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const i=t[e.type];if(i!==void 0){e.target=this;const a=i.slice(0);for(let r=0,s=a.length;r>8&255]+_a[n>>16&255]+_a[n>>24&255]+"-"+_a[e&255]+_a[e>>8&255]+"-"+_a[e>>16&15|64]+_a[e>>24&255]+"-"+_a[t&63|128]+_a[t>>8&255]+"-"+_a[t>>16&255]+_a[t>>24&255]+_a[i&255]+_a[i>>8&255]+_a[i>>16&255]+_a[i>>24&255]).toLowerCase()}function Lt(n,e,t){return Math.max(e,Math.min(t,n))}function yb(n,e){return(n%e+e)%e}function XF(n,e,t,i,a){return i+(n-e)*(a-i)/(t-e)}function YF(n,e,t){return n!==e?(t-n)/(e-n):0}function Pm(n,e,t){return(1-t)*n+t*e}function qF(n,e,t,i){return Pm(n,e,1-Math.exp(-t*i))}function jF(n,e=1){return e-Math.abs(yb(n,e*2)-e)}function ZF(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function KF(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function QF(n,e){return n+Math.floor(Math.random()*(e-n+1))}function JF(n,e){return n+Math.random()*(e-n)}function $F(n){return n*(.5-Math.random())}function eG(n){n!==void 0&&(u4=n);let e=u4+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function tG(n){return n*Uu}function nG(n){return n*bd}function iG(n){return(n&n-1)===0&&n!==0}function aG(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function rG(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function sG(n,e,t,i,a){const r=Math.cos,s=Math.sin,o=r(t/2),c=s(t/2),h=r((e+i)/2),f=s((e+i)/2),d=r((e-i)/2),m=s((e-i)/2),g=r((i-e)/2),x=s((i-e)/2);switch(a){case"XYX":n.set(o*f,c*d,c*m,o*h);break;case"YZY":n.set(c*m,o*f,c*d,o*h);break;case"ZXZ":n.set(c*d,c*m,o*f,o*h);break;case"XZX":n.set(o*f,c*x,c*g,o*h);break;case"YXY":n.set(c*g,o*f,c*x,o*h);break;case"ZYZ":n.set(c*x,c*g,o*f,o*h);break;default:ut("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+a)}}function Oa(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function jt(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}const $t={DEG2RAD:Uu,RAD2DEG:bd,generateUUID:Nr,clamp:Lt,euclideanModulo:yb,mapLinear:XF,inverseLerp:YF,lerp:Pm,damp:qF,pingpong:jF,smoothstep:ZF,smootherstep:KF,randInt:QF,randFloat:JF,randFloatSpread:$F,seededRandom:eG,degToRad:tG,radToDeg:nG,isPowerOfTwo:iG,ceilPowerOfTwo:aG,floorPowerOfTwo:rG,setQuaternionFromProperEuler:sG,normalize:jt,denormalize:Oa};class de{constructor(e=0,t=0){de.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,a=e.elements;return this.x=a[0]*t+a[3]*i+a[6],this.y=a[1]*t+a[4]*i+a[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Lt(this.x,e.x,t.x),this.y=Lt(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Lt(this.x,e,t),this.y=Lt(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Lt(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Lt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),a=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*i-s*a+e.x,this.y=r*a+s*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class St{constructor(e=0,t=0,i=0,a=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=a}static slerpFlat(e,t,i,a,r,s,o){let c=i[a+0],h=i[a+1],f=i[a+2],d=i[a+3],m=r[s+0],g=r[s+1],x=r[s+2],T=r[s+3];if(o<=0){e[t+0]=c,e[t+1]=h,e[t+2]=f,e[t+3]=d;return}if(o>=1){e[t+0]=m,e[t+1]=g,e[t+2]=x,e[t+3]=T;return}if(d!==T||c!==m||h!==g||f!==x){let y=c*m+h*g+f*x+d*T;y<0&&(m=-m,g=-g,x=-x,T=-T,y=-y);let v=1-o;if(y<.9995){const S=Math.acos(y),E=Math.sin(S);v=Math.sin(v*S)/E,o=Math.sin(o*S)/E,c=c*v+m*o,h=h*v+g*o,f=f*v+x*o,d=d*v+T*o}else{c=c*v+m*o,h=h*v+g*o,f=f*v+x*o,d=d*v+T*o;const S=1/Math.sqrt(c*c+h*h+f*f+d*d);c*=S,h*=S,f*=S,d*=S}}e[t]=c,e[t+1]=h,e[t+2]=f,e[t+3]=d}static multiplyQuaternionsFlat(e,t,i,a,r,s){const o=i[a],c=i[a+1],h=i[a+2],f=i[a+3],d=r[s],m=r[s+1],g=r[s+2],x=r[s+3];return e[t]=o*x+f*d+c*g-h*m,e[t+1]=c*x+f*m+h*d-o*g,e[t+2]=h*x+f*g+o*m-c*d,e[t+3]=f*x-o*d-c*m-h*g,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,a){return this._x=e,this._y=t,this._z=i,this._w=a,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,a=e._y,r=e._z,s=e._order,o=Math.cos,c=Math.sin,h=o(i/2),f=o(a/2),d=o(r/2),m=c(i/2),g=c(a/2),x=c(r/2);switch(s){case"XYZ":this._x=m*f*d+h*g*x,this._y=h*g*d-m*f*x,this._z=h*f*x+m*g*d,this._w=h*f*d-m*g*x;break;case"YXZ":this._x=m*f*d+h*g*x,this._y=h*g*d-m*f*x,this._z=h*f*x-m*g*d,this._w=h*f*d+m*g*x;break;case"ZXY":this._x=m*f*d-h*g*x,this._y=h*g*d+m*f*x,this._z=h*f*x+m*g*d,this._w=h*f*d-m*g*x;break;case"ZYX":this._x=m*f*d-h*g*x,this._y=h*g*d+m*f*x,this._z=h*f*x-m*g*d,this._w=h*f*d+m*g*x;break;case"YZX":this._x=m*f*d+h*g*x,this._y=h*g*d+m*f*x,this._z=h*f*x-m*g*d,this._w=h*f*d-m*g*x;break;case"XZY":this._x=m*f*d-h*g*x,this._y=h*g*d-m*f*x,this._z=h*f*x+m*g*d,this._w=h*f*d+m*g*x;break;default:ut("Quaternion: .setFromEuler() encountered an unknown order: "+s)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,a=Math.sin(i);return this._x=e.x*a,this._y=e.y*a,this._z=e.z*a,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],a=t[4],r=t[8],s=t[1],o=t[5],c=t[9],h=t[2],f=t[6],d=t[10],m=i+o+d;if(m>0){const g=.5/Math.sqrt(m+1);this._w=.25/g,this._x=(f-c)*g,this._y=(r-h)*g,this._z=(s-a)*g}else if(i>o&&i>d){const g=2*Math.sqrt(1+i-o-d);this._w=(f-c)/g,this._x=.25*g,this._y=(a+s)/g,this._z=(r+h)/g}else if(o>d){const g=2*Math.sqrt(1+o-i-d);this._w=(r-h)/g,this._x=(a+s)/g,this._y=.25*g,this._z=(c+f)/g}else{const g=2*Math.sqrt(1+d-i-o);this._w=(s-a)/g,this._x=(r+h)/g,this._y=(c+f)/g,this._z=.25*g}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Lt(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const a=Math.min(1,t/i);return this.slerp(e,a),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,a=e._y,r=e._z,s=e._w,o=t._x,c=t._y,h=t._z,f=t._w;return this._x=i*f+s*o+a*h-r*c,this._y=a*f+s*c+r*o-i*h,this._z=r*f+s*h+i*c-a*o,this._w=s*f-i*o-a*c-r*h,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let i=e._x,a=e._y,r=e._z,s=e._w,o=this.dot(e);o<0&&(i=-i,a=-a,r=-r,s=-s,o=-o);let c=1-t;if(o<.9995){const h=Math.acos(o),f=Math.sin(h);c=Math.sin(c*h)/f,t=Math.sin(t*h)/f,this._x=this._x*c+i*t,this._y=this._y*c+a*t,this._z=this._z*c+r*t,this._w=this._w*c+s*t,this._onChangeCallback()}else this._x=this._x*c+i*t,this._y=this._y*c+a*t,this._z=this._z*c+r*t,this._w=this._w*c+s*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),a=Math.sqrt(1-i),r=Math.sqrt(i);return this.set(a*Math.sin(e),a*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class L{constructor(e=0,t=0,i=0){L.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(h4.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(h4.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,a=this.z,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6]*a,this.y=r[1]*t+r[4]*i+r[7]*a,this.z=r[2]*t+r[5]*i+r[8]*a,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,a=this.z,r=e.elements,s=1/(r[3]*t+r[7]*i+r[11]*a+r[15]);return this.x=(r[0]*t+r[4]*i+r[8]*a+r[12])*s,this.y=(r[1]*t+r[5]*i+r[9]*a+r[13])*s,this.z=(r[2]*t+r[6]*i+r[10]*a+r[14])*s,this}applyQuaternion(e){const t=this.x,i=this.y,a=this.z,r=e.x,s=e.y,o=e.z,c=e.w,h=2*(s*a-o*i),f=2*(o*t-r*a),d=2*(r*i-s*t);return this.x=t+c*h+s*d-o*f,this.y=i+c*f+o*h-r*d,this.z=a+c*d+r*f-s*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 t=this.x,i=this.y,a=this.z,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*a,this.y=r[1]*t+r[5]*i+r[9]*a,this.z=r[2]*t+r[6]*i+r[10]*a,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Lt(this.x,e.x,t.x),this.y=Lt(this.y,e.y,t.y),this.z=Lt(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Lt(this.x,e,t),this.y=Lt(this.y,e,t),this.z=Lt(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Lt(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,a=e.y,r=e.z,s=t.x,o=t.y,c=t.z;return this.x=a*c-r*o,this.y=r*s-i*c,this.z=i*o-a*s,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return wT.copy(this).projectOnVector(e),this.sub(wT)}reflect(e){return this.sub(wT.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Lt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,a=this.z-e.z;return t*t+i*i+a*a}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const a=Math.sin(t)*e;return this.x=a*Math.sin(i),this.y=Math.cos(t)*e,this.z=a*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),a=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=a,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const wT=new L,h4=new St;class Et{constructor(e,t,i,a,r,s,o,c,h){Et.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,a,r,s,o,c,h)}set(e,t,i,a,r,s,o,c,h){const f=this.elements;return f[0]=e,f[1]=a,f[2]=o,f[3]=t,f[4]=r,f[5]=c,f[6]=i,f[7]=s,f[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,a=t.elements,r=this.elements,s=i[0],o=i[3],c=i[6],h=i[1],f=i[4],d=i[7],m=i[2],g=i[5],x=i[8],T=a[0],y=a[3],v=a[6],S=a[1],E=a[4],b=a[7],D=a[2],C=a[5],I=a[8];return r[0]=s*T+o*S+c*D,r[3]=s*y+o*E+c*C,r[6]=s*v+o*b+c*I,r[1]=h*T+f*S+d*D,r[4]=h*y+f*E+d*C,r[7]=h*v+f*b+d*I,r[2]=m*T+g*S+x*D,r[5]=m*y+g*E+x*C,r[8]=m*v+g*b+x*I,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],a=e[2],r=e[3],s=e[4],o=e[5],c=e[6],h=e[7],f=e[8];return t*s*f-t*o*h-i*r*f+i*o*c+a*r*h-a*s*c}invert(){const e=this.elements,t=e[0],i=e[1],a=e[2],r=e[3],s=e[4],o=e[5],c=e[6],h=e[7],f=e[8],d=f*s-o*h,m=o*c-f*r,g=h*r-s*c,x=t*d+i*m+a*g;if(x===0)return this.set(0,0,0,0,0,0,0,0,0);const T=1/x;return e[0]=d*T,e[1]=(a*h-f*i)*T,e[2]=(o*i-a*s)*T,e[3]=m*T,e[4]=(f*t-a*c)*T,e[5]=(a*r-o*t)*T,e[6]=g*T,e[7]=(i*c-h*t)*T,e[8]=(s*t-i*r)*T,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,a,r,s,o){const c=Math.cos(r),h=Math.sin(r);return this.set(i*c,i*h,-i*(c*s+h*o)+s+e,-a*h,a*c,-a*(-h*s+c*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(RT.makeScale(e,t)),this}rotate(e){return this.premultiply(RT.makeRotation(-e)),this}translate(e,t){return this.premultiply(RT.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let a=0;a<9;a++)if(t[a]!==i[a])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const RT=new Et,f4=new Et().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),d4=new Et().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function oG(){const n={enabled:!0,workingColorSpace:Wn,spaces:{},convert:function(a,r,s){return this.enabled===!1||r===s||!r||!s||(this.spaces[r].transfer===wn&&(a.r=Jo(a.r),a.g=Jo(a.g),a.b=Jo(a.b)),this.spaces[r].primaries!==this.spaces[s].primaries&&(a.applyMatrix3(this.spaces[r].toXYZ),a.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===wn&&(a.r=ad(a.r),a.g=ad(a.g),a.b=ad(a.b))),a},workingToColorSpace:function(a,r){return this.convert(a,this.workingColorSpace,r)},colorSpaceToWorking:function(a,r){return this.convert(a,r,this.workingColorSpace)},getPrimaries:function(a){return this.spaces[a].primaries},getTransfer:function(a){return a===Da?c0:this.spaces[a].transfer},getToneMappingMode:function(a){return this.spaces[a].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(a,r=this.workingColorSpace){return a.fromArray(this.spaces[r].luminanceCoefficients)},define:function(a){Object.assign(this.spaces,a)},_getMatrix:function(a,r,s){return a.copy(this.spaces[r].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(a){return this.spaces[a].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(a=this.workingColorSpace){return this.spaces[a].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(a,r){return Md("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(a,r)},toWorkingColorSpace:function(a,r){return Md("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(a,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[Wn]:{primaries:e,whitePoint:i,transfer:c0,toXYZ:f4,fromXYZ:d4,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:En},outputColorSpaceConfig:{drawingBufferColorSpace:En}},[En]:{primaries:e,whitePoint:i,transfer:wn,toXYZ:f4,fromXYZ:d4,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:En}}}),n}const rn=oG();function Jo(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function ad(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let Xh;class zU{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Xh===void 0&&(Xh=h0("canvas")),Xh.width=e.width,Xh.height=e.height;const a=Xh.getContext("2d");e instanceof ImageData?a.putImageData(e,0,0):a.drawImage(e,0,0,e.width,e.height),i=Xh}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=h0("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const a=i.getImageData(0,0,e.width,e.height),r=a.data;for(let s=0;s1),this.pmremVersion=0}get width(){return this.source.getSize(NT).x}get height(){return this.source.getSize(NT).y}get depth(){return this.source.getSize(NT).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){ut(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const a=this[t];if(a===void 0){ut(`Texture.setValues(): property '${t}' does not exist.`);continue}a&&i&&a.isVector2&&i.isVector2||a&&i&&a.isVector3&&i.isVector3||a&&i&&a.isMatrix3&&i.isMatrix3?a.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==C1)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Ea:e.x=e.x-Math.floor(e.x);break;case Pi:e.x=e.x<0?0:1;break;case xd: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 Ea:e.y=e.y-Math.floor(e.y);break;case Pi:e.y=e.y<0?0:1;break;case xd: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++}}Nn.DEFAULT_IMAGE=null;Nn.DEFAULT_MAPPING=C1;Nn.DEFAULT_ANISOTROPY=1;class zt{constructor(e=0,t=0,i=0,a=1){zt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=a}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,a){return this.x=e,this.y=t,this.z=i,this.w=a,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,a=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*a+s[12]*r,this.y=s[1]*t+s[5]*i+s[9]*a+s[13]*r,this.z=s[2]*t+s[6]*i+s[10]*a+s[14]*r,this.w=s[3]*t+s[7]*i+s[11]*a+s[15]*r,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 t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,a,r;const c=e.elements,h=c[0],f=c[4],d=c[8],m=c[1],g=c[5],x=c[9],T=c[2],y=c[6],v=c[10];if(Math.abs(f-m)<.01&&Math.abs(d-T)<.01&&Math.abs(x-y)<.01){if(Math.abs(f+m)<.1&&Math.abs(d+T)<.1&&Math.abs(x+y)<.1&&Math.abs(h+g+v-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const E=(h+1)/2,b=(g+1)/2,D=(v+1)/2,C=(f+m)/4,I=(d+T)/4,P=(x+y)/4;return E>b&&E>D?E<.01?(i=0,a=.707106781,r=.707106781):(i=Math.sqrt(E),a=C/i,r=I/i):b>D?b<.01?(i=.707106781,a=0,r=.707106781):(a=Math.sqrt(b),i=C/a,r=P/a):D<.01?(i=.707106781,a=.707106781,r=0):(r=Math.sqrt(D),i=I/r,a=P/r),this.set(i,a,r,t),this}let S=Math.sqrt((y-x)*(y-x)+(d-T)*(d-T)+(m-f)*(m-f));return Math.abs(S)<.001&&(S=1),this.x=(y-x)/S,this.y=(d-T)/S,this.z=(m-f)/S,this.w=Math.acos((h+g+v-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Lt(this.x,e.x,t.x),this.y=Lt(this.y,e.y,t.y),this.z=Lt(this.z,e.z,t.z),this.w=Lt(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Lt(this.x,e,t),this.y=Lt(this.y,e,t),this.z=Lt(this.z,e,t),this.w=Lt(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Lt(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Sb extends nr{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ht,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new zt(0,0,e,t),this.scissorTest=!1,this.viewport=new zt(0,0,e,t);const a={width:e,height:t,depth:i.depth},r=new Nn(a);this.textures=[];const s=i.count;for(let o=0;o1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,i=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,ms),ms.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Lp),qg.subVectors(this.max,Lp),Yh.subVectors(e.a,Lp),qh.subVectors(e.b,Lp),jh.subVectors(e.c,Lp),wl.subVectors(qh,Yh),Rl.subVectors(jh,qh),jc.subVectors(Yh,jh);let t=[0,-wl.z,wl.y,0,-Rl.z,Rl.y,0,-jc.z,jc.y,wl.z,0,-wl.x,Rl.z,0,-Rl.x,jc.z,0,-jc.x,-wl.y,wl.x,0,-Rl.y,Rl.x,0,-jc.y,jc.x,0];return!DT(t,Yh,qh,jh,qg)||(t=[1,0,0,0,1,0,0,0,1],!DT(t,Yh,qh,jh,qg))?!1:(jg.crossVectors(wl,Rl),t=[jg.x,jg.y,jg.z],DT(t,Yh,qh,jh,qg))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ms).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ms).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:(Ro[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ro[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ro[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ro[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ro[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ro[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ro[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ro[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ro),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 Ro=[new L,new L,new L,new L,new L,new L,new L,new L],ms=new L,Yg=new ta,Yh=new L,qh=new L,jh=new L,wl=new L,Rl=new L,jc=new L,Lp=new L,qg=new L,jg=new L,Zc=new L;function DT(n,e,t,i,a){for(let r=0,s=n.length-3;r<=s;r+=3){Zc.fromArray(n,r);const o=a.x*Math.abs(Zc.x)+a.y*Math.abs(Zc.y)+a.z*Math.abs(Zc.z),c=e.dot(Zc),h=t.dot(Zc),f=i.dot(Zc);if(Math.max(-Math.max(c,h,f),Math.min(c,h,f))>o)return!1}return!0}const uG=new ta,Ip=new L,OT=new L;class na{constructor(e=new L,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):uG.setFromPoints(e).getCenter(i);let a=0;for(let r=0,s=e.length;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Ip.subVectors(e,this.center);const t=Ip.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),a=(i-this.radius)*.5;this.center.addScaledVector(Ip,a/i),this.radius+=a}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):(OT.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ip.copy(e.center).add(OT)),this.expandByPoint(Ip.copy(e.center).sub(OT))),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}}const Co=new L,LT=new L,Zg=new L,Cl=new L,IT=new L,Kg=new L,UT=new L;class lh{constructor(e=new L,t=new L(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Co)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Co.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Co.copy(this.origin).addScaledVector(this.direction,t),Co.distanceToSquared(e))}distanceSqToSegment(e,t,i,a){LT.copy(e).add(t).multiplyScalar(.5),Zg.copy(t).sub(e).normalize(),Cl.copy(this.origin).sub(LT);const r=e.distanceTo(t)*.5,s=-this.direction.dot(Zg),o=Cl.dot(this.direction),c=-Cl.dot(Zg),h=Cl.lengthSq(),f=Math.abs(1-s*s);let d,m,g,x;if(f>0)if(d=s*c-o,m=s*o-c,x=r*f,d>=0)if(m>=-x)if(m<=x){const T=1/f;d*=T,m*=T,g=d*(d+s*m+2*o)+m*(s*d+m+2*c)+h}else m=r,d=Math.max(0,-(s*m+o)),g=-d*d+m*(m+2*c)+h;else m=-r,d=Math.max(0,-(s*m+o)),g=-d*d+m*(m+2*c)+h;else m<=-x?(d=Math.max(0,-(-s*r+o)),m=d>0?-r:Math.min(Math.max(-r,-c),r),g=-d*d+m*(m+2*c)+h):m<=x?(d=0,m=Math.min(Math.max(-r,-c),r),g=m*(m+2*c)+h):(d=Math.max(0,-(s*r+o)),m=d>0?r:Math.min(Math.max(-r,-c),r),g=-d*d+m*(m+2*c)+h);else m=s>0?-r:r,d=Math.max(0,-(s*m+o)),g=-d*d+m*(m+2*c)+h;return i&&i.copy(this.origin).addScaledVector(this.direction,d),a&&a.copy(LT).addScaledVector(Zg,m),g}intersectSphere(e,t){Co.subVectors(e.center,this.origin);const i=Co.dot(this.direction),a=Co.dot(Co)-i*i,r=e.radius*e.radius;if(a>r)return null;const s=Math.sqrt(r-a),o=i-s,c=i+s;return c<0?null:o<0?this.at(c,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,a,r,s,o,c;const h=1/this.direction.x,f=1/this.direction.y,d=1/this.direction.z,m=this.origin;return h>=0?(i=(e.min.x-m.x)*h,a=(e.max.x-m.x)*h):(i=(e.max.x-m.x)*h,a=(e.min.x-m.x)*h),f>=0?(r=(e.min.y-m.y)*f,s=(e.max.y-m.y)*f):(r=(e.max.y-m.y)*f,s=(e.min.y-m.y)*f),i>s||r>a||((r>i||isNaN(i))&&(i=r),(s=0?(o=(e.min.z-m.z)*d,c=(e.max.z-m.z)*d):(o=(e.max.z-m.z)*d,c=(e.min.z-m.z)*d),i>c||o>a)||((o>i||i!==i)&&(i=o),(c=0?i:a,t)}intersectsBox(e){return this.intersectBox(e,Co)!==null}intersectTriangle(e,t,i,a,r){IT.subVectors(t,e),Kg.subVectors(i,e),UT.crossVectors(IT,Kg);let s=this.direction.dot(UT),o;if(s>0){if(a)return null;o=1}else if(s<0)o=-1,s=-s;else return null;Cl.subVectors(this.origin,e);const c=o*this.direction.dot(Kg.crossVectors(Cl,Kg));if(c<0)return null;const h=o*this.direction.dot(IT.cross(Cl));if(h<0||c+h>s)return null;const f=-o*Cl.dot(UT);return f<0?null:this.at(f/s,r)}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 ke{constructor(e,t,i,a,r,s,o,c,h,f,d,m,g,x,T,y){ke.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,a,r,s,o,c,h,f,d,m,g,x,T,y)}set(e,t,i,a,r,s,o,c,h,f,d,m,g,x,T,y){const v=this.elements;return v[0]=e,v[4]=t,v[8]=i,v[12]=a,v[1]=r,v[5]=s,v[9]=o,v[13]=c,v[2]=h,v[6]=f,v[10]=d,v[14]=m,v[3]=g,v[7]=x,v[11]=T,v[15]=y,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new ke().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,a=1/Zh.setFromMatrixColumn(e,0).length(),r=1/Zh.setFromMatrixColumn(e,1).length(),s=1/Zh.setFromMatrixColumn(e,2).length();return t[0]=i[0]*a,t[1]=i[1]*a,t[2]=i[2]*a,t[3]=0,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=0,t[8]=i[8]*s,t[9]=i[9]*s,t[10]=i[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,a=e.y,r=e.z,s=Math.cos(i),o=Math.sin(i),c=Math.cos(a),h=Math.sin(a),f=Math.cos(r),d=Math.sin(r);if(e.order==="XYZ"){const m=s*f,g=s*d,x=o*f,T=o*d;t[0]=c*f,t[4]=-c*d,t[8]=h,t[1]=g+x*h,t[5]=m-T*h,t[9]=-o*c,t[2]=T-m*h,t[6]=x+g*h,t[10]=s*c}else if(e.order==="YXZ"){const m=c*f,g=c*d,x=h*f,T=h*d;t[0]=m+T*o,t[4]=x*o-g,t[8]=s*h,t[1]=s*d,t[5]=s*f,t[9]=-o,t[2]=g*o-x,t[6]=T+m*o,t[10]=s*c}else if(e.order==="ZXY"){const m=c*f,g=c*d,x=h*f,T=h*d;t[0]=m-T*o,t[4]=-s*d,t[8]=x+g*o,t[1]=g+x*o,t[5]=s*f,t[9]=T-m*o,t[2]=-s*h,t[6]=o,t[10]=s*c}else if(e.order==="ZYX"){const m=s*f,g=s*d,x=o*f,T=o*d;t[0]=c*f,t[4]=x*h-g,t[8]=m*h+T,t[1]=c*d,t[5]=T*h+m,t[9]=g*h-x,t[2]=-h,t[6]=o*c,t[10]=s*c}else if(e.order==="YZX"){const m=s*c,g=s*h,x=o*c,T=o*h;t[0]=c*f,t[4]=T-m*d,t[8]=x*d+g,t[1]=d,t[5]=s*f,t[9]=-o*f,t[2]=-h*f,t[6]=g*d+x,t[10]=m-T*d}else if(e.order==="XZY"){const m=s*c,g=s*h,x=o*c,T=o*h;t[0]=c*f,t[4]=-d,t[8]=h*f,t[1]=m*d+T,t[5]=s*f,t[9]=g*d-x,t[2]=x*d-g,t[6]=o*f,t[10]=T*d+m}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(hG,e,fG)}lookAt(e,t,i){const a=this.elements;return vr.subVectors(e,t),vr.lengthSq()===0&&(vr.z=1),vr.normalize(),Nl.crossVectors(i,vr),Nl.lengthSq()===0&&(Math.abs(i.z)===1?vr.x+=1e-4:vr.z+=1e-4,vr.normalize(),Nl.crossVectors(i,vr)),Nl.normalize(),Qg.crossVectors(vr,Nl),a[0]=Nl.x,a[4]=Qg.x,a[8]=vr.x,a[1]=Nl.y,a[5]=Qg.y,a[9]=vr.y,a[2]=Nl.z,a[6]=Qg.z,a[10]=vr.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,a=t.elements,r=this.elements,s=i[0],o=i[4],c=i[8],h=i[12],f=i[1],d=i[5],m=i[9],g=i[13],x=i[2],T=i[6],y=i[10],v=i[14],S=i[3],E=i[7],b=i[11],D=i[15],C=a[0],I=a[4],P=a[8],O=a[12],w=a[1],B=a[5],j=a[9],ee=a[13],se=a[2],re=a[6],W=a[10],te=a[14],K=a[3],oe=a[7],ie=a[11],Ce=a[15];return r[0]=s*C+o*w+c*se+h*K,r[4]=s*I+o*B+c*re+h*oe,r[8]=s*P+o*j+c*W+h*ie,r[12]=s*O+o*ee+c*te+h*Ce,r[1]=f*C+d*w+m*se+g*K,r[5]=f*I+d*B+m*re+g*oe,r[9]=f*P+d*j+m*W+g*ie,r[13]=f*O+d*ee+m*te+g*Ce,r[2]=x*C+T*w+y*se+v*K,r[6]=x*I+T*B+y*re+v*oe,r[10]=x*P+T*j+y*W+v*ie,r[14]=x*O+T*ee+y*te+v*Ce,r[3]=S*C+E*w+b*se+D*K,r[7]=S*I+E*B+b*re+D*oe,r[11]=S*P+E*j+b*W+D*ie,r[15]=S*O+E*ee+b*te+D*Ce,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],a=e[8],r=e[12],s=e[1],o=e[5],c=e[9],h=e[13],f=e[2],d=e[6],m=e[10],g=e[14],x=e[3],T=e[7],y=e[11],v=e[15];return x*(+r*c*d-a*h*d-r*o*m+i*h*m+a*o*g-i*c*g)+T*(+t*c*g-t*h*m+r*s*m-a*s*g+a*h*f-r*c*f)+y*(+t*h*d-t*o*g-r*s*d+i*s*g+r*o*f-i*h*f)+v*(-a*o*f-t*c*d+t*o*m+a*s*d-i*s*m+i*c*f)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const a=this.elements;return e.isVector3?(a[12]=e.x,a[13]=e.y,a[14]=e.z):(a[12]=e,a[13]=t,a[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],a=e[2],r=e[3],s=e[4],o=e[5],c=e[6],h=e[7],f=e[8],d=e[9],m=e[10],g=e[11],x=e[12],T=e[13],y=e[14],v=e[15],S=d*y*h-T*m*h+T*c*g-o*y*g-d*c*v+o*m*v,E=x*m*h-f*y*h-x*c*g+s*y*g+f*c*v-s*m*v,b=f*T*h-x*d*h+x*o*g-s*T*g-f*o*v+s*d*v,D=x*d*c-f*T*c-x*o*m+s*T*m+f*o*y-s*d*y,C=t*S+i*E+a*b+r*D;if(C===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const I=1/C;return e[0]=S*I,e[1]=(T*m*r-d*y*r-T*a*g+i*y*g+d*a*v-i*m*v)*I,e[2]=(o*y*r-T*c*r+T*a*h-i*y*h-o*a*v+i*c*v)*I,e[3]=(d*c*r-o*m*r-d*a*h+i*m*h+o*a*g-i*c*g)*I,e[4]=E*I,e[5]=(f*y*r-x*m*r+x*a*g-t*y*g-f*a*v+t*m*v)*I,e[6]=(x*c*r-s*y*r-x*a*h+t*y*h+s*a*v-t*c*v)*I,e[7]=(s*m*r-f*c*r+f*a*h-t*m*h-s*a*g+t*c*g)*I,e[8]=b*I,e[9]=(x*d*r-f*T*r-x*i*g+t*T*g+f*i*v-t*d*v)*I,e[10]=(s*T*r-x*o*r+x*i*h-t*T*h-s*i*v+t*o*v)*I,e[11]=(f*o*r-s*d*r-f*i*h+t*d*h+s*i*g-t*o*g)*I,e[12]=D*I,e[13]=(f*T*a-x*d*a+x*i*m-t*T*m-f*i*y+t*d*y)*I,e[14]=(x*o*a-s*T*a-x*i*c+t*T*c+s*i*y-t*o*y)*I,e[15]=(s*d*a-f*o*a+f*i*c-t*d*c-s*i*m+t*o*m)*I,this}scale(e){const t=this.elements,i=e.x,a=e.y,r=e.z;return t[0]*=i,t[4]*=a,t[8]*=r,t[1]*=i,t[5]*=a,t[9]*=r,t[2]*=i,t[6]*=a,t[10]*=r,t[3]*=i,t[7]*=a,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],a=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,a))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),a=Math.sin(t),r=1-i,s=e.x,o=e.y,c=e.z,h=r*s,f=r*o;return this.set(h*s+i,h*o-a*c,h*c+a*o,0,h*o+a*c,f*o+i,f*c-a*s,0,h*c-a*o,f*c+a*s,r*c*c+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,a,r,s){return this.set(1,i,r,0,e,1,s,0,t,a,1,0,0,0,0,1),this}compose(e,t,i){const a=this.elements,r=t._x,s=t._y,o=t._z,c=t._w,h=r+r,f=s+s,d=o+o,m=r*h,g=r*f,x=r*d,T=s*f,y=s*d,v=o*d,S=c*h,E=c*f,b=c*d,D=i.x,C=i.y,I=i.z;return a[0]=(1-(T+v))*D,a[1]=(g+b)*D,a[2]=(x-E)*D,a[3]=0,a[4]=(g-b)*C,a[5]=(1-(m+v))*C,a[6]=(y+S)*C,a[7]=0,a[8]=(x+E)*I,a[9]=(y-S)*I,a[10]=(1-(m+T))*I,a[11]=0,a[12]=e.x,a[13]=e.y,a[14]=e.z,a[15]=1,this}decompose(e,t,i){const a=this.elements;let r=Zh.set(a[0],a[1],a[2]).length();const s=Zh.set(a[4],a[5],a[6]).length(),o=Zh.set(a[8],a[9],a[10]).length();this.determinant()<0&&(r=-r),e.x=a[12],e.y=a[13],e.z=a[14],gs.copy(this);const h=1/r,f=1/s,d=1/o;return gs.elements[0]*=h,gs.elements[1]*=h,gs.elements[2]*=h,gs.elements[4]*=f,gs.elements[5]*=f,gs.elements[6]*=f,gs.elements[8]*=d,gs.elements[9]*=d,gs.elements[10]*=d,t.setFromRotationMatrix(gs),i.x=r,i.y=s,i.z=o,this}makePerspective(e,t,i,a,r,s,o=br,c=!1){const h=this.elements,f=2*r/(t-e),d=2*r/(i-a),m=(t+e)/(t-e),g=(i+a)/(i-a);let x,T;if(c)x=r/(s-r),T=s*r/(s-r);else if(o===br)x=-(s+r)/(s-r),T=-2*s*r/(s-r);else if(o===Ed)x=-s/(s-r),T=-s*r/(s-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return h[0]=f,h[4]=0,h[8]=m,h[12]=0,h[1]=0,h[5]=d,h[9]=g,h[13]=0,h[2]=0,h[6]=0,h[10]=x,h[14]=T,h[3]=0,h[7]=0,h[11]=-1,h[15]=0,this}makeOrthographic(e,t,i,a,r,s,o=br,c=!1){const h=this.elements,f=2/(t-e),d=2/(i-a),m=-(t+e)/(t-e),g=-(i+a)/(i-a);let x,T;if(c)x=1/(s-r),T=s/(s-r);else if(o===br)x=-2/(s-r),T=-(s+r)/(s-r);else if(o===Ed)x=-1/(s-r),T=-r/(s-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return h[0]=f,h[4]=0,h[8]=0,h[12]=m,h[1]=0,h[5]=d,h[9]=0,h[13]=g,h[2]=0,h[6]=0,h[10]=x,h[14]=T,h[3]=0,h[7]=0,h[11]=0,h[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let a=0;a<16;a++)if(t[a]!==i[a])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const Zh=new L,gs=new ke,hG=new L(0,0,0),fG=new L(1,1,1),Nl=new L,Qg=new L,vr=new L,p4=new ke,m4=new St;class Ei{constructor(e=0,t=0,i=0,a=Ei.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=a}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,a=this._order){return this._x=e,this._y=t,this._z=i,this._order=a,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const a=e.elements,r=a[0],s=a[4],o=a[8],c=a[1],h=a[5],f=a[9],d=a[2],m=a[6],g=a[10];switch(t){case"XYZ":this._y=Math.asin(Lt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-f,g),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(m,h),this._z=0);break;case"YXZ":this._x=Math.asin(-Lt(f,-1,1)),Math.abs(f)<.9999999?(this._y=Math.atan2(o,g),this._z=Math.atan2(c,h)):(this._y=Math.atan2(-d,r),this._z=0);break;case"ZXY":this._x=Math.asin(Lt(m,-1,1)),Math.abs(m)<.9999999?(this._y=Math.atan2(-d,g),this._z=Math.atan2(-s,h)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-Lt(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(m,g),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-s,h));break;case"YZX":this._z=Math.asin(Lt(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-f,h),this._y=Math.atan2(-d,r)):(this._x=0,this._y=Math.atan2(o,g));break;case"XZY":this._z=Math.asin(-Lt(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(m,h),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-f,g),this._y=0);break;default:ut("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return p4.makeRotationFromQuaternion(e),this.setFromRotationMatrix(p4,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return m4.setFromEuler(this),this.setFromQuaternion(m4,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Ei.DEFAULT_ORDER="XYZ";class Ad{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(a.userData=this.userData),a.layers=this.layers.mask,a.matrix=this.matrix.toArray(),a.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(a.matrixAutoUpdate=!1),this.isInstancedMesh&&(a.type="InstancedMesh",a.count=this.count,a.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(a.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(a.type="BatchedMesh",a.perObjectFrustumCulled=this.perObjectFrustumCulled,a.sortObjects=this.sortObjects,a.drawRanges=this._drawRanges,a.reservedRanges=this._reservedRanges,a.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),a.instanceInfo=this._instanceInfo.map(o=>({...o})),a.availableInstanceIds=this._availableInstanceIds.slice(),a.availableGeometryIds=this._availableGeometryIds.slice(),a.nextIndexStart=this._nextIndexStart,a.nextVertexStart=this._nextVertexStart,a.geometryCount=this._geometryCount,a.maxInstanceCount=this._maxInstanceCount,a.maxVertexCount=this._maxVertexCount,a.maxIndexCount=this._maxIndexCount,a.geometryInitialized=this._geometryInitialized,a.matricesTexture=this._matricesTexture.toJSON(e),a.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(a.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(a.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(a.boundingBox=this.boundingBox.toJSON()));function r(o,c){return o[c.uuid]===void 0&&(o[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?a.background=this.background.toJSON():this.background.isTexture&&(a.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(a.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){a.geometry=r(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const c=o.shapes;if(Array.isArray(c))for(let h=0,f=c.length;h0){a.children=[];for(let o=0;o0){a.animations=[];for(let o=0;o0&&(i.geometries=o),c.length>0&&(i.materials=c),h.length>0&&(i.textures=h),f.length>0&&(i.images=f),d.length>0&&(i.shapes=d),m.length>0&&(i.skeletons=m),g.length>0&&(i.animations=g),x.length>0&&(i.nodes=x)}return i.object=a,i;function s(o){const c=[];for(const h in o){const f=o[h];delete f.metadata,c.push(f)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i0?a.multiplyScalar(1/Math.sqrt(r)):a.set(0,0,0)}static getBarycoord(e,t,i,a,r){vs.subVectors(a,t),Do.subVectors(i,t),zT.subVectors(e,t);const s=vs.dot(vs),o=vs.dot(Do),c=vs.dot(zT),h=Do.dot(Do),f=Do.dot(zT),d=s*h-o*o;if(d===0)return r.set(0,0,0),null;const m=1/d,g=(h*c-o*f)*m,x=(s*f-o*c)*m;return r.set(1-g-x,x,g)}static containsPoint(e,t,i,a){return this.getBarycoord(e,t,i,a,Oo)===null?!1:Oo.x>=0&&Oo.y>=0&&Oo.x+Oo.y<=1}static getInterpolation(e,t,i,a,r,s,o,c){return this.getBarycoord(e,t,i,a,Oo)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(r,Oo.x),c.addScaledVector(s,Oo.y),c.addScaledVector(o,Oo.z),c)}static getInterpolatedAttribute(e,t,i,a,r,s){return GT.setScalar(0),VT.setScalar(0),kT.setScalar(0),GT.fromBufferAttribute(e,t),VT.fromBufferAttribute(e,i),kT.fromBufferAttribute(e,a),s.setScalar(0),s.addScaledVector(GT,r.x),s.addScaledVector(VT,r.y),s.addScaledVector(kT,r.z),s}static isFrontFacing(e,t,i,a){return vs.subVectors(i,t),Do.subVectors(e,t),vs.cross(Do).dot(a)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,a){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[a]),this}setFromAttributeAndIndices(e,t,i,a){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,a),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 vs.subVectors(this.c,this.b),Do.subVectors(this.a,this.b),vs.cross(Do).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Qa.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Qa.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,a,r){return Qa.getInterpolation(e,this.a,this.b,this.c,t,i,a,r)}containsPoint(e){return Qa.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Qa.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,a=this.b,r=this.c;let s,o;Jh.subVectors(a,i),$h.subVectors(r,i),BT.subVectors(e,i);const c=Jh.dot(BT),h=$h.dot(BT);if(c<=0&&h<=0)return t.copy(i);HT.subVectors(e,a);const f=Jh.dot(HT),d=$h.dot(HT);if(f>=0&&d<=f)return t.copy(a);const m=c*d-f*h;if(m<=0&&c>=0&&f<=0)return s=c/(c-f),t.copy(i).addScaledVector(Jh,s);FT.subVectors(e,r);const g=Jh.dot(FT),x=$h.dot(FT);if(x>=0&&g<=x)return t.copy(r);const T=g*h-c*x;if(T<=0&&h>=0&&x<=0)return o=h/(h-x),t.copy(i).addScaledVector($h,o);const y=f*x-g*d;if(y<=0&&d-f>=0&&g-x>=0)return S4.subVectors(r,a),o=(d-f)/(d-f+(g-x)),t.copy(a).addScaledVector(S4,o);const v=1/(y+T+m);return s=T*v,o=m*v,t.copy(i).addScaledVector(Jh,s).addScaledVector($h,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const FU={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},Dl={h:0,s:0,l:0},$g={h:0,s:0,l:0};function WT(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class je{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const a=e;a&&a.isColor?this.copy(a):typeof a=="number"?this.setHex(a):typeof a=="string"&&this.setStyle(a)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=En){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,rn.colorSpaceToWorking(this,t),this}setRGB(e,t,i,a=rn.workingColorSpace){return this.r=e,this.g=t,this.b=i,rn.colorSpaceToWorking(this,a),this}setHSL(e,t,i,a=rn.workingColorSpace){if(e=yb(e,1),t=Lt(t,0,1),i=Lt(i,0,1),t===0)this.r=this.g=this.b=i;else{const r=i<=.5?i*(1+t):i+t-i*t,s=2*i-r;this.r=WT(s,r,e+1/3),this.g=WT(s,r,e),this.b=WT(s,r,e-1/3)}return rn.colorSpaceToWorking(this,a),this}setStyle(e,t=En){function i(r){r!==void 0&&parseFloat(r)<1&&ut("Color: Alpha component of "+e+" will be ignored.")}let a;if(a=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=a[1],o=a[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:ut("Color: Unknown color model "+e)}}else if(a=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=a[1],s=r.length;if(s===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(s===6)return this.setHex(parseInt(r,16),t);ut("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=En){const i=FU[e.toLowerCase()];return i!==void 0?this.setHex(i,t):ut("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=Jo(e.r),this.g=Jo(e.g),this.b=Jo(e.b),this}copyLinearToSRGB(e){return this.r=ad(e.r),this.g=ad(e.g),this.b=ad(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=En){return rn.workingToColorSpace(xa.copy(this),e),Math.round(Lt(xa.r*255,0,255))*65536+Math.round(Lt(xa.g*255,0,255))*256+Math.round(Lt(xa.b*255,0,255))}getHexString(e=En){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=rn.workingColorSpace){rn.workingToColorSpace(xa.copy(this),t);const i=xa.r,a=xa.g,r=xa.b,s=Math.max(i,a,r),o=Math.min(i,a,r);let c,h;const f=(o+s)/2;if(o===s)c=0,h=0;else{const d=s-o;switch(h=f<=.5?d/(s+o):d/(2-s-o),s){case i:c=(a-r)/d+(a0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){ut(`Material: parameter '${t}' has value of undefined.`);continue}const a=this[t];if(a===void 0){ut(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}a&&a.isColor?a.set(i):a&&a.isVector3&&i&&i.isVector3?a.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==Iu&&(i.blending=this.blending),this.side!==Ns&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==ex&&(i.blendSrc=this.blendSrc),this.blendDst!==tx&&(i.blendDst=this.blendDst),this.blendEquation!==Js&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==Xu&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==sE&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==xu&&(i.stencilFail=this.stencilFail),this.stencilZFail!==xu&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==xu&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function a(r){const s=[];for(const o in r){const c=r[o];delete c.metadata,s.push(c)}return s}if(t){const r=a(e.textures),s=a(e.images);r.length>0&&(i.textures=r),s.length>0&&(i.images=s)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const a=t.length;i=new Array(a);for(let r=0;r!==a;++r)i[r]=t[r].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Ia extends qn{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new je(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 Ei,this.combine=O0,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 Wo=_G();function _G(){const n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),a=new Uint32Array(512);for(let c=0;c<256;++c){const h=c-127;h<-27?(i[c]=0,i[c|256]=32768,a[c]=24,a[c|256]=24):h<-14?(i[c]=1024>>-h-14,i[c|256]=1024>>-h-14|32768,a[c]=-h-1,a[c|256]=-h-1):h<=15?(i[c]=h+15<<10,i[c|256]=h+15<<10|32768,a[c]=13,a[c|256]=13):h<128?(i[c]=31744,i[c|256]=64512,a[c]=24,a[c|256]=24):(i[c]=31744,i[c|256]=64512,a[c]=13,a[c|256]=13)}const r=new Uint32Array(2048),s=new Uint32Array(64),o=new Uint32Array(64);for(let c=1;c<1024;++c){let h=c<<13,f=0;for(;!(h&8388608);)h<<=1,f-=8388608;h&=-8388609,f+=947912704,r[c]=h|f}for(let c=1024;c<2048;++c)r[c]=939524096+(c-1024<<13);for(let c=1;c<31;++c)s[c]=c<<23;s[31]=1199570944,s[32]=2147483648;for(let c=33;c<63;++c)s[c]=2147483648+(c-32<<23);s[63]=3347054592;for(let c=1;c<64;++c)c!==32&&(o[c]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:a,mantissaTable:r,exponentTable:s,offsetTable:o}}function Ya(n){Math.abs(n)>65504&&ut("DataUtils.toHalfFloat(): Value out of range."),n=Lt(n,-65504,65504),Wo.floatView[0]=n;const e=Wo.uint32View[0],t=e>>23&511;return Wo.baseTable[t]+((e&8388607)>>Wo.shiftTable[t])}function cm(n){const e=n>>10;return Wo.uint32View[0]=Wo.mantissaTable[Wo.offsetTable[e]+(n&1023)]+Wo.exponentTable[e],Wo.floatView[0]}class oE{static toHalfFloat(e){return Ya(e)}static fromHalfFloat(e){return cm(e)}}const Ci=new L,ev=new de;let xG=0;class Ot{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:xG++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=u0,this.updateRanges=[],this.gpuType=si,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let a=0,r=this.itemSize;at.count&&ut("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new ta);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Bt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new L(-1/0,-1/0,-1/0),new L(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,a=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const h in c)c[h]!==void 0&&(e[h]=c[h]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const c in i){const h=i[c];e.data.attributes[c]=h.toJSON(e.data)}const a={};let r=!1;for(const c in this.morphAttributes){const h=this.morphAttributes[c],f=[];for(let d=0,m=h.length;d0&&(a[c]=f,r=!0)}r&&(e.data.morphAttributes=a,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const a=e.attributes;for(const h in a){const f=a[h];this.setAttribute(h,f.clone(t))}const r=e.morphAttributes;for(const h in r){const f=[],d=r[h];for(let m=0,g=d.length;m0){const a=t[i[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,s=a.length;r(e.far-e.near)**2))&&(T4.copy(r).invert(),Kc.copy(e.ray).applyMatrix4(T4),!(i.boundingBox!==null&&Kc.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,Kc)))}_computeIntersections(e,t,i){let a;const r=this.geometry,s=this.material,o=r.index,c=r.attributes.position,h=r.attributes.uv,f=r.attributes.uv1,d=r.attributes.normal,m=r.groups,g=r.drawRange;if(o!==null)if(Array.isArray(s))for(let x=0,T=m.length;xt.far?null:{distance:h,point:sv.clone(),object:n}}function ov(n,e,t,i,a,r,s,o,c,h){n.getVertexPosition(o,nv),n.getVertexPosition(c,iv),n.getVertexPosition(h,av);const f=wG(n,e,t,i,nv,iv,av,M4);if(f){const d=new L;Qa.getBarycoord(M4,nv,iv,av,d),a&&(f.uv=Qa.getInterpolatedAttribute(a,o,c,h,d,new de)),r&&(f.uv1=Qa.getInterpolatedAttribute(r,o,c,h,d,new de)),s&&(f.normal=Qa.getInterpolatedAttribute(s,o,c,h,d,new L),f.normal.dot(i.direction)>0&&f.normal.multiplyScalar(-1));const m={a:o,b:c,c:h,normal:new L,materialIndex:0};Qa.getNormal(nv,iv,av,m.normal),f.face=m,f.barycoord=d}return f}class ch extends Ct{constructor(e=1,t=1,i=1,a=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:a,heightSegments:r,depthSegments:s};const o=this;a=Math.floor(a),r=Math.floor(r),s=Math.floor(s);const c=[],h=[],f=[],d=[];let m=0,g=0;x("z","y","x",-1,-1,i,t,e,s,r,0),x("z","y","x",1,-1,i,t,-e,s,r,1),x("x","z","y",1,1,e,i,t,a,s,2),x("x","z","y",1,-1,e,i,-t,a,s,3),x("x","y","z",1,-1,e,t,i,a,r,4),x("x","y","z",-1,-1,e,t,-i,a,r,5),this.setIndex(c),this.setAttribute("position",new xt(h,3)),this.setAttribute("normal",new xt(f,3)),this.setAttribute("uv",new xt(d,2));function x(T,y,v,S,E,b,D,C,I,P,O){const w=b/I,B=D/P,j=b/2,ee=D/2,se=C/2,re=I+1,W=P+1;let te=0,K=0;const oe=new L;for(let ie=0;ie0?1:-1,f.push(oe.x,oe.y,oe.z),d.push(Xe/I),d.push(1-ie/P),te+=1}}for(let ie=0;ie0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const a in this.extensions)this.extensions[a]===!0&&(i[a]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class bc extends Wt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ke,this.projectionMatrix=new ke,this.projectionMatrixInverse=new ke,this.coordinateSystem=br,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Ol=new L,b4=new de,A4=new de;let hi=class extends bc{constructor(e=50,t=1,i=.1,a=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=a,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=bd*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Uu*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return bd*2*Math.atan(Math.tan(Uu*.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,t,i){Ol.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ol.x,Ol.y).multiplyScalar(-e/Ol.z),Ol.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Ol.x,Ol.y).multiplyScalar(-e/Ol.z)}getViewSize(e,t){return this.getViewBounds(e,b4,A4),t.subVectors(A4,b4)}setViewOffset(e,t,i,a,r,s){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=a,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Uu*.5*this.fov)/this.zoom,i=2*t,a=this.aspect*i,r=-.5*a;const s=this.view;if(this.view!==null&&this.view.enabled){const c=s.fullWidth,h=s.fullHeight;r+=s.offsetX*a/c,t-=s.offsetY*i/h,a*=s.width/c,i*=s.height/h}const o=this.filmOffset;o!==0&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+a,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}};const tf=-90,nf=1;class VU extends Wt{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const a=new hi(tf,nf,e,t);a.layers=this.layers,this.add(a);const r=new hi(tf,nf,e,t);r.layers=this.layers,this.add(r);const s=new hi(tf,nf,e,t);s.layers=this.layers,this.add(s);const o=new hi(tf,nf,e,t);o.layers=this.layers,this.add(o);const c=new hi(tf,nf,e,t);c.layers=this.layers,this.add(c);const h=new hi(tf,nf,e,t);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,a,r,s,o,c]=t;for(const h of t)this.remove(h);if(e===br)i.up.set(0,1,0),i.lookAt(1,0,0),a.up.set(0,1,0),a.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===Ed)i.up.set(0,-1,0),i.lookAt(-1,0,0),a.up.set(0,-1,0),a.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const h of t)this.add(h),h.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:a}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,o,c,h,f]=this.children,d=e.getRenderTarget(),m=e.getActiveCubeFace(),g=e.getActiveMipmapLevel(),x=e.xr.enabled;e.xr.enabled=!1;const T=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,a),e.render(t,r),e.setRenderTarget(i,1,a),e.render(t,s),e.setRenderTarget(i,2,a),e.render(t,o),e.setRenderTarget(i,3,a),e.render(t,c),e.setRenderTarget(i,4,a),e.render(t,h),i.texture.generateMipmaps=T,e.setRenderTarget(i,5,a),e.render(t,f),e.setRenderTarget(d,m,g),e.xr.enabled=x,i.texture.needsPMREMUpdate=!0}}class U0 extends Nn{constructor(e=[],t=rl,i,a,r,s,o,c,h,f){super(e,t,i,a,r,s,o,c,h,f),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class kU extends xi{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},a=[i,i,i,i,i,i];this.texture=new U0(a),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={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 ); - - } - `},a=new ch(5,5,5),r=new Vi({name:"CubemapFromEquirect",uniforms:wd(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:Ui,blending:Ta});r.uniforms.tEquirect.value=t;const s=new oi(a,r),o=t.minFilter;return t.minFilter===Mr&&(t.minFilter=Ht),new VU(1,10,this).update(e,s),t.minFilter=o,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,i=!0,a=!0){const r=e.getRenderTarget();for(let s=0;s<6;s++)e.setRenderTarget(this,s),e.clear(t,i,a);e.setRenderTarget(r)}}class Ua extends Wt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const DG={type:"move"};class g_{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Ua,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Ua,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new L,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new L),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Ua,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new L,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new L),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let a=null,r=null,s=null;const o=this._targetRay,c=this._grip,h=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(h&&e.hand){s=!0;for(const T of e.hand.values()){const y=t.getJointPose(T,i),v=this._getHandJoint(h,T);y!==null&&(v.matrix.fromArray(y.transform.matrix),v.matrix.decompose(v.position,v.rotation,v.scale),v.matrixWorldNeedsUpdate=!0,v.jointRadius=y.radius),v.visible=y!==null}const f=h.joints["index-finger-tip"],d=h.joints["thumb-tip"],m=f.position.distanceTo(d.position),g=.02,x=.005;h.inputState.pinching&&m>g+x?(h.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!h.inputState.pinching&&m<=g-x&&(h.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,i),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1));o!==null&&(a=t.getPose(e.targetRaySpace,i),a===null&&r!==null&&(a=r),a!==null&&(o.matrix.fromArray(a.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,a.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(a.linearVelocity)):o.hasLinearVelocity=!1,a.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(a.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(DG)))}return o!==null&&(o.visible=a!==null),c!==null&&(c.visible=r!==null),h!==null&&(h.visible=s!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Ua;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class H1{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new je(e),this.density=t}clone(){return new H1(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class F1{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new je(e),this.near=t,this.far=i}clone(){return new F1(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Rd extends Wt{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Ei,this.environmentIntensity=1,this.environmentRotation=new Ei,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class P0{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=u0,this.updateRanges=[],this.version=0,this.uuid=Nr()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let a=0,r=this.stride;ae.far||t.push({distance:c,point:zp.clone(),uv:Qa.getInterpolation(zp,lv,Hp,cv,w4,qT,R4,new de),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function uv(n,e,t,i,a,r){of.subVectors(n,t).addScalar(.5).multiply(i),a!==void 0?(Bp.x=r*of.x-a*of.y,Bp.y=a*of.x+r*of.y):Bp.copy(of),n.copy(e),n.x+=Bp.x,n.y+=Bp.y,n.applyMatrix4(WU)}const hv=new L,C4=new L;class YU extends Wt{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,a=t.length;i0){let i,a;for(i=1,a=t.length;i0){hv.setFromMatrixPosition(this.matrixWorld);const a=e.ray.origin.distanceTo(hv);this.getObjectForDistance(a).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){hv.setFromMatrixPosition(e.matrixWorld),C4.setFromMatrixPosition(this.matrixWorld);const i=hv.distanceTo(C4)/e.zoom;t[0].object.visible=!0;let a,r;for(a=1,r=t.length;a=s)t[a-1].object.visible=!1,t[a].object.visible=!0;else break}for(this._currentLevel=a-1;a1?null:t.copy(e.start).addScaledVector(i,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||PG.getNormalMatrix(e),a=this.coplanarPoint(KT).applyMatrix4(e),r=this.normal.applyMatrix3(i).normalize();return this.constant=-a.dot(r),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 Qc=new na,zG=new de(.5,.5),pv=new L;class Yd{constructor(e=new Go,t=new Go,i=new Go,a=new Go,r=new Go,s=new Go){this.planes=[e,t,i,a,r,s]}set(e,t,i,a,r,s){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(a),o[4].copy(r),o[5].copy(s),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=br,i=!1){const a=this.planes,r=e.elements,s=r[0],o=r[1],c=r[2],h=r[3],f=r[4],d=r[5],m=r[6],g=r[7],x=r[8],T=r[9],y=r[10],v=r[11],S=r[12],E=r[13],b=r[14],D=r[15];if(a[0].setComponents(h-s,g-f,v-x,D-S).normalize(),a[1].setComponents(h+s,g+f,v+x,D+S).normalize(),a[2].setComponents(h+o,g+d,v+T,D+E).normalize(),a[3].setComponents(h-o,g-d,v-T,D-E).normalize(),i)a[4].setComponents(c,m,y,b).normalize(),a[5].setComponents(h-c,g-m,v-y,D-b).normalize();else if(a[4].setComponents(h-c,g-m,v-y,D-b).normalize(),t===br)a[5].setComponents(h+c,g+m,v+y,D+b).normalize();else if(t===Ed)a[5].setComponents(c,m,y,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Qc.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Qc.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Qc)}intersectsSprite(e){Qc.center.set(0,0,0);const t=zG.distanceTo(e.center);return Qc.radius=.7071067811865476+t,Qc.applyMatrix4(e.matrixWorld),this.intersectsSphere(Qc)}intersectsSphere(e){const t=this.planes,i=e.center,a=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(i)0?e.max.x:e.min.x,pv.y=a.normal.y>0?e.max.y:e.min.y,pv.z=a.normal.z>0?e.max.z:e.min.z,a.distanceToPoint(pv)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}const ks=new ke,Ws=new Yd;class k1{constructor(){this.coordinateSystem=br}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let i=0;i=r.length&&r.push({start:-1,count:-1,z:-1,index:-1});const o=r[this.index];s.push(o),this.index++,o.start=e,o.count=t,o.z=i,o.index=a}reset(){this.list.length=0,this.index=0}}const Xa=new ke,GG=new je(1,1,1),B4=new Yd,VG=new k1,mv=new ta,Jc=new na,Vp=new L,H4=new L,kG=new L,JT=new FG,ya=new oi,gv=[];function WG(n,e,t=0){const i=e.itemSize;if(n.isInterleavedBufferAttribute||n.array.constructor!==e.array.constructor){const a=n.count;for(let r=0;r65535?new Uint32Array(a):new Uint16Array(a);t.setIndex(new Ot(r,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const a=e.getAttribute(i),r=t.getAttribute(i);if(a.itemSize!==r.itemSize||a.normalized!==r.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){const t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){const t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new ta);const e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let i=0,a=t.length;i=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");const i={visible:!0,active:!0,geometryIndex:e};let a=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(QT),a=this._availableInstanceIds.shift(),this._instanceInfo[a]=i):(a=this._instanceInfo.length,this._instanceInfo.push(i));const r=this._matricesTexture;Xa.identity().toArray(r.image.data,a*16),r.needsUpdate=!0;const s=this._colorsTexture;return s&&(GG.toArray(s.image.data,a*4),s.needsUpdate=!0),this._visibilityChanged=!0,a}addGeometry(e,t=-1,i=-1){this._initializeGeometry(e),this._validateGeometry(e);const a={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},r=this._geometryInfo;a.vertexStart=this._nextVertexStart,a.reservedVertexCount=t===-1?e.getAttribute("position").count:t;const s=e.getIndex();if(s!==null&&(a.indexStart=this._nextIndexStart,a.reservedIndexCount=i===-1?s.count:i),a.indexStart!==-1&&a.indexStart+a.reservedIndexCount>this._maxIndexCount||a.vertexStart+a.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let c;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(QT),c=this._availableGeometryIds.shift(),r[c]=a):(c=this._geometryCount,this._geometryCount++,r.push(a)),this.setGeometryAt(c,e),this._nextIndexStart=a.indexStart+a.reservedIndexCount,this._nextVertexStart=a.vertexStart+a.reservedVertexCount,c}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,a=i.getIndex()!==null,r=i.getIndex(),s=t.getIndex(),o=this._geometryInfo[e];if(a&&s.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");const c=o.vertexStart,h=o.reservedVertexCount;o.vertexCount=t.getAttribute("position").count;for(const f in i.attributes){const d=t.getAttribute(f),m=i.getAttribute(f);WG(d,m,c);const g=d.itemSize;for(let x=d.count,T=h;x=t.length||t[e].active===!1)return this;const i=this._instanceInfo;for(let a=0,r=i.length;ao).sort((s,o)=>i[s].vertexStart-i[o].vertexStart),r=this.geometry;for(let s=0,o=i.length;s=this._geometryCount)return null;const i=this.geometry,a=this._geometryInfo[e];if(a.boundingBox===null){const r=new ta,s=i.index,o=i.attributes.position;for(let c=a.start,h=a.start+a.count;c=this._geometryCount)return null;const i=this.geometry,a=this._geometryInfo[e];if(a.boundingSphere===null){const r=new na;this.getBoundingBoxAt(e,mv),mv.getCenter(r.center);const s=i.index,o=i.attributes.position;let c=0;for(let h=a.start,f=a.start+a.count;ho.active);if(Math.max(...i.map(o=>o.vertexStart+o.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...i.map(c=>c.indexStart+c.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);const r=this.geometry;r.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Ct,this._initializeGeometry(r));const s=this.geometry;r.index&&$c(r.index.array,s.index.array);for(const o in r.attributes)$c(r.attributes[o].array,s.attributes[o].array)}raycast(e,t){const i=this._instanceInfo,a=this._geometryInfo,r=this.matrixWorld,s=this.geometry;ya.material=this.material,ya.geometry.index=s.index,ya.geometry.attributes=s.attributes,ya.geometry.boundingBox===null&&(ya.geometry.boundingBox=new ta),ya.geometry.boundingSphere===null&&(ya.geometry.boundingSphere=new na);for(let o=0,c=i.length;o({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,i,a,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const s=a.getIndex(),o=s===null?1:s.array.BYTES_PER_ELEMENT,c=this._instanceInfo,h=this._multiDrawStarts,f=this._multiDrawCounts,d=this._geometryInfo,m=this.perObjectFrustumCulled,g=this._indirectTexture,x=g.image.data,T=i.isArrayCamera?VG:B4;m&&!i.isArrayCamera&&(Xa.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),B4.setFromProjectionMatrix(Xa,i.coordinateSystem,i.reversedDepth));let y=0;if(this.sortObjects){Xa.copy(this.matrixWorld).invert(),Vp.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Xa),H4.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Xa);for(let E=0,b=c.length;E0){const a=t[i[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,s=a.length;ri)return;$T.applyMatrix4(n.matrixWorld);const h=e.ray.origin.distanceTo($T);if(!(he.far))return{distance:h,point:G4.clone().applyMatrix4(n.matrixWorld),index:s,face:null,faceIndex:null,barycoord:null,object:n}}const V4=new L,k4=new L;class ir extends so{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let a=0,r=t.count;a0){const a=t[i[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,s=a.length;ra.far)return;r.push({distance:h,distanceToRay:Math.sqrt(o),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:s})}}class jU extends Nn{constructor(e,t,i,a,r=Ht,s=Ht,o,c,h){super(e,t,i,a,r,s,o,c,h),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;const f=this;function d(){f.needsUpdate=!0,f._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d)}"requestVideoFrameCallback"in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(d))}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}}class XG extends jU{constructor(e,t,i,a,r,s,o,c){super({},e,t,i,a,r,s,o,c),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}}class YG extends Nn{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=Fn,this.minFilter=Fn,this.generateMipmaps=!1,this.needsUpdate=!0}}class X1 extends Nn{constructor(e,t,i,a,r,s,o,c,h,f,d,m){super(null,s,o,c,h,f,a,r,d,m),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class qG extends X1{constructor(e,t,i,a,r,s){super(e,t,i,r,s),this.isCompressedArrayTexture=!0,this.image.depth=a,this.wrapR=Pi,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class jG extends X1{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,rl),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class ZG extends Nn{constructor(e,t,i,a,r,s,o,c,h){super(e,t,i,a,r,s,o,c,h),this.isCanvasTexture=!0,this.needsUpdate=!0}}class z0 extends Nn{constructor(e,t,i=Ds,a,r,s,o=Fn,c=Fn,h,f=yd,d=1){if(f!==yd&&f!==ju)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const m={width:e,height:t,depth:d};super(m,a,r,s,o,c,f,i,h),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Jl(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class Cb extends Nn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Y1 extends Ct{constructor(e=1,t=1,i=4,a=8,r=1){super(),this.type="CapsuleGeometry",this.parameters={radius:e,height:t,capSegments:i,radialSegments:a,heightSegments:r},t=Math.max(0,t),i=Math.max(1,Math.floor(i)),a=Math.max(3,Math.floor(a)),r=Math.max(1,Math.floor(r));const s=[],o=[],c=[],h=[],f=t/2,d=Math.PI/2*e,m=t,g=2*d+m,x=i*2+r,T=a+1,y=new L,v=new L;for(let S=0;S<=x;S++){let E=0,b=0,D=0,C=0;if(S<=i){const O=S/i,w=O*Math.PI/2;b=-f-e*Math.cos(w),D=e*Math.sin(w),C=-e*Math.cos(w),E=O*d}else if(S<=i+r){const O=(S-i)/r;b=-f+O*t,D=e,C=0,E=d+O*m}else{const O=(S-i-r)/i,w=O*Math.PI/2;b=f+e*Math.sin(w),D=e*Math.cos(w),C=e*Math.sin(w),E=d+m+O*d}const I=Math.max(0,Math.min(1,E/g));let P=0;S===0?P=.5/a:S===x&&(P=-.5/a);for(let O=0;O<=a;O++){const w=O/a,B=w*Math.PI*2,j=Math.sin(B),ee=Math.cos(B);v.x=-D*ee,v.y=b,v.z=D*j,o.push(v.x,v.y,v.z),y.set(-D*ee,C,D*j),y.normalize(),c.push(y.x,y.y,y.z),h.push(w+P,I)}if(S>0){const O=(S-1)*T;for(let w=0;w0&&E(!0),t>0&&E(!1)),this.setIndex(f),this.setAttribute("position",new xt(d,3)),this.setAttribute("normal",new xt(m,3)),this.setAttribute("uv",new xt(g,2));function S(){const b=new L,D=new L;let C=0;const I=(t-e)/i;for(let P=0;P<=r;P++){const O=[],w=P/r,B=w*(t-e)+e;for(let j=0;j<=a;j++){const ee=j/a,se=ee*c+o,re=Math.sin(se),W=Math.cos(se);D.x=B*re,D.y=-w*i+y,D.z=B*W,d.push(D.x,D.y,D.z),b.set(re,I,W).normalize(),m.push(b.x,b.y,b.z),g.push(ee,1-w),O.push(x++)}T.push(O)}for(let P=0;P0||O!==0)&&(f.push(w,B,ee),C+=3),(t>0||O!==r-1)&&(f.push(B,j,ee),C+=3)}h.addGroup(v,C,0),v+=C}function E(b){const D=x,C=new de,I=new L;let P=0;const O=b===!0?e:t,w=b===!0?1:-1;for(let j=1;j<=a;j++)d.push(0,y*w,0),m.push(0,w,0),g.push(.5,.5),x++;const B=x;for(let j=0;j<=a;j++){const se=j/a*c+o,re=Math.cos(se),W=Math.sin(se);I.x=O*W,I.y=y*w,I.z=O*re,d.push(I.x,I.y,I.z),m.push(0,w,0),C.x=re*.5+.5,C.y=W*.5*w+.5,g.push(C.x,C.y),x++}for(let j=0;j.9&&I<.1&&(E<.2&&(s[S+0]+=1),b<.2&&(s[S+2]+=1),D<.2&&(s[S+4]+=1))}}function m(S){r.push(S.x,S.y,S.z)}function g(S,E){const b=S*3;E.x=e[b+0],E.y=e[b+1],E.z=e[b+2]}function x(){const S=new L,E=new L,b=new L,D=new L,C=new de,I=new de,P=new de;for(let O=0,w=0;O0)c=a-1;else{c=a;break}if(a=c,i[a]===s)return a/(r-1);const f=i[a],m=i[a+1]-f,g=(s-f)/m;return(a+g)/(r-1)}getTangent(e,t){let a=e-1e-4,r=e+1e-4;a<0&&(a=0),r>1&&(r=1);const s=this.getPoint(a),o=this.getPoint(r),c=t||(s.isVector2?new de:new L);return c.copy(o).sub(s).normalize(),c}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new L,a=[],r=[],s=[],o=new L,c=new ke;for(let g=0;g<=e;g++){const x=g/e;a[g]=this.getTangentAt(x,new L)}r[0]=new L,s[0]=new L;let h=Number.MAX_VALUE;const f=Math.abs(a[0].x),d=Math.abs(a[0].y),m=Math.abs(a[0].z);f<=h&&(h=f,i.set(1,0,0)),d<=h&&(h=d,i.set(0,1,0)),m<=h&&i.set(0,0,1),o.crossVectors(a[0],i).normalize(),r[0].crossVectors(a[0],o),s[0].crossVectors(a[0],r[0]);for(let g=1;g<=e;g++){if(r[g]=r[g-1].clone(),s[g]=s[g-1].clone(),o.crossVectors(a[g-1],a[g]),o.length()>Number.EPSILON){o.normalize();const x=Math.acos(Lt(a[g-1].dot(a[g]),-1,1));r[g].applyMatrix4(c.makeRotationAxis(o,x))}s[g].crossVectors(a[g],r[g])}if(t===!0){let g=Math.acos(Lt(r[0].dot(r[e]),-1,1));g/=e,a[0].dot(o.crossVectors(r[0],r[e]))>0&&(g=-g);for(let x=1;x<=e;x++)r[x].applyMatrix4(c.makeRotationAxis(a[x],g*x)),s[x].crossVectors(a[x],r[x])}return{tangents:a,normals:r,binormals:s}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Z1 extends Ls{constructor(e=0,t=0,i=1,a=1,r=0,s=Math.PI*2,o=!1,c=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=a,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=o,this.aRotation=c}getPoint(e,t=new de){const i=t,a=Math.PI*2;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)a;)r-=a;r0?0:(Math.floor(Math.abs(o)/r)+1)*r:c===0&&o===r-1&&(o=r-2,c=1);let h,f;this.closed||o>0?h=a[(o-1)%r]:(Mv.subVectors(a[0],a[1]).add(a[0]),h=Mv);const d=a[o%r],m=a[(o+1)%r];if(this.closed||o+2a.length-2?a.length-1:s+1],d=a[s>a.length-3?a.length-1:s+2];return i.set(Y4(o,c.x,h.x,f.x,d.x),Y4(o,c.y,h.y,f.y,d.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t=i){const s=a[r]-i,o=this.curves[r],c=o.getLength(),h=c===0?0:1-s/c;return o.getPointAt(h,t)}r++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,a=this.curves.length;i1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t0){const d=h.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(h);const f=h.getPoint(1);return this.currentPoint.copy(f),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Pu extends Fx{constructor(e){super(e),this.uuid=Nr(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,a=this.holes.length;i80*t){o=n[0],c=n[1];let f=o,d=c;for(let m=t;mf&&(f=g),x>d&&(d=x)}h=Math.max(f-o,d-c),h=h!==0?32767/h:0}return d0(r,s,t,o,c,h,0),s}function t6(n,e,t,i,a){let r;if(a===xV(n,e,t,i)>0)for(let s=e;s=e;s-=i)r=q4(s/i|0,n[s],n[s+1],r);return r&&Cd(r,r.next)&&(m0(r),r=r.next),r}function Ku(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(Cd(t,t.next)||fi(t.prev,t,t.next)===0)){if(m0(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function d0(n,e,t,i,a,r,s){if(!n)return;!s&&r&&dV(n,i,a,r);let o=n;for(;n.prev!==n.next;){const c=n.prev,h=n.next;if(r?rV(n,i,a,r):aV(n)){e.push(c.i,n.i,h.i),m0(n),n=h.next,o=h.next;continue}if(n=h,n===o){s?s===1?(n=sV(Ku(n),e),d0(n,e,t,i,a,r,2)):s===2&&oV(n,e,t,i,a,r):d0(Ku(n),e,t,i,a,r,1);break}}}function aV(n){const e=n.prev,t=n,i=n.next;if(fi(e,t,i)>=0)return!1;const a=e.x,r=t.x,s=i.x,o=e.y,c=t.y,h=i.y,f=Math.min(a,r,s),d=Math.min(o,c,h),m=Math.max(a,r,s),g=Math.max(o,c,h);let x=i.next;for(;x!==e;){if(x.x>=f&&x.x<=m&&x.y>=d&&x.y<=g&&um(a,o,r,c,s,h,x.x,x.y)&&fi(x.prev,x,x.next)>=0)return!1;x=x.next}return!0}function rV(n,e,t,i){const a=n.prev,r=n,s=n.next;if(fi(a,r,s)>=0)return!1;const o=a.x,c=r.x,h=s.x,f=a.y,d=r.y,m=s.y,g=Math.min(o,c,h),x=Math.min(f,d,m),T=Math.max(o,c,h),y=Math.max(f,d,m),v=cE(g,x,e,t,i),S=cE(T,y,e,t,i);let E=n.prevZ,b=n.nextZ;for(;E&&E.z>=v&&b&&b.z<=S;){if(E.x>=g&&E.x<=T&&E.y>=x&&E.y<=y&&E!==a&&E!==s&&um(o,f,c,d,h,m,E.x,E.y)&&fi(E.prev,E,E.next)>=0||(E=E.prevZ,b.x>=g&&b.x<=T&&b.y>=x&&b.y<=y&&b!==a&&b!==s&&um(o,f,c,d,h,m,b.x,b.y)&&fi(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;E&&E.z>=v;){if(E.x>=g&&E.x<=T&&E.y>=x&&E.y<=y&&E!==a&&E!==s&&um(o,f,c,d,h,m,E.x,E.y)&&fi(E.prev,E,E.next)>=0)return!1;E=E.prevZ}for(;b&&b.z<=S;){if(b.x>=g&&b.x<=T&&b.y>=x&&b.y<=y&&b!==a&&b!==s&&um(o,f,c,d,h,m,b.x,b.y)&&fi(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function sV(n,e){let t=n;do{const i=t.prev,a=t.next.next;!Cd(i,a)&&i6(i,t,t.next,a)&&p0(i,a)&&p0(a,i)&&(e.push(i.i,t.i,a.i),m0(t),m0(t.next),t=n=a),t=t.next}while(t!==n);return Ku(t)}function oV(n,e,t,i,a,r){let s=n;do{let o=s.next.next;for(;o!==s.prev;){if(s.i!==o.i&&gV(s,o)){let c=a6(s,o);s=Ku(s,s.next),c=Ku(c,c.next),d0(s,e,t,i,a,r,0),d0(c,e,t,i,a,r,0);return}o=o.next}s=s.next}while(s!==n)}function lV(n,e,t,i){const a=[];for(let r=0,s=e.length;r=t.next.y&&t.next.y!==t.y){const d=t.x+(a-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>r&&(r=d,s=t.x=t.x&&t.x>=c&&i!==t.x&&n6(as.x||t.x===s.x&&fV(s,t)))&&(s=t,f=d)}t=t.next}while(t!==o);return s}function fV(n,e){return fi(n.prev,n,e.prev)<0&&fi(e.next,n,n.next)<0}function dV(n,e,t,i){let a=n;do a.z===0&&(a.z=cE(a.x,a.y,e,t,i)),a.prevZ=a.prev,a.nextZ=a.next,a=a.next;while(a!==n);a.prevZ.nextZ=null,a.prevZ=null,pV(a)}function pV(n){let e,t=1;do{let i=n,a;n=null;let r=null;for(e=0;i;){e++;let s=i,o=0;for(let h=0;h0||c>0&&s;)o!==0&&(c===0||!s||i.z<=s.z)?(a=i,i=i.nextZ,o--):(a=s,s=s.nextZ,c--),r?r.nextZ=a:n=a,a.prevZ=r,r=a;i=s}r.nextZ=null,t*=2}while(e>1);return n}function cE(n,e,t,i,a){return n=(n-t)*a|0,e=(e-i)*a|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function mV(n){let e=n,t=n;do(e.x=(n-s)*(r-o)&&(n-s)*(i-o)>=(t-s)*(e-o)&&(t-s)*(r-o)>=(a-s)*(i-o)}function um(n,e,t,i,a,r,s,o){return!(n===s&&e===o)&&n6(n,e,t,i,a,r,s,o)}function gV(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!vV(n,e)&&(p0(n,e)&&p0(e,n)&&_V(n,e)&&(fi(n.prev,n,e.prev)||fi(n,e.prev,e))||Cd(n,e)&&fi(n.prev,n,n.next)>0&&fi(e.prev,e,e.next)>0)}function fi(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function Cd(n,e){return n.x===e.x&&n.y===e.y}function i6(n,e,t,i){const a=Av(fi(n,e,t)),r=Av(fi(n,e,i)),s=Av(fi(t,i,n)),o=Av(fi(t,i,e));return!!(a!==r&&s!==o||a===0&&bv(n,t,e)||r===0&&bv(n,i,e)||s===0&&bv(t,n,i)||o===0&&bv(t,e,i))}function bv(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function Av(n){return n>0?1:n<0?-1:0}function vV(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&i6(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function p0(n,e){return fi(n.prev,n,n.next)<0?fi(n,e,n.next)>=0&&fi(n,n.prev,e)>=0:fi(n,e,n.prev)<0||fi(n,n.next,e)<0}function _V(n,e){let t=n,i=!1;const a=(n.x+e.x)/2,r=(n.y+e.y)/2;do t.y>r!=t.next.y>r&&t.next.y!==t.y&&a<(t.next.x-t.x)*(r-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function a6(n,e){const t=uE(n.i,n.x,n.y),i=uE(e.i,e.x,e.y),a=n.next,r=e.prev;return n.next=e,e.prev=n,t.next=a,a.prev=t,i.next=t,t.prev=i,r.next=i,i.prev=r,i}function q4(n,e,t,i){const a=uE(n,e,t);return i?(a.next=i.next,a.prev=i,i.next.prev=a,i.next=a):(a.prev=a,a.next=a),a}function m0(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function uE(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function xV(n,e,t,i){let a=0;for(let r=e,s=t-i;r2&&n[e-1].equals(n[0])&&n.pop()}function Z4(n,e){for(let t=0;tNumber.EPSILON){const Ee=Math.sqrt(U),Le=Math.sqrt(ct*ct+k*k),ye=G.x-Je/Ee,vt=G.y+$e/Ee,qe=be.x-k/Le,_t=be.y+ct/Le,pt=((qe-ye)*k-(_t-vt)*ct)/($e*k-Je*ct);De=ye+$e*pt-Te.x,Fe=vt+Je*pt-Te.y;const Ie=De*De+Fe*Fe;if(Ie<=2)return new de(De,Fe);Be=Math.sqrt(Ie/2)}else{let Ee=!1;$e>Number.EPSILON?ct>Number.EPSILON&&(Ee=!0):$e<-Number.EPSILON?ct<-Number.EPSILON&&(Ee=!0):Math.sign(Je)===Math.sign(k)&&(Ee=!0),Ee?(De=-Je,Fe=$e,Be=Math.sqrt(U)):(De=$e,Fe=Je,Be=Math.sqrt(U/2))}return new de(De/Be,Fe/Be)}const oe=[];for(let Te=0,G=re.length,be=G-1,De=Te+1;Te=0;Te--){const G=Te/y,be=g*Math.cos(G*Math.PI/2),De=x*Math.sin(G*Math.PI/2)+T;for(let Fe=0,Be=re.length;Fe=0;){const De=be;let Fe=be-1;Fe<0&&(Fe=Te.length-1);for(let Be=0,$e=f+y*2;Be<$e;Be++){const Je=te*Be,ct=te*(Be+1),k=G+De+Je,U=G+Fe+Je,ce=G+Fe+ct,Ee=G+De+ct;Mt(k,U,ce,Ee)}}}function ue(Te,G,be){c.push(Te),c.push(G),c.push(be)}function it(Te,G,be){ot(Te),ot(G),ot(be);const De=a.length/3,Fe=S.generateTopUV(i,a,De-3,De-2,De-1);Ke(Fe[0]),Ke(Fe[1]),Ke(Fe[2])}function Mt(Te,G,be,De){ot(Te),ot(G),ot(De),ot(G),ot(be),ot(De);const Fe=a.length/3,Be=S.generateSideWallUV(i,a,Fe-6,Fe-3,Fe-2,Fe-1);Ke(Be[0]),Ke(Be[1]),Ke(Be[3]),Ke(Be[1]),Ke(Be[2]),Ke(Be[3])}function ot(Te){a.push(c[Te*3+0]),a.push(c[Te*3+1]),a.push(c[Te*3+2])}function Ke(Te){r.push(Te.x),r.push(Te.y)}}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON(),t=this.parameters.shapes,i=this.parameters.options;return TV(t,i,e)}static fromJSON(e,t){const i=[];for(let r=0,s=e.shapes.length;r0)&&g.push(E,b,C),(v!==i-1||c0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class o6 extends qn{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new je(16777215),this.specular=new je(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new je(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ll,this.normalScale=new de(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ei,this.combine=O0,this.reflectivity=1,this.refractionRatio=.98,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.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,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.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.flatShading=e.flatShading,this.fog=e.fog,this}}class l6 extends qn{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new je(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new je(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ll,this.normalScale=new de(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,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.gradientMap=e.gradientMap,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.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class Pb extends qn{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ll,this.normalScale=new de(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),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.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class c6 extends qn{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new je(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new je(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ll,this.normalScale=new de(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ei,this.combine=O0,this.reflectivity=1,this.refractionRatio=.98,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.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.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.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.flatShading=e.flatShading,this.fog=e.fog,this}}class zb extends qn{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Mc,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 Bb extends qn{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 u6 extends qn{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new je(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ll,this.normalScale=new de(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,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.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}}class h6 extends Bi{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function bu(n,e){return!n||n.constructor===e?n:typeof e.BYTES_PER_ELEMENT=="number"?new e(n):Array.prototype.slice.call(n)}function f6(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function d6(n){function e(a,r){return n[a]-n[r]}const t=n.length,i=new Array(t);for(let a=0;a!==t;++a)i[a]=a;return i.sort(e),i}function hE(n,e,t){const i=n.length,a=new n.constructor(i);for(let r=0,s=0;s!==i;++r){const o=t[r]*e;for(let c=0;c!==e;++c)a[s++]=n[o+c]}return a}function Hb(n,e,t,i){let a=1,r=n[0];for(;r!==void 0&&r[i]===void 0;)r=n[a++];if(r===void 0)return;let s=r[i];if(s!==void 0)if(Array.isArray(s))do s=r[i],s!==void 0&&(e.push(r.time),t.push(...s)),r=n[a++];while(r!==void 0);else if(s.toArray!==void 0)do s=r[i],s!==void 0&&(e.push(r.time),s.toArray(t,t.length)),r=n[a++];while(r!==void 0);else do s=r[i],s!==void 0&&(e.push(r.time),t.push(s)),r=n[a++];while(r!==void 0)}function MV(n,e,t,i,a=30){const r=n.clone();r.name=e;const s=[];for(let c=0;c=i)){d.push(h.times[g]);for(let T=0;Tr.tracks[c].times[0]&&(o=r.tracks[c].times[0]);for(let c=0;c=o.times[x]){const v=x*d+f,S=v+d-f;T=o.values.slice(v,S)}else{const v=o.createInterpolant(),S=f,E=d-f;v.evaluate(r),T=v.resultBuffer.slice(S,E)}c==="quaternion"&&new St().fromArray(T).normalize().conjugate().toArray(T);const y=h.times.length;for(let v=0;v=r)){const o=t[1];e=r)break t}s=i,i=0;break n}break e}for(;i>>1;et;)--s;if(++s,r!==0||s!==a){r>=s&&(s=Math.max(s,1),r=s-1);const o=this.getValueSize();this.times=i.slice(r,s),this.values=this.values.slice(r*o,s*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(Bt("KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,a=this.values,r=i.length;r===0&&(Bt("KeyframeTrack: Track is empty.",this),e=!1);let s=null;for(let o=0;o!==r;o++){const c=i[o];if(typeof c=="number"&&isNaN(c)){Bt("KeyframeTrack: Time is not a valid number.",this,o,c),e=!1;break}if(s!==null&&s>c){Bt("KeyframeTrack: Out of order keys.",this,o,c,s),e=!1;break}s=c}if(a!==void 0&&f6(a))for(let o=0,c=a.length;o!==c;++o){const h=a[o];if(isNaN(h)){Bt("KeyframeTrack: Value is not a valid number.",this,o,h),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),a=this.getInterpolation()===m_,r=e.length-1;let s=1;for(let o=1;o0){e[s]=e[r];for(let o=r*i,c=s*i,h=0;h!==i;++h)t[c+h]=t[o+h];++s}return s!==e.length?(this.times=e.slice(0,s),this.values=t.slice(0,s*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,a=new i(this.name,e,t);return a.createInterpolant=this.createInterpolant,a}}cs.prototype.ValueTypeName="";cs.prototype.TimeBufferType=Float32Array;cs.prototype.ValueBufferType=Float32Array;cs.prototype.DefaultInterpolation=Td;class fh extends cs{constructor(e,t,i){super(e,t,i)}}fh.prototype.ValueTypeName="bool";fh.prototype.ValueBufferType=Array;fh.prototype.DefaultInterpolation=Sd;fh.prototype.InterpolantFactoryMethodLinear=void 0;fh.prototype.InterpolantFactoryMethodSmooth=void 0;class Gb extends cs{constructor(e,t,i,a){super(e,t,i,a)}}Gb.prototype.ValueTypeName="color";class xc extends cs{constructor(e,t,i,a){super(e,t,i,a)}}xc.prototype.ValueTypeName="number";class g6 extends qd{constructor(e,t,i,a){super(e,t,i,a)}interpolate_(e,t,i,a){const r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,c=(i-t)/(a-t);let h=e*o;for(let f=h+o;h!==f;h+=4)St.slerpFlat(r,0,s,h-o,s,h,c);return r}}class yc extends cs{constructor(e,t,i,a){super(e,t,i,a)}InterpolantFactoryMethodLinear(e){return new g6(this.times,this.values,this.getValueSize(),e)}}yc.prototype.ValueTypeName="quaternion";yc.prototype.InterpolantFactoryMethodSmooth=void 0;class dh extends cs{constructor(e,t,i){super(e,t,i)}}dh.prototype.ValueTypeName="string";dh.prototype.ValueBufferType=Array;dh.prototype.DefaultInterpolation=Sd;dh.prototype.InterpolantFactoryMethodLinear=void 0;dh.prototype.InterpolantFactoryMethodSmooth=void 0;class Qu extends cs{constructor(e,t,i,a){super(e,t,i,a)}}Qu.prototype.ValueTypeName="vector";class Ju{constructor(e="",t=-1,i=[],a=z1){this.name=e,this.tracks=i,this.duration=t,this.blendMode=a,this.uuid=Nr(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,a=1/(e.fps||1);for(let s=0,o=i.length;s!==o;++s)t.push(RV(i[s]).scale(a));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r.userData=JSON.parse(e.userData||"{}"),r}static toJSON(e){const t=[],i=e.tracks,a={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let r=0,s=i.length;r!==s;++r)t.push(cs.toJSON(i[r]));return a}static CreateFromMorphTargetSequence(e,t,i,a){const r=t.length,s=[];for(let o=0;o1){const d=f[1];let m=a[d];m||(a[d]=m=[]),m.push(h)}}const s=[];for(const o in a)s.push(this.CreateFromMorphTargetSequence(o,a[o],t,i));return s}static parseAnimation(e,t){if(ut("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return Bt("AnimationClip: No animation in JSONLoader data."),null;const i=function(d,m,g,x,T){if(g.length!==0){const y=[],v=[];Hb(g,y,v,x),y.length!==0&&T.push(new d(m,y,v))}},a=[],r=e.name||"default",s=e.fps||30,o=e.blendMode;let c=e.length||-1;const h=e.hierarchy||[];for(let d=0;d{t&&t(r),this.manager.itemEnd(e)},0),r;if(Lo[e]!==void 0){Lo[e].push({onLoad:t,onProgress:i,onError:a});return}Lo[e]=[],Lo[e].push({onLoad:t,onProgress:i,onError:a});const s=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,c=this.responseType;fetch(s).then(h=>{if(h.status===200||h.status===0){if(h.status===0&&ut("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||h.body===void 0||h.body.getReader===void 0)return h;const f=Lo[e],d=h.body.getReader(),m=h.headers.get("X-File-Size")||h.headers.get("Content-Length"),g=m?parseInt(m):0,x=g!==0;let T=0;const y=new ReadableStream({start(v){S();function S(){d.read().then(({done:E,value:b})=>{if(E)v.close();else{T+=b.byteLength;const D=new ProgressEvent("progress",{lengthComputable:x,loaded:T,total:g});for(let C=0,I=f.length;C{v.error(E)})}}});return new Response(y)}else throw new CV(`fetch for "${h.url}" responded with ${h.status}: ${h.statusText}`,h)}).then(h=>{switch(c){case"arraybuffer":return h.arrayBuffer();case"blob":return h.blob();case"document":return h.text().then(f=>new DOMParser().parseFromString(f,o));case"json":return h.json();default:if(o==="")return h.text();{const d=/charset="?([^;"\s]*)"?/i.exec(o),m=d&&d[1]?d[1].toLowerCase():void 0,g=new TextDecoder(m);return h.arrayBuffer().then(x=>g.decode(x))}}}).then(h=>{no.add(`file:${e}`,h);const f=Lo[e];delete Lo[e];for(let d=0,m=f.length;d{const f=Lo[e];if(f===void 0)throw this.manager.itemError(e),h;delete Lo[e];for(let d=0,m=f.length;d{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}class NV extends Mi{constructor(e){super(e)}load(e,t,i,a){const r=this,s=new os(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(o){try{t(r.parse(JSON.parse(o)))}catch(c){a?a(c):Bt(c),r.manager.itemError(e)}},i,a)}parse(e){const t=[];for(let i=0;i0:a.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const r in e.uniforms){const s=e.uniforms[r];switch(a.uniforms[r]={},s.type){case"t":a.uniforms[r].value=i(s.value);break;case"c":a.uniforms[r].value=new je().setHex(s.value);break;case"v2":a.uniforms[r].value=new de().fromArray(s.value);break;case"v3":a.uniforms[r].value=new L().fromArray(s.value);break;case"v4":a.uniforms[r].value=new zt().fromArray(s.value);break;case"m3":a.uniforms[r].value=new Et().fromArray(s.value);break;case"m4":a.uniforms[r].value=new ke().fromArray(s.value);break;default:a.uniforms[r].value=s.value}}if(e.defines!==void 0&&(a.defines=e.defines),e.vertexShader!==void 0&&(a.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(a.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(a.glslVersion=e.glslVersion),e.extensions!==void 0)for(const r in e.extensions)a.extensions[r]=e.extensions[r];if(e.lights!==void 0&&(a.lights=e.lights),e.clipping!==void 0&&(a.clipping=e.clipping),e.size!==void 0&&(a.size=e.size),e.sizeAttenuation!==void 0&&(a.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(a.map=i(e.map)),e.matcap!==void 0&&(a.matcap=i(e.matcap)),e.alphaMap!==void 0&&(a.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(a.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(a.bumpScale=e.bumpScale),e.normalMap!==void 0&&(a.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(a.normalMapType=e.normalMapType),e.normalScale!==void 0){let r=e.normalScale;Array.isArray(r)===!1&&(r=[r,r]),a.normalScale=new de().fromArray(r)}return e.displacementMap!==void 0&&(a.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(a.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(a.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(a.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(a.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(a.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(a.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(a.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(a.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(a.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(a.envMap=i(e.envMap)),e.envMapRotation!==void 0&&a.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(a.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(a.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(a.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(a.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(a.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(a.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(a.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(a.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(a.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(a.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(a.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(a.clearcoatNormalScale=new de().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(a.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(a.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(a.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(a.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(a.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(a.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(a.sheenRoughnessMap=i(e.sheenRoughnessMap)),a}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return ry.createMaterialFromType(e)}static createMaterialFromType(e){const t={ShadowMaterial:s6,SpriteMaterial:bb,RawShaderMaterial:hh,ShaderMaterial:Vi,PointsMaterial:W1,MeshPhysicalMaterial:ls,MeshStandardMaterial:V0,MeshPhongMaterial:o6,MeshToonMaterial:l6,MeshNormalMaterial:Pb,MeshLambertMaterial:c6,MeshDepthMaterial:zb,MeshDistanceMaterial:Bb,MeshBasicMaterial:Ia,MeshMatcapMaterial:u6,LineDashedMaterial:h6,LineBasicMaterial:Bi,Material:qn};return new t[e]}}class uc{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class M6 extends Ct{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class b6 extends Mi{constructor(e){super(e)}load(e,t,i,a){const r=this,s=new os(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(e,function(o){try{t(r.parse(JSON.parse(o)))}catch(c){a?a(c):Bt(c),r.manager.itemError(e)}},i,a)}parse(e){const t={},i={};function a(g,x){if(t[x]!==void 0)return t[x];const y=g.interleavedBuffers[x],v=r(g,y.buffer),S=Wf(y.type,v),E=new P0(S,y.stride);return E.uuid=y.uuid,t[x]=E,E}function r(g,x){if(i[x]!==void 0)return i[x];const y=g.arrayBuffers[x],v=new Uint32Array(y).buffer;return i[x]=v,v}const s=e.isInstancedBufferGeometry?new M6:new Ct,o=e.data.index;if(o!==void 0){const g=Wf(o.type,o.array);s.setIndex(new Ot(g,1))}const c=e.data.attributes;for(const g in c){const x=c[g];let T;if(x.isInterleavedBufferAttribute){const y=a(e.data,x.data);T=new _c(y,x.itemSize,x.offset,x.normalized)}else{const y=Wf(x.type,x.array),v=x.isInstancedBufferAttribute?Zu:Ot;T=new v(y,x.itemSize,x.normalized)}x.name!==void 0&&(T.name=x.name),x.usage!==void 0&&T.setUsage(x.usage),s.setAttribute(g,T)}const h=e.data.morphAttributes;if(h)for(const g in h){const x=h[g],T=[];for(let y=0,v=x.length;y0){const c=new Vb(t);r=new Nd(c),r.setCrossOrigin(this.crossOrigin);for(let h=0,f=e.length;h0){a=new Nd(this.manager),a.setCrossOrigin(this.crossOrigin);for(let s=0,o=e.length;s{let y=null,v=null;return T.boundingBox!==void 0&&(y=new ta().fromJSON(T.boundingBox)),T.boundingSphere!==void 0&&(v=new na().fromJSON(T.boundingSphere)),{...T,boundingBox:y,boundingSphere:v}}),s._instanceInfo=e.instanceInfo,s._availableInstanceIds=e._availableInstanceIds,s._availableGeometryIds=e._availableGeometryIds,s._nextIndexStart=e.nextIndexStart,s._nextVertexStart=e.nextVertexStart,s._geometryCount=e.geometryCount,s._maxInstanceCount=e.maxInstanceCount,s._maxVertexCount=e.maxVertexCount,s._maxIndexCount=e.maxIndexCount,s._geometryInitialized=e.geometryInitialized,s._matricesTexture=h(e.matricesTexture.uuid),s._indirectTexture=h(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(s._colorsTexture=h(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(s.boundingSphere=new na().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(s.boundingBox=new ta().fromJSON(e.boundingBox));break;case"LOD":s=new YU;break;case"Line":s=new so(o(e.geometry),c(e.material));break;case"LineLoop":s=new wb(o(e.geometry),c(e.material));break;case"LineSegments":s=new ir(o(e.geometry),c(e.material));break;case"PointCloud":case"Points":s=new Rb(o(e.geometry),c(e.material));break;case"Sprite":s=new XU(c(e.material));break;case"Group":s=new Ua;break;case"Bone":s=new V1;break;default:s=new Wt}if(s.uuid=e.uuid,e.name!==void 0&&(s.name=e.name),e.matrix!==void 0?(s.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(s.matrixAutoUpdate=e.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(e.position!==void 0&&s.position.fromArray(e.position),e.rotation!==void 0&&s.rotation.fromArray(e.rotation),e.quaternion!==void 0&&s.quaternion.fromArray(e.quaternion),e.scale!==void 0&&s.scale.fromArray(e.scale)),e.up!==void 0&&s.up.fromArray(e.up),e.castShadow!==void 0&&(s.castShadow=e.castShadow),e.receiveShadow!==void 0&&(s.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(s.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(s.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(s.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(s.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&s.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(s.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(s.visible=e.visible),e.frustumCulled!==void 0&&(s.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(s.renderOrder=e.renderOrder),e.userData!==void 0&&(s.userData=e.userData),e.layers!==void 0&&(s.layers.mask=e.layers),e.children!==void 0){const m=e.children;for(let g=0;g"u"&&ut("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&ut("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,i,a){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,s=no.get(`image-bitmap:${e}`);if(s!==void 0){if(r.manager.itemStart(e),s.then){s.then(h=>{if(s2.has(s)===!0)a&&a(s2.get(s)),r.manager.itemError(e),r.manager.itemEnd(e);else return t&&t(h),r.manager.itemEnd(e),h});return}return setTimeout(function(){t&&t(s),r.manager.itemEnd(e)},0),s}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const c=fetch(e,o).then(function(h){return h.blob()}).then(function(h){return createImageBitmap(h,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(h){return no.add(`image-bitmap:${e}`,h),t&&t(h),r.manager.itemEnd(e),h}).catch(function(h){a&&a(h),s2.set(c,h),no.remove(`image-bitmap:${e}`),r.manager.itemError(e),r.manager.itemEnd(e)});no.add(`image-bitmap:${e}`,c),r.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let wv;class jb{static getContext(){return wv===void 0&&(wv=new(window.AudioContext||window.webkitAudioContext)),wv}static setContext(e){wv=e}}class BV extends Mi{constructor(e){super(e)}load(e,t,i,a){const r=this,s=new os(this.manager);s.setResponseType("arraybuffer"),s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(c){try{const h=c.slice(0);jb.getContext().decodeAudioData(h,function(d){t(d)}).catch(o)}catch(h){o(h)}},i,a);function o(c){a?a(c):Bt(c),r.manager.itemError(e)}}}const iN=new ke,aN=new ke,eu=new ke;class HV{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new hi,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new hi,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,eu.copy(e.projectionMatrix);const a=t.eyeSep/2,r=a*t.near/t.focus,s=t.near*Math.tan(Uu*t.fov*.5)/t.zoom;let o,c;aN.elements[12]=-a,iN.elements[12]=a,o=-s*t.aspect+r,c=s*t.aspect+r,eu.elements[0]=2*t.near/(c-o),eu.elements[8]=(c+o)/(c-o),this.cameraL.projectionMatrix.copy(eu),o=-s*t.aspect-r,c=s*t.aspect-r,eu.elements[0]=2*t.near/(c-o),eu.elements[8]=(c+o)/(c-o),this.cameraR.projectionMatrix.copy(eu)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(aN),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(iN)}}class w6 extends hi{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Zb{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}const tu=new L,o2=new St,FV=new L,nu=new L,iu=new L;class GV extends Wt{constructor(){super(),this.type="AudioListener",this.context=jb.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Zb}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(tu,o2,FV),nu.set(0,0,-1).applyQuaternion(o2),iu.set(0,1,0).applyQuaternion(o2),t.positionX){const i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(tu.x,i),t.positionY.linearRampToValueAtTime(tu.y,i),t.positionZ.linearRampToValueAtTime(tu.z,i),t.forwardX.linearRampToValueAtTime(nu.x,i),t.forwardY.linearRampToValueAtTime(nu.y,i),t.forwardZ.linearRampToValueAtTime(nu.z,i),t.upX.linearRampToValueAtTime(iu.x,i),t.upY.linearRampToValueAtTime(iu.y,i),t.upZ.linearRampToValueAtTime(iu.z,i)}else t.setPosition(tu.x,tu.y,tu.z),t.setOrientation(nu.x,nu.y,nu.z,iu.x,iu.y,iu.z)}}class R6 extends Wt{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){ut("Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){ut("Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){ut("Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){ut("Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(i,a,this._addIndex*t,1,t);for(let c=t,h=t+t;c!==h;++c)if(i[c]!==i[c+t]){o.setValue(i,a);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,a=i*this._origIndex;e.getValue(t,a);for(let r=i,s=a;r!==s;++r)t[r]=t[a+r%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let s=0;s!==r;++s)e[t+s]=e[i+s]}_slerp(e,t,i,a){St.slerpFlat(e,t,e,t,e,i,a)}_slerpAdditive(e,t,i,a,r){const s=this._workIndex*r;St.multiplyQuaternionsFlat(e,s,e,t,e,i),St.slerpFlat(e,t,e,t,e,s,a)}_lerp(e,t,i,a,r){const s=1-a;for(let o=0;o!==r;++o){const c=t+o;e[c]=e[c]*s+e[i+o]*a}}_lerpAdditive(e,t,i,a,r){for(let s=0;s!==r;++s){const o=t+s;e[o]=e[o]+e[i+s]*a}}}const Kb="\\[\\]\\.:\\/",XV=new RegExp("["+Kb+"]","g"),Qb="[^"+Kb+"]",YV="[^"+Kb.replace("\\.","")+"]",qV=/((?:WC+[\/:])*)/.source.replace("WC",Qb),jV=/(WCOD+)?/.source.replace("WCOD",YV),ZV=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Qb),KV=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Qb),QV=new RegExp("^"+qV+jV+ZV+KV+"$"),JV=["material","materials","bones","map"];class $V{constructor(e,t,i){const a=i||fn.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,a)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,a=this._bindings[i];a!==void 0&&a.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let a=this._targetGroup.nCachedObjects_,r=i.length;a!==r;++a)i[a].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class fn{constructor(e,t,i){this.path=t,this.parsedPath=i||fn.parseTrackName(t),this.node=fn.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new fn.Composite(e,t,i):new fn(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(XV,"")}static parseTrackName(e){const t=QV.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},a=i.nodeName&&i.nodeName.lastIndexOf(".");if(a!==void 0&&a!==-1){const r=i.nodeName.substring(a+1);JV.indexOf(r)!==-1&&(i.nodeName=i.nodeName.substring(0,a),i.objectName=r)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(r){for(let s=0;s=r){const d=r++,m=e[d];t[m.uuid]=f,e[f]=m,t[h]=d,e[d]=c;for(let g=0,x=a;g!==x;++g){const T=i[g],y=T[d],v=T[f];T[f]=y,T[d]=v}}}this.nCachedObjects_=r}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,a=i.length;let r=this.nCachedObjects_,s=e.length;for(let o=0,c=arguments.length;o!==c;++o){const h=arguments[o],f=h.uuid,d=t[f];if(d!==void 0)if(delete t[f],d0&&(t[g.uuid]=d),e[d]=g,e.pop();for(let x=0,T=a;x!==T;++x){const y=i[x];y[d]=y[m],y.pop()}}}this.nCachedObjects_=r}subscribe_(e,t){const i=this._bindingsIndicesByPath;let a=i[e];const r=this._bindings;if(a!==void 0)return r[a];const s=this._paths,o=this._parsedPaths,c=this._objects,h=c.length,f=this.nCachedObjects_,d=new Array(h);a=r.length,i[e]=a,s.push(e),o.push(t),r.push(d);for(let m=f,g=c.length;m!==g;++m){const x=c[m];d[m]=new fn(x,e,t)}return d}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const a=this._paths,r=this._parsedPaths,s=this._bindings,o=s.length-1,c=s[o],h=e[o];t[h]=i,s[i]=c,s.pop(),r[i]=r[o],r.pop(),a[i]=a[o],a.pop()}}}class N6{constructor(e,t,i=null,a=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=a;const r=t.tracks,s=r.length,o=new Array(s),c={endingStart:Eu,endingEnd:Eu};for(let h=0;h!==s;++h){const f=r[h].createInterpolant(null);o[h]=f,f.settings=c}this._interpolantSettings=c,this._interpolants=o,this._propertyBindings=new Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=TU,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i=!1){if(e.fadeOut(t),this.fadeIn(t),i===!0){const a=this._clip.duration,r=e._clip.duration,s=r/a,o=a/r;e.warp(1,s,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i=!1){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const a=this._mixer,r=a.time,s=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=a._lendControlInterpolant(),this._timeScaleInterpolant=o);const c=o.parameterPositions,h=o.sampleValues;return c[0]=r,c[1]=r+i,h[0]=e/s,h[1]=t/s,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,a){if(!this.enabled){this._updateWeight(e);return}const r=this._startTime;if(r!==null){const c=(e-r)*i;c<0||i===0?t=0:(this._startTime=null,t=i*c)}t*=this._updateTimeScale(e);const s=this._updateTime(t),o=this._updateWeight(e);if(o>0){const c=this._interpolants,h=this._propertyBindings;switch(this.blendMode){case vb:for(let f=0,d=c.length;f!==d;++f)c[f].evaluate(s),h[f].accumulateAdditive(o);break;case z1:default:for(let f=0,d=c.length;f!==d;++f)c[f].evaluate(s),h[f].accumulate(a,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const a=i.evaluate(e)[0];t*=a,e>i.parameterPositions[1]&&(this.stopFading(),a===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const a=i.evaluate(e)[0];t*=a,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let a=this.time+e,r=this._loopCount;const s=i===EU;if(e===0)return r===-1?a:s&&(r&1)===1?t-a:a;if(i===gb){r===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(a>=t)a=t;else if(a<0)a=0;else{this.time=a;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=a,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(r===-1&&(e>=0?(r=0,this._setEndings(!0,this.repetitions===0,s)):this._setEndings(this.repetitions===0,!0,s)),a>=t||a<0){const o=Math.floor(a/t);a-=t*o,r+=Math.abs(o);const c=this.repetitions-r;if(c<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,a=e>0?t:0,this.time=a,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(c===1){const h=e<0;this._setEndings(h,!h,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=a,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=a;if(s&&(r&1)===1)return t-a}return a}_setEndings(e,t,i){const a=this._interpolantSettings;i?(a.endingStart=Mu,a.endingEnd=Mu):(e?a.endingStart=this.zeroSlopeAtStart?Mu:Eu:a.endingStart=l0,t?a.endingEnd=this.zeroSlopeAtEnd?Mu:Eu:a.endingEnd=l0)}_scheduleFading(e,t,i){const a=this._mixer,r=a.time;let s=this._weightInterpolant;s===null&&(s=a._lendControlInterpolant(),this._weightInterpolant=s);const o=s.parameterPositions,c=s.sampleValues;return o[0]=r,c[0]=t,o[1]=r+e,c[1]=i,this}}const tk=new Float32Array(1);class D6 extends nr{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const i=e._localRoot||this._root,a=e._clip.tracks,r=a.length,s=e._propertyBindings,o=e._interpolants,c=i.uuid,h=this._bindingsByRootAndName;let f=h[c];f===void 0&&(f={},h[c]=f);for(let d=0;d!==r;++d){const m=a[d],g=m.name;let x=f[g];if(x!==void 0)++x.referenceCount,s[d]=x;else{if(x=s[d],x!==void 0){x._cacheIndex===null&&(++x.referenceCount,this._addInactiveBinding(x,c,g));continue}const T=t&&t._propertyBindings[d].binding.parsedPath;x=new C6(fn.create(i,g,T),m.ValueTypeName,m.getValueSize()),++x.referenceCount,this._addInactiveBinding(x,c,g),s[d]=x}o[d].resultBuffer=x.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,a=e._clip.uuid,r=this._actionsByClip[a];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,a,i)}const t=e._propertyBindings;for(let i=0,a=t.length;i!==a;++i){const r=t[i];r.useCount++===0&&(this._lendBinding(r),r.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,a=t.length;i!==a;++i){const r=t[i];--r.useCount===0&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,a=this.time+=e,r=Math.sign(e),s=this._accuIndex^=1;for(let h=0;h!==i;++h)t[h]._update(a,e,r,s);const o=this._bindings,c=this._nActiveBindings;for(let h=0;h!==c;++h)o[h].apply(s);return this}setTime(e){this.time=0;for(let t=0;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}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}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}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}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,lN).distanceTo(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}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const cN=new L,Rv=new L,uf=new L,hf=new L,l2=new L,uk=new L,hk=new L;class fk{constructor(e=new L,t=new L){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){cN.subVectors(e,this.start),Rv.subVectors(this.end,this.start);const i=Rv.dot(Rv);let r=Rv.dot(cN)/i;return t&&(r=Lt(r,0,1)),r}closestPointToPoint(e,t,i){const a=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(a).add(this.start)}distanceSqToLine3(e,t=uk,i=hk){const a=10000000000000001e-32;let r,s;const o=this.start,c=e.start,h=this.end,f=e.end;uf.subVectors(h,o),hf.subVectors(f,c),l2.subVectors(o,c);const d=uf.dot(uf),m=hf.dot(hf),g=hf.dot(l2);if(d<=a&&m<=a)return t.copy(o),i.copy(c),t.sub(i),t.dot(t);if(d<=a)r=0,s=g/m,s=Lt(s,0,1);else{const x=uf.dot(l2);if(m<=a)s=0,r=Lt(-x/d,0,1);else{const T=uf.dot(hf),y=d*m-T*T;y!==0?r=Lt((T*g-x*m)/y,0,1):r=0,s=(T*r+g)/m,s<0?(s=0,r=Lt(-x/d,0,1)):s>1&&(s=1,r=Lt((T-x)/d,0,1))}}return t.copy(o).add(uf.multiplyScalar(r)),i.copy(c).add(hf.multiplyScalar(s)),t.sub(i),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const uN=new L;class dk extends Wt{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new Ct,a=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let s=0,o=1,c=32;s1)for(let d=0;d.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{mN.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(mN,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class I6 extends ir{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],a=new Ct;a.setAttribute("position",new xt(t,3)),a.setAttribute("color",new xt(i,3));const r=new Bi({vertexColors:!0,toneMapped:!1});super(a,r),this.type="AxesHelper"}setColors(e,t,i){const a=new je,r=this.geometry.attributes.color.array;return a.set(e),a.toArray(r,0),a.toArray(r,3),a.set(t),a.toArray(r,6),a.toArray(r,9),a.set(i),a.toArray(r,12),a.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class Ak{constructor(){this.type="ShapePath",this.color=new je,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Fx,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,a){return this.currentPath.quadraticCurveTo(e,t,i,a),this}bezierCurveTo(e,t,i,a,r,s){return this.currentPath.bezierCurveTo(e,t,i,a,r,s),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(v){const S=[];for(let E=0,b=v.length;ENumber.EPSILON){if(w<0&&(I=S[C],O=-O,P=S[D],w=-w),v.yP.y)continue;if(v.y===I.y){if(v.x===I.x)return!0}else{const B=w*(v.x-I.x)-O*(v.y-I.y);if(B===0)return!0;if(B<0)continue;b=!b}}else{if(v.y!==I.y)continue;if(P.x<=v.x&&v.x<=I.x||I.x<=v.x&&v.x<=P.x)return!0}}return b}const a=ws.isClockWise,r=this.subPaths;if(r.length===0)return[];let s,o,c;const h=[];if(r.length===1)return o=r[0],c=new Pu,c.curves=o.curves,h.push(c),h;let f=!a(r[0].getPoints());f=e?!f:f;const d=[],m=[];let g=[],x=0,T;m[x]=void 0,g[x]=[];for(let v=0,S=r.length;v1){let v=!1,S=0;for(let E=0,b=m.length;E0&&v===!1&&(g=d)}let y;for(let v=0,S=m.length;ve?(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2):(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0),n}function Ck(n,e){const t=n.image&&n.image.width?n.image.width/n.image.height:1;return t>e?(n.repeat.x=e/t,n.repeat.y=1,n.offset.x=(1-n.repeat.x)/2,n.offset.y=0):(n.repeat.x=1,n.repeat.y=t/e,n.offset.x=0,n.offset.y=(1-n.repeat.y)/2),n}function Nk(n){return n.repeat.x=1,n.repeat.y=1,n.offset.x=0,n.offset.y=0,n}function mE(n,e,t,i){const a=Dk(i);switch(t){case pb:return n*e;case As:return n*e/a.components*a.byteLength;case I0:return n*e/a.components*a.byteLength;case ko:return n*e*2/a.components*a.byteLength;case U1:return n*e*2/a.components*a.byteLength;case mb:return n*e*3/a.components*a.byteLength;case $n:return n*e*4/a.components*a.byteLength;case P1:return n*e*4/a.components*a.byteLength;case Om:case Lm:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case Im:case Um:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case cx:case hx:return Math.max(n,16)*Math.max(e,8)/4;case lx:case ux:return Math.max(n,8)*Math.max(e,8)/2;case fx:case dx:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case px:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case mx:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case gx:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case vx:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case _x:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case xx:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case yx:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case Sx:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case Tx:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case Ex:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case Mx:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case bx:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case Ax:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case wx:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case Rx:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case Cx:case Nx:case Dx:return Math.ceil(n/4)*Math.ceil(e/4)*16;case Ox:case Lx:return Math.ceil(n/4)*Math.ceil(e/4)*8;case Ix:case Ux:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function Dk(n){switch(n){case zi:case D1:return{byteLength:1,components:1};case Yu:case O1:case Xn:return{byteLength:2,components:1};case L1:case I1:return{byteLength:2,components:4};case Ds:case L0:case si:return{byteLength:4,components:1};case fb:case db:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${n}.`)}class Ok{static contain(e,t){return Rk(e,t)}static cover(e,t){return Ck(e,t)}static fill(e){return Nk(e)}static getByteLength(e,t,i,a){return mE(e,t,i,a)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Cs}}));typeof window<"u"&&(window.__THREE__?ut("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Cs);/** - * @license - * Copyright 2010-2025 Three.js Authors - * SPDX-License-Identifier: MIT - */function U6(){let n=null,e=!1,t=null,i=null;function a(r,s){t(r,s),i=n.requestAnimationFrame(a)}return{start:function(){e!==!0&&t!==null&&(i=n.requestAnimationFrame(a),e=!0)},stop:function(){n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(r){t=r},setContext:function(r){n=r}}}function Lk(n){const e=new WeakMap;function t(o,c){const h=o.array,f=o.usage,d=h.byteLength,m=n.createBuffer();n.bindBuffer(c,m),n.bufferData(c,h,f),o.onUploadCallback();let g;if(h instanceof Float32Array)g=n.FLOAT;else if(typeof Float16Array<"u"&&h instanceof Float16Array)g=n.HALF_FLOAT;else if(h instanceof Uint16Array)o.isFloat16BufferAttribute?g=n.HALF_FLOAT:g=n.UNSIGNED_SHORT;else if(h instanceof Int16Array)g=n.SHORT;else if(h instanceof Uint32Array)g=n.UNSIGNED_INT;else if(h instanceof Int32Array)g=n.INT;else if(h instanceof Int8Array)g=n.BYTE;else if(h instanceof Uint8Array)g=n.UNSIGNED_BYTE;else if(h instanceof Uint8ClampedArray)g=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+h);return{buffer:m,type:g,bytesPerElement:h.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,c,h){const f=c.array,d=c.updateRanges;if(n.bindBuffer(h,o),d.length===0)n.bufferSubData(h,0,f);else{d.sort((g,x)=>g.start-x.start);let m=0;for(let g=1;g 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`,Kk=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; - uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,Qk=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; -#endif`,Jk=`#if NUM_CLIPPING_PLANES > 0 - vClipPosition = - mvPosition.xyz; -#endif`,$k=`#if defined( USE_COLOR_ALPHA ) - diffuseColor *= vColor; -#elif defined( USE_COLOR ) - diffuseColor.rgb *= vColor; -#endif`,eW=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) - varying vec3 vColor; -#endif`,tW=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - varying vec3 vColor; -#endif`,nW=`#if defined( USE_COLOR_ALPHA ) - vColor = vec4( 1.0 ); -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - vColor = vec3( 1.0 ); -#endif -#ifdef USE_COLOR - vColor *= color; -#endif -#ifdef USE_INSTANCING_COLOR - vColor.xyz *= instanceColor.xyz; -#endif -#ifdef USE_BATCHING_COLOR - vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); - vColor.xyz *= batchingColor.xyz; -#endif`,iW=`#define PI 3.141592653589793 -#define PI2 6.283185307179586 -#define PI_HALF 1.5707963267948966 -#define RECIPROCAL_PI 0.3183098861837907 -#define RECIPROCAL_PI2 0.15915494309189535 -#define EPSILON 1e-6 -#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -#define whiteComplement( a ) ( 1.0 - saturate( a ) ) -float pow2( const in float x ) { return x*x; } -vec3 pow2( const in vec3 x ) { return x*x; } -float pow3( const in float x ) { return x*x*x; } -float pow4( const in float x ) { float x2 = x*x; return x2*x2; } -float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } -float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } -highp float rand( const in vec2 uv ) { - const highp float a = 12.9898, b = 78.233, c = 43758.5453; - highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); - return fract( sin( sn ) * c ); -} -#ifdef HIGH_PRECISION - float precisionSafeLength( vec3 v ) { return length( v ); } -#else - float precisionSafeLength( vec3 v ) { - float maxComponent = max3( abs( v ) ); - return length( v / maxComponent ) * maxComponent; - } -#endif -struct IncidentLight { - vec3 color; - vec3 direction; - bool visible; -}; -struct ReflectedLight { - vec3 directDiffuse; - vec3 directSpecular; - vec3 indirectDiffuse; - vec3 indirectSpecular; -}; -#ifdef USE_ALPHAHASH - varying vec3 vPosition; -#endif -vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); -} -vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); -} -bool isPerspectiveMatrix( mat4 m ) { - return m[ 2 ][ 3 ] == - 1.0; -} -vec2 equirectUv( in vec3 dir ) { - float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; - float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; - return vec2( u, v ); -} -vec3 BRDF_Lambert( const in vec3 diffuseColor ) { - return RECIPROCAL_PI * diffuseColor; -} -vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} -float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,aW=`#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`,rW=`vec3 transformedNormal = objectNormal; -#ifdef USE_TANGENT - vec3 transformedTangent = objectTangent; -#endif -#ifdef USE_BATCHING - mat3 bm = mat3( batchingMatrix ); - transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); - transformedNormal = bm * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = bm * transformedTangent; - #endif -#endif -#ifdef USE_INSTANCING - mat3 im = mat3( instanceMatrix ); - transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); - transformedNormal = im * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = im * transformedTangent; - #endif -#endif -transformedNormal = normalMatrix * transformedNormal; -#ifdef FLIP_SIDED - transformedNormal = - transformedNormal; -#endif -#ifdef USE_TANGENT - transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; - #ifdef FLIP_SIDED - transformedTangent = - transformedTangent; - #endif -#endif`,sW=`#ifdef USE_DISPLACEMENTMAP - uniform sampler2D displacementMap; - uniform float displacementScale; - uniform float displacementBias; -#endif`,oW=`#ifdef USE_DISPLACEMENTMAP - transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,lW=`#ifdef USE_EMISSIVEMAP - vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); - #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE - emissiveColor = sRGBTransferEOTF( emissiveColor ); - #endif - totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,cW=`#ifdef USE_EMISSIVEMAP - uniform sampler2D emissiveMap; -#endif`,uW="gl_FragColor = linearToOutputTexel( gl_FragColor );",hW=`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 ); -}`,fW=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vec3 cameraToFrag; - if ( isOrthographic ) { - cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToFrag = normalize( vWorldPosition - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vec3 reflectVec = reflect( cameraToFrag, worldNormal ); - #else - vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); - #endif - #else - vec3 reflectVec = vReflect; - #endif - #ifdef ENVMAP_TYPE_CUBE - vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); - #else - vec4 envColor = vec4( 0.0 ); - #endif - #ifdef ENVMAP_BLENDING_MULTIPLY - outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_MIX ) - outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_ADD ) - outgoingLight += envColor.xyz * specularStrength * reflectivity; - #endif -#endif`,dW=`#ifdef USE_ENVMAP - uniform float envMapIntensity; - uniform float flipEnvMap; - uniform mat3 envMapRotation; - #ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; - #else - uniform sampler2D envMap; - #endif -#endif`,pW=`#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`,mW=`#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`,gW=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vWorldPosition = worldPosition.xyz; - #else - vec3 cameraToVertex; - if ( isOrthographic ) { - cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vReflect = reflect( cameraToVertex, worldNormal ); - #else - vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); - #endif - #endif -#endif`,vW=`#ifdef USE_FOG - vFogDepth = - mvPosition.z; -#endif`,_W=`#ifdef USE_FOG - varying float vFogDepth; -#endif`,xW=`#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`,yW=`#ifdef USE_FOG - uniform vec3 fogColor; - varying float vFogDepth; - #ifdef FOG_EXP2 - uniform float fogDensity; - #else - uniform float fogNear; - uniform float fogFar; - #endif -#endif`,SW=`#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 -}`,TW=`#ifdef USE_LIGHTMAP - uniform sampler2D lightMap; - uniform float lightMapIntensity; -#endif`,EW=`LambertMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,MW=`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`,bW=`uniform bool receiveShadow; -uniform vec3 ambientLightColor; -#if defined( USE_LIGHT_PROBES ) - uniform vec3 lightProbe[ 9 ]; -#endif -vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { - float x = normal.x, y = normal.y, z = normal.z; - vec3 result = shCoefficients[ 0 ] * 0.886227; - result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; - result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; - result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; - result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; - result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; - result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); - result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; - result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); - return result; -} -vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); - return irradiance; -} -vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { - vec3 irradiance = ambientLightColor; - return irradiance; -} -float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { - float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); - if ( cutoffDistance > 0.0 ) { - distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); - } - return distanceFalloff; -} -float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { - return smoothstep( coneCosine, penumbraCosine, angleCosine ); -} -#if NUM_DIR_LIGHTS > 0 - struct DirectionalLight { - vec3 direction; - vec3 color; - }; - uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; - void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { - light.color = directionalLight.color; - light.direction = directionalLight.direction; - light.visible = true; - } -#endif -#if NUM_POINT_LIGHTS > 0 - struct PointLight { - vec3 position; - vec3 color; - float distance; - float decay; - }; - uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; - void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = pointLight.position - geometryPosition; - light.direction = normalize( lVector ); - float lightDistance = length( lVector ); - light.color = pointLight.color; - light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } -#endif -#if NUM_SPOT_LIGHTS > 0 - struct SpotLight { - vec3 position; - vec3 direction; - vec3 color; - float distance; - float decay; - float coneCos; - float penumbraCos; - }; - uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; - void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = spotLight.position - geometryPosition; - light.direction = normalize( lVector ); - float angleCos = dot( light.direction, spotLight.direction ); - float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); - if ( spotAttenuation > 0.0 ) { - float lightDistance = length( lVector ); - light.color = spotLight.color * spotAttenuation; - light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } else { - light.color = vec3( 0.0 ); - light.visible = false; - } - } -#endif -#if NUM_RECT_AREA_LIGHTS > 0 - struct RectAreaLight { - vec3 color; - vec3 position; - vec3 halfWidth; - vec3 halfHeight; - }; - uniform sampler2D ltc_1; uniform sampler2D ltc_2; - uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; -#endif -#if NUM_HEMI_LIGHTS > 0 - struct HemisphereLight { - vec3 direction; - vec3 skyColor; - vec3 groundColor; - }; - uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; - vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { - float dotNL = dot( normal, hemiLight.direction ); - float hemiDiffuseWeight = 0.5 * dotNL + 0.5; - vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); - return irradiance; - } -#endif`,AW=`#ifdef USE_ENVMAP - vec3 getIBLIrradiance( const in vec3 normal ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); - return PI * envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 reflectVec = reflect( - viewDir, normal ); - reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); - reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); - return envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - #ifdef USE_ANISOTROPY - vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 bentNormal = cross( bitangent, viewDir ); - bentNormal = normalize( cross( bentNormal, bitangent ) ); - bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); - return getIBLRadiance( viewDir, bentNormal, roughness ); - #else - return vec3( 0.0 ); - #endif - } - #endif -#endif`,wW=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,RW=`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`,CW=`BlinnPhongMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularColor = specular; -material.specularShininess = shininess; -material.specularStrength = specularStrength;`,NW=`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`,DW=`PhysicalMaterial material; -material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); -vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); -float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); -material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; -material.roughness = min( material.roughness, 1.0 ); -#ifdef IOR - material.ior = ior; - #ifdef USE_SPECULAR - float specularIntensityFactor = specularIntensity; - vec3 specularColorFactor = specularColor; - #ifdef USE_SPECULAR_COLORMAP - specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; - #endif - material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); - #else - float specularIntensityFactor = 1.0; - vec3 specularColorFactor = vec3( 1.0 ); - material.specularF90 = 1.0; - #endif - material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); -#else - material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); - material.specularF90 = 1.0; -#endif -#ifdef USE_CLEARCOAT - material.clearcoat = clearcoat; - material.clearcoatRoughness = clearcoatRoughness; - material.clearcoatF0 = vec3( 0.04 ); - material.clearcoatF90 = 1.0; - #ifdef USE_CLEARCOATMAP - material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; - #endif - #ifdef USE_CLEARCOAT_ROUGHNESSMAP - material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; - #endif - material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); - material.clearcoatRoughness += geometryRoughness; - material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); -#endif -#ifdef USE_DISPERSION - material.dispersion = dispersion; -#endif -#ifdef USE_IRIDESCENCE - material.iridescence = iridescence; - material.iridescenceIOR = iridescenceIOR; - #ifdef USE_IRIDESCENCEMAP - material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; - #endif - #ifdef USE_IRIDESCENCE_THICKNESSMAP - material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; - #else - material.iridescenceThickness = iridescenceThicknessMaximum; - #endif -#endif -#ifdef USE_SHEEN - material.sheenColor = sheenColor; - #ifdef USE_SHEEN_COLORMAP - material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; - #endif - material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); - #ifdef USE_SHEEN_ROUGHNESSMAP - material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; - #endif -#endif -#ifdef USE_ANISOTROPY - #ifdef USE_ANISOTROPYMAP - mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); - vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; - vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; - #else - vec2 anisotropyV = anisotropyVector; - #endif - material.anisotropy = length( anisotropyV ); - if( material.anisotropy == 0.0 ) { - anisotropyV = vec2( 1.0, 0.0 ); - } else { - anisotropyV /= material.anisotropy; - material.anisotropy = saturate( material.anisotropy ); - } - material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); - material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; - material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,OW=`uniform sampler2D dfgLUT; -struct PhysicalMaterial { - vec3 diffuseColor; - float roughness; - vec3 specularColor; - float specularF90; - float dispersion; - #ifdef USE_CLEARCOAT - float clearcoat; - float clearcoatRoughness; - vec3 clearcoatF0; - float clearcoatF90; - #endif - #ifdef USE_IRIDESCENCE - float iridescence; - float iridescenceIOR; - float iridescenceThickness; - vec3 iridescenceFresnel; - vec3 iridescenceF0; - #endif - #ifdef USE_SHEEN - vec3 sheenColor; - float sheenRoughness; - #endif - #ifdef IOR - float ior; - #endif - #ifdef USE_TRANSMISSION - float transmission; - float transmissionAlpha; - float thickness; - float attenuationDistance; - vec3 attenuationColor; - #endif - #ifdef USE_ANISOTROPY - float anisotropy; - float alphaT; - vec3 anisotropyT; - vec3 anisotropyB; - #endif -}; -vec3 clearcoatSpecularDirect = vec3( 0.0 ); -vec3 clearcoatSpecularIndirect = vec3( 0.0 ); -vec3 sheenSpecularDirect = vec3( 0.0 ); -vec3 sheenSpecularIndirect = vec3(0.0 ); -vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { - float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); - float x2 = x * x; - float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); - return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); -} -float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { - float a2 = pow2( alpha ); - float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); - float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); - return 0.5 / max( gv + gl, EPSILON ); -} -float D_GGX( const in float alpha, const in float dotNH ) { - float a2 = pow2( alpha ); - float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; - return RECIPROCAL_PI * a2 / pow2( denom ); -} -#ifdef USE_ANISOTROPY - float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { - float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); - float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); - float v = 0.5 / ( gv + gl ); - return saturate(v); - } - float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { - float a2 = alphaT * alphaB; - highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); - highp float v2 = dot( v, v ); - float w2 = a2 / v2; - return RECIPROCAL_PI * a2 * pow2 ( w2 ); - } -#endif -#ifdef USE_CLEARCOAT - vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { - vec3 f0 = material.clearcoatF0; - float f90 = material.clearcoatF90; - float roughness = material.clearcoatRoughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - return F * ( V * D ); - } -#endif -vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { - vec3 f0 = material.specularColor; - float f90 = material.specularF90; - float roughness = material.roughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - #ifdef USE_IRIDESCENCE - F = mix( F, material.iridescenceFresnel, material.iridescence ); - #endif - #ifdef USE_ANISOTROPY - float dotTL = dot( material.anisotropyT, lightDir ); - float dotTV = dot( material.anisotropyT, viewDir ); - float dotTH = dot( material.anisotropyT, halfDir ); - float dotBL = dot( material.anisotropyB, lightDir ); - float dotBV = dot( material.anisotropyB, viewDir ); - float dotBH = dot( material.anisotropyB, halfDir ); - float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); - float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); - #else - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - #endif - return F * ( V * D ); -} -vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { - const float LUT_SIZE = 64.0; - const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; - const float LUT_BIAS = 0.5 / LUT_SIZE; - float dotNV = saturate( dot( N, V ) ); - vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); - uv = uv * LUT_SCALE + LUT_BIAS; - return uv; -} -float LTC_ClippedSphereFormFactor( const in vec3 f ) { - float l = length( f ); - return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); -} -vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { - float x = dot( v1, v2 ); - float y = abs( x ); - float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; - float b = 3.4175940 + ( 4.1616724 + y ) * y; - float v = a / b; - float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; - return cross( v1, v2 ) * theta_sintheta; -} -vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { - vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; - vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; - vec3 lightNormal = cross( v1, v2 ); - if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); - vec3 T1, T2; - T1 = normalize( V - N * dot( V, N ) ); - T2 = - cross( N, T1 ); - mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); - vec3 coords[ 4 ]; - coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); - coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); - coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); - coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); - coords[ 0 ] = normalize( coords[ 0 ] ); - coords[ 1 ] = normalize( coords[ 1 ] ); - coords[ 2 ] = normalize( coords[ 2 ] ); - coords[ 3 ] = normalize( coords[ 3 ] ); - vec3 vectorFormFactor = vec3( 0.0 ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); - float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); - return vec3( result ); -} -#if defined( USE_SHEEN ) -float D_Charlie( float roughness, float dotNH ) { - float alpha = pow2( roughness ); - float invAlpha = 1.0 / alpha; - float cos2h = dotNH * dotNH; - float sin2h = max( 1.0 - cos2h, 0.0078125 ); - return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); -} -float V_Neubelt( float dotNV, float dotNL ) { - return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); -} -vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float D = D_Charlie( sheenRoughness, dotNH ); - float V = V_Neubelt( dotNV, dotNL ); - return sheenColor * ( D * V ); -} -#endif -float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - float r2 = roughness * roughness; - float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; - float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; - float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); - return saturate( DG * RECIPROCAL_PI ); -} -vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - vec2 uv = vec2( roughness, dotNV ); - return texture2D( dfgLUT, uv ).rg; -} -vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { - vec2 fab = DFGApprox( normal, viewDir, roughness ); - return specularColor * fab.x + specularF90 * fab.y; -} -#ifdef USE_IRIDESCENCE -void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#else -void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#endif - vec2 fab = DFGApprox( normal, viewDir, roughness ); - #ifdef USE_IRIDESCENCE - vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); - #else - vec3 Fr = specularColor; - #endif - vec3 FssEss = Fr * fab.x + specularF90 * fab.y; - float Ess = fab.x + fab.y; - float Ems = 1.0 - Ess; - vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); - singleScatter += FssEss; - multiScatter += Fms * Ems; -} -vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { - vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - vec2 dfgV = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNV * dotNV), 0.0, dotNV), material.roughness ); - vec2 dfgL = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNL * dotNL), 0.0, dotNL), material.roughness ); - vec3 FssEss_V = material.specularColor * dfgV.x + material.specularF90 * dfgV.y; - vec3 FssEss_L = material.specularColor * dfgL.x + material.specularF90 * dfgL.y; - float Ess_V = dfgV.x + dfgV.y; - float Ess_L = dfgL.x + dfgL.y; - float Ems_V = 1.0 - Ess_V; - float Ems_L = 1.0 - Ess_L; - vec3 Favg = material.specularColor + ( 1.0 - material.specularColor ) * 0.047619; - vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg * Favg + EPSILON ); - float compensationFactor = Ems_V * Ems_L; - vec3 multiScatter = Fms * compensationFactor; - return singleScatter + multiScatter; -} -#if NUM_RECT_AREA_LIGHTS > 0 - void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - vec3 normal = geometryNormal; - vec3 viewDir = geometryViewDir; - vec3 position = geometryPosition; - vec3 lightPos = rectAreaLight.position; - vec3 halfWidth = rectAreaLight.halfWidth; - vec3 halfHeight = rectAreaLight.halfHeight; - vec3 lightColor = rectAreaLight.color; - float roughness = material.roughness; - vec3 rectCoords[ 4 ]; - rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; - rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; - rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; - vec2 uv = LTC_Uv( normal, viewDir, roughness ); - vec4 t1 = texture2D( ltc_1, uv ); - vec4 t2 = texture2D( ltc_2, uv ); - mat3 mInv = mat3( - vec3( t1.x, 0, t1.y ), - vec3( 0, 1, 0 ), - vec3( t1.z, 0, t1.w ) - ); - vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); - reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); - reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); - } -#endif -void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - #ifdef USE_CLEARCOAT - float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); - vec3 ccIrradiance = dotNLcc * directLight.color; - clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); - #endif - #ifdef USE_SHEEN - sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); - #endif - reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { - #ifdef USE_CLEARCOAT - clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); - #endif - #ifdef USE_SHEEN - sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); - #endif - vec3 singleScattering = vec3( 0.0 ); - vec3 multiScattering = vec3( 0.0 ); - vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; - #ifdef USE_IRIDESCENCE - computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); - #else - computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); - #endif - vec3 totalScattering = singleScattering + multiScattering; - vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); - reflectedLight.indirectSpecular += radiance * singleScattering; - reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; - reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; -} -#define RE_Direct RE_Direct_Physical -#define RE_Direct_RectArea RE_Direct_RectArea_Physical -#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical -#define RE_IndirectSpecular RE_IndirectSpecular_Physical -float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { - return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,LW=` -vec3 geometryPosition = - vViewPosition; -vec3 geometryNormal = normal; -vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); -vec3 geometryClearcoatNormal = vec3( 0.0 ); -#ifdef USE_CLEARCOAT - geometryClearcoatNormal = clearcoatNormal; -#endif -#ifdef USE_IRIDESCENCE - float dotNVi = saturate( dot( normal, geometryViewDir ) ); - if ( material.iridescenceThickness == 0.0 ) { - material.iridescence = 0.0; - } else { - material.iridescence = saturate( material.iridescence ); - } - if ( material.iridescence > 0.0 ) { - material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); - material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); - } -#endif -IncidentLight directLight; -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - pointLight = pointLights[ i ]; - getPointLightInfo( pointLight, geometryPosition, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - SpotLight spotLight; - vec4 spotColor; - vec3 spotLightCoord; - bool inSpotLightMap; - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - spotLight = spotLights[ i ]; - getSpotLightInfo( spotLight, geometryPosition, directLight ); - #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX - #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS - #else - #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #endif - #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) - spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; - inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); - spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); - directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; - #endif - #undef SPOT_LIGHT_MAP_INDEX - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) - RectAreaLight rectAreaLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if defined( RE_IndirectDiffuse ) - vec3 iblIrradiance = vec3( 0.0 ); - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - #if defined( USE_LIGHT_PROBES ) - irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); - #endif - #if ( NUM_HEMI_LIGHTS > 0 ) - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - } - #pragma unroll_loop_end - #endif -#endif -#if defined( RE_IndirectSpecular ) - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,IW=`#if defined( RE_IndirectDiffuse ) - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; - irradiance += lightMapIrradiance; - #endif - #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) - iblIrradiance += getIBLIrradiance( geometryNormal ); - #endif -#endif -#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) - #ifdef USE_ANISOTROPY - radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); - #else - radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); - #endif - #ifdef USE_CLEARCOAT - clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); - #endif -#endif`,UW=`#if defined( RE_IndirectDiffuse ) - RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif -#if defined( RE_IndirectSpecular ) - RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,PW=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) - gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,zW=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) - uniform float logDepthBufFC; - varying float vFragDepth; - varying float vIsPerspective; -#endif`,BW=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER - varying float vFragDepth; - varying float vIsPerspective; -#endif`,HW=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER - vFragDepth = 1.0 + gl_Position.w; - vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,FW=`#ifdef USE_MAP - vec4 sampledDiffuseColor = texture2D( map, vMapUv ); - #ifdef DECODE_VIDEO_TEXTURE - sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); - #endif - diffuseColor *= sampledDiffuseColor; -#endif`,GW=`#ifdef USE_MAP - uniform sampler2D map; -#endif`,VW=`#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`,kW=`#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`,WW=`float metalnessFactor = metalness; -#ifdef USE_METALNESSMAP - vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); - metalnessFactor *= texelMetalness.b; -#endif`,XW=`#ifdef USE_METALNESSMAP - uniform sampler2D metalnessMap; -#endif`,YW=`#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`,qW=`#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`,jW=`#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`,ZW=`#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`,KW=`#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`,QW=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; -#ifdef FLAT_SHADED - vec3 fdx = dFdx( vViewPosition ); - vec3 fdy = dFdy( vViewPosition ); - vec3 normal = normalize( cross( fdx, fdy ) ); -#else - vec3 normal = normalize( vNormal ); - #ifdef DOUBLE_SIDED - normal *= faceDirection; - #endif -#endif -#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) - #ifdef USE_TANGENT - mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn = getTangentFrame( - vViewPosition, normal, - #if defined( USE_NORMALMAP ) - vNormalMapUv - #elif defined( USE_CLEARCOAT_NORMALMAP ) - vClearcoatNormalMapUv - #else - vUv - #endif - ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn[0] *= faceDirection; - tbn[1] *= faceDirection; - #endif -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - #ifdef USE_TANGENT - mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn2[0] *= faceDirection; - tbn2[1] *= faceDirection; - #endif -#endif -vec3 nonPerturbedNormal = normal;`,JW=`#ifdef USE_NORMALMAP_OBJECTSPACE - normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - #ifdef FLIP_SIDED - normal = - normal; - #endif - #ifdef DOUBLE_SIDED - normal = normal * faceDirection; - #endif - normal = normalize( normalMatrix * normal ); -#elif defined( USE_NORMALMAP_TANGENTSPACE ) - vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - mapN.xy *= normalScale; - normal = normalize( tbn * mapN ); -#elif defined( USE_BUMPMAP ) - normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,$W=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,eX=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,tX=`#ifndef FLAT_SHADED - vNormal = normalize( transformedNormal ); - #ifdef USE_TANGENT - vTangent = normalize( transformedTangent ); - vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); - #endif -#endif`,nX=`#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`,iX=`#ifdef USE_CLEARCOAT - vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,aX=`#ifdef USE_CLEARCOAT_NORMALMAP - vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; - clearcoatMapN.xy *= clearcoatNormalScale; - clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,rX=`#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`,sX=`#ifdef USE_IRIDESCENCEMAP - uniform sampler2D iridescenceMap; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform sampler2D iridescenceThicknessMap; -#endif`,oX=`#ifdef OPAQUE -diffuseColor.a = 1.0; -#endif -#ifdef USE_TRANSMISSION -diffuseColor.a *= material.transmissionAlpha; -#endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,lX=`vec3 packNormalToRGB( const in vec3 normal ) { - return normalize( normal ) * 0.5 + 0.5; -} -vec3 unpackRGBToNormal( const in vec3 rgb ) { - return 2.0 * rgb.xyz - 1.0; -} -const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; -const float Inv255 = 1. / 255.; -const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); -const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); -const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); -const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); -vec4 packDepthToRGBA( const in float v ) { - if( v <= 0.0 ) - return vec4( 0., 0., 0., 0. ); - if( v >= 1.0 ) - return vec4( 1., 1., 1., 1. ); - float vuf; - float af = modf( v * PackFactors.a, vuf ); - float bf = modf( vuf * ShiftRight8, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); -} -vec3 packDepthToRGB( const in float v ) { - if( v <= 0.0 ) - return vec3( 0., 0., 0. ); - if( v >= 1.0 ) - return vec3( 1., 1., 1. ); - float vuf; - float bf = modf( v * PackFactors.b, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec3( vuf * Inv255, gf * PackUpscale, bf ); -} -vec2 packDepthToRG( const in float v ) { - if( v <= 0.0 ) - return vec2( 0., 0. ); - if( v >= 1.0 ) - return vec2( 1., 1. ); - float vuf; - float gf = modf( v * 256., vuf ); - return vec2( vuf * Inv255, gf ); -} -float unpackRGBAToDepth( const in vec4 v ) { - return dot( v, UnpackFactors4 ); -} -float unpackRGBToDepth( const in vec3 v ) { - return dot( v, UnpackFactors3 ); -} -float unpackRGToDepth( const in vec2 v ) { - return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; -} -vec4 pack2HalfToRGBA( const in vec2 v ) { - vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); - return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); -} -vec2 unpackRGBATo2Half( const in vec4 v ) { - return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); -} -float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { - return ( viewZ + near ) / ( near - far ); -} -float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { - return depth * ( near - far ) - near; -} -float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { - return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); -} -float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { - return ( near * far ) / ( ( far - near ) * depth - far ); -}`,cX=`#ifdef PREMULTIPLIED_ALPHA - gl_FragColor.rgb *= gl_FragColor.a; -#endif`,uX=`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;`,hX=`#ifdef DITHERING - gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,fX=`#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`,dX=`float roughnessFactor = roughness; -#ifdef USE_ROUGHNESSMAP - vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); - roughnessFactor *= texelRoughness.g; -#endif`,pX=`#ifdef USE_ROUGHNESSMAP - uniform sampler2D roughnessMap; -#endif`,mX=`#if NUM_SPOT_LIGHT_COORDS > 0 - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#if NUM_SPOT_LIGHT_MAPS > 0 - uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif - float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { - float depth = unpackRGBAToDepth( texture2D( depths, uv ) ); - #ifdef USE_REVERSED_DEPTH_BUFFER - return step( depth, compare ); - #else - return step( compare, depth ); - #endif - } - vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { - return unpackRGBATo2Half( texture2D( shadow, uv ) ); - } - float VSMShadow( sampler2D shadow, vec2 uv, float compare ) { - float occlusion = 1.0; - vec2 distribution = texture2DDistribution( shadow, uv ); - #ifdef USE_REVERSED_DEPTH_BUFFER - float hard_shadow = step( distribution.x, compare ); - #else - float hard_shadow = step( compare, distribution.x ); - #endif - if ( hard_shadow != 1.0 ) { - float distance = compare - distribution.x; - float variance = max( 0.00000, distribution.y * distribution.y ); - float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); - } - return occlusion; - } - float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - float shadow = 1.0; - shadowCoord.xyz /= shadowCoord.w; - shadowCoord.z += shadowBias; - bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; - bool frustumTest = inFrustum && shadowCoord.z <= 1.0; - if ( frustumTest ) { - #if defined( SHADOWMAP_TYPE_PCF ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx0 = - texelSize.x * shadowRadius; - float dy0 = - texelSize.y * shadowRadius; - float dx1 = + texelSize.x * shadowRadius; - float dy1 = + texelSize.y * shadowRadius; - float dx2 = dx0 / 2.0; - float dy2 = dy0 / 2.0; - float dx3 = dx1 / 2.0; - float dy3 = dy1 / 2.0; - shadow = ( - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) - ) * ( 1.0 / 17.0 ); - #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx = texelSize.x; - float dy = texelSize.y; - vec2 uv = shadowCoord.xy; - vec2 f = fract( uv * shadowMapSize + 0.5 ); - uv -= f * texelSize; - shadow = ( - texture2DCompare( shadowMap, uv, shadowCoord.z ) + - texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + - texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + - mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), - f.x ) + - mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), - f.x ) + - mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), - f.y ) + - mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), - f.y ) + - mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), - f.x ), - mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), - f.x ), - f.y ) - ) * ( 1.0 / 9.0 ); - #elif defined( SHADOWMAP_TYPE_VSM ) - shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); - #else - shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } - vec2 cubeToUV( vec3 v, float texelSizeY ) { - vec3 absV = abs( v ); - float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); - absV *= scaleToCube; - v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); - vec2 planar = v.xy; - float almostATexel = 1.5 * texelSizeY; - float almostOne = 1.0 - almostATexel; - if ( absV.z >= almostOne ) { - if ( v.z > 0.0 ) - planar.x = 4.0 - v.x; - } else if ( absV.x >= almostOne ) { - float signX = sign( v.x ); - planar.x = v.z * signX + 2.0 * signX; - } else if ( absV.y >= almostOne ) { - float signY = sign( v.y ); - planar.x = v.x + 2.0 * signY + 2.0; - planar.y = v.z * signY - 2.0; - } - return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); - } - float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { - float shadow = 1.0; - vec3 lightToPosition = shadowCoord.xyz; - - float lightToPositionLength = length( lightToPosition ); - if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { - float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; - vec3 bd3D = normalize( lightToPosition ); - vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); - #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) - vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; - shadow = ( - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) - ) * ( 1.0 / 9.0 ); - #else - shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } -#endif`,gX=`#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`,vX=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) - vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - vec4 shadowWorldPosition; -#endif -#if defined( USE_SHADOWMAP ) - #if NUM_DIR_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); - vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); - vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif -#endif -#if NUM_SPOT_LIGHT_COORDS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { - shadowWorldPosition = worldPosition; - #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; - #endif - vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end -#endif`,_X=`float getShadowMask() { - float shadow = 1.0; - #ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - directionalLight = directionalLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { - spotLight = spotLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - pointLight = pointLightShadows[ i ]; - shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; - } - #pragma unroll_loop_end - #endif - #endif - return shadow; -}`,xX=`#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,yX=`#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`,SX=`#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`,TX=`#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`,EX=`float specularStrength; -#ifdef USE_SPECULARMAP - vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); - specularStrength = texelSpecular.r; -#else - specularStrength = 1.0; -#endif`,MX=`#ifdef USE_SPECULARMAP - uniform sampler2D specularMap; -#endif`,bX=`#if defined( TONE_MAPPING ) - gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,AX=`#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; }`,wX=`#ifdef USE_TRANSMISSION - material.transmission = transmission; - material.transmissionAlpha = 1.0; - material.thickness = thickness; - material.attenuationDistance = attenuationDistance; - material.attenuationColor = attenuationColor; - #ifdef USE_TRANSMISSIONMAP - material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; - #endif - #ifdef USE_THICKNESSMAP - material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; - #endif - vec3 pos = vWorldPosition; - vec3 v = normalize( cameraPosition - pos ); - vec3 n = inverseTransformDirection( normal, viewMatrix ); - vec4 transmitted = getIBLVolumeRefraction( - n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, - pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, - material.attenuationColor, material.attenuationDistance ); - material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); - totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,RX=`#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`,CX=`#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`,NX=`#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`,DX=`#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`,OX=`#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 LX=`varying vec2 vUv; -uniform mat3 uvTransform; -void main() { - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,IX=`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 -}`,UX=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,PX=`#ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; -#elif defined( ENVMAP_TYPE_CUBE_UV ) - uniform sampler2D envMap; -#endif -uniform float flipEnvMap; -uniform float backgroundBlurriness; -uniform float backgroundIntensity; -uniform mat3 backgroundRotation; -varying vec3 vWorldDirection; -#include -void main() { - #ifdef ENVMAP_TYPE_CUBE - vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); - #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); - #else - vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,zX=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,BX=`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 -}`,HX=`#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; -}`,FX=`#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 -}`,GX=`#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; -}`,VX=`#define DISTANCE -uniform vec3 referencePosition; -uniform float nearDistance; -uniform float farDistance; -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -#include -void main () { - vec4 diffuseColor = vec4( 1.0 ); - #include - #include - #include - #include - #include - float dist = length( vWorldPosition - referencePosition ); - dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); - dist = saturate( dist ); - gl_FragColor = packDepthToRGBA( dist ); -}`,kX=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include -}`,WX=`uniform sampler2D tEquirect; -varying vec3 vWorldDirection; -#include -void main() { - vec3 direction = normalize( vWorldDirection ); - vec2 sampleUV = equirectUv( direction ); - gl_FragColor = texture2D( tEquirect, sampleUV ); - #include - #include -}`,XX=`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 -}`,YX=`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 -}`,qX=`#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 -}`,jX=`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 -}`,ZX=`#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 -}`,KX=`#define LAMBERT -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,QX=`#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; -}`,JX=`#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 -}`,$X=`#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 -}`,eY=`#define NORMAL -uniform float opacity; -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); - #include - #include - #include - #include - gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); - #ifdef OPAQUE - gl_FragColor.a = 1.0; - #endif -}`,tY=`#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 -}`,nY=`#define PHONG -uniform vec3 diffuse; -uniform vec3 emissive; -uniform vec3 specular; -uniform float shininess; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,iY=`#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 -}`,aY=`#define STANDARD -#ifdef PHYSICAL - #define IOR - #define USE_SPECULAR -#endif -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float roughness; -uniform float metalness; -uniform float opacity; -#ifdef IOR - uniform float ior; -#endif -#ifdef USE_SPECULAR - uniform float specularIntensity; - uniform vec3 specularColor; - #ifdef USE_SPECULAR_COLORMAP - uniform sampler2D specularColorMap; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - uniform sampler2D specularIntensityMap; - #endif -#endif -#ifdef USE_CLEARCOAT - uniform float clearcoat; - uniform float clearcoatRoughness; -#endif -#ifdef USE_DISPERSION - uniform float dispersion; -#endif -#ifdef USE_IRIDESCENCE - uniform float iridescence; - uniform float iridescenceIOR; - uniform float iridescenceThicknessMinimum; - uniform float iridescenceThicknessMaximum; -#endif -#ifdef USE_SHEEN - uniform vec3 sheenColor; - uniform float sheenRoughness; - #ifdef USE_SHEEN_COLORMAP - uniform sampler2D sheenColorMap; - #endif - #ifdef USE_SHEEN_ROUGHNESSMAP - uniform sampler2D sheenRoughnessMap; - #endif -#endif -#ifdef USE_ANISOTROPY - uniform vec2 anisotropyVector; - #ifdef USE_ANISOTROPYMAP - uniform sampler2D anisotropyMap; - #endif -#endif -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; - vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; - #include - vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; - #ifdef USE_SHEEN - float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); - outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; - #endif - #ifdef USE_CLEARCOAT - float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); - vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); - outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; - #endif - #include - #include - #include - #include - #include - #include -}`,rY=`#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 -}`,sY=`#define TOON -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include -}`,oY=`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 -}`,lY=`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 -}`,cY=`#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,uY=`uniform vec3 color; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); - #include - #include - #include -}`,hY=`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 -}`,fY=`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 -}`,Qt={alphahash_fragment:Ik,alphahash_pars_fragment:Uk,alphamap_fragment:Pk,alphamap_pars_fragment:zk,alphatest_fragment:Bk,alphatest_pars_fragment:Hk,aomap_fragment:Fk,aomap_pars_fragment:Gk,batching_pars_vertex:Vk,batching_vertex:kk,begin_vertex:Wk,beginnormal_vertex:Xk,bsdfs:Yk,iridescence_fragment:qk,bumpmap_pars_fragment:jk,clipping_planes_fragment:Zk,clipping_planes_pars_fragment:Kk,clipping_planes_pars_vertex:Qk,clipping_planes_vertex:Jk,color_fragment:$k,color_pars_fragment:eW,color_pars_vertex:tW,color_vertex:nW,common:iW,cube_uv_reflection_fragment:aW,defaultnormal_vertex:rW,displacementmap_pars_vertex:sW,displacementmap_vertex:oW,emissivemap_fragment:lW,emissivemap_pars_fragment:cW,colorspace_fragment:uW,colorspace_pars_fragment:hW,envmap_fragment:fW,envmap_common_pars_fragment:dW,envmap_pars_fragment:pW,envmap_pars_vertex:mW,envmap_physical_pars_fragment:AW,envmap_vertex:gW,fog_vertex:vW,fog_pars_vertex:_W,fog_fragment:xW,fog_pars_fragment:yW,gradientmap_pars_fragment:SW,lightmap_pars_fragment:TW,lights_lambert_fragment:EW,lights_lambert_pars_fragment:MW,lights_pars_begin:bW,lights_toon_fragment:wW,lights_toon_pars_fragment:RW,lights_phong_fragment:CW,lights_phong_pars_fragment:NW,lights_physical_fragment:DW,lights_physical_pars_fragment:OW,lights_fragment_begin:LW,lights_fragment_maps:IW,lights_fragment_end:UW,logdepthbuf_fragment:PW,logdepthbuf_pars_fragment:zW,logdepthbuf_pars_vertex:BW,logdepthbuf_vertex:HW,map_fragment:FW,map_pars_fragment:GW,map_particle_fragment:VW,map_particle_pars_fragment:kW,metalnessmap_fragment:WW,metalnessmap_pars_fragment:XW,morphinstance_vertex:YW,morphcolor_vertex:qW,morphnormal_vertex:jW,morphtarget_pars_vertex:ZW,morphtarget_vertex:KW,normal_fragment_begin:QW,normal_fragment_maps:JW,normal_pars_fragment:$W,normal_pars_vertex:eX,normal_vertex:tX,normalmap_pars_fragment:nX,clearcoat_normal_fragment_begin:iX,clearcoat_normal_fragment_maps:aX,clearcoat_pars_fragment:rX,iridescence_pars_fragment:sX,opaque_fragment:oX,packing:lX,premultiplied_alpha_fragment:cX,project_vertex:uX,dithering_fragment:hX,dithering_pars_fragment:fX,roughnessmap_fragment:dX,roughnessmap_pars_fragment:pX,shadowmap_pars_fragment:mX,shadowmap_pars_vertex:gX,shadowmap_vertex:vX,shadowmask_pars_fragment:_X,skinbase_vertex:xX,skinning_pars_vertex:yX,skinning_vertex:SX,skinnormal_vertex:TX,specularmap_fragment:EX,specularmap_pars_fragment:MX,tonemapping_fragment:bX,tonemapping_pars_fragment:AX,transmission_fragment:wX,transmission_pars_fragment:RX,uv_pars_fragment:CX,uv_pars_vertex:NX,uv_vertex:DX,worldpos_vertex:OX,background_vert:LX,background_frag:IX,backgroundCube_vert:UX,backgroundCube_frag:PX,cube_vert:zX,cube_frag:BX,depth_vert:HX,depth_frag:FX,distanceRGBA_vert:GX,distanceRGBA_frag:VX,equirect_vert:kX,equirect_frag:WX,linedashed_vert:XX,linedashed_frag:YX,meshbasic_vert:qX,meshbasic_frag:jX,meshlambert_vert:ZX,meshlambert_frag:KX,meshmatcap_vert:QX,meshmatcap_frag:JX,meshnormal_vert:$X,meshnormal_frag:eY,meshphong_vert:tY,meshphong_frag:nY,meshphysical_vert:iY,meshphysical_frag:aY,meshtoon_vert:rY,meshtoon_frag:sY,points_vert:oY,points_frag:lY,shadow_vert:cY,shadow_frag:uY,sprite_vert:hY,sprite_frag:fY},at={common:{diffuse:{value:new je(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Et},alphaMap:{value:null},alphaMapTransform:{value:new Et},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Et}},envmap:{envMap:{value:null},envMapRotation:{value:new Et},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Et}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Et}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Et},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Et},normalScale:{value:new de(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Et},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Et}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Et}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Et}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new je(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new je(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Et},alphaTest:{value:0},uvTransform:{value:new Et}},sprite:{diffuse:{value:new je(16777215)},opacity:{value:1},center:{value:new de(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Et},alphaMap:{value:null},alphaMapTransform:{value:new Et},alphaTest:{value:0}}},bs={basic:{uniforms:wa([at.common,at.specularmap,at.envmap,at.aomap,at.lightmap,at.fog]),vertexShader:Qt.meshbasic_vert,fragmentShader:Qt.meshbasic_frag},lambert:{uniforms:wa([at.common,at.specularmap,at.envmap,at.aomap,at.lightmap,at.emissivemap,at.bumpmap,at.normalmap,at.displacementmap,at.fog,at.lights,{emissive:{value:new je(0)}}]),vertexShader:Qt.meshlambert_vert,fragmentShader:Qt.meshlambert_frag},phong:{uniforms:wa([at.common,at.specularmap,at.envmap,at.aomap,at.lightmap,at.emissivemap,at.bumpmap,at.normalmap,at.displacementmap,at.fog,at.lights,{emissive:{value:new je(0)},specular:{value:new je(1118481)},shininess:{value:30}}]),vertexShader:Qt.meshphong_vert,fragmentShader:Qt.meshphong_frag},standard:{uniforms:wa([at.common,at.envmap,at.aomap,at.lightmap,at.emissivemap,at.bumpmap,at.normalmap,at.displacementmap,at.roughnessmap,at.metalnessmap,at.fog,at.lights,{emissive:{value:new je(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Qt.meshphysical_vert,fragmentShader:Qt.meshphysical_frag},toon:{uniforms:wa([at.common,at.aomap,at.lightmap,at.emissivemap,at.bumpmap,at.normalmap,at.displacementmap,at.gradientmap,at.fog,at.lights,{emissive:{value:new je(0)}}]),vertexShader:Qt.meshtoon_vert,fragmentShader:Qt.meshtoon_frag},matcap:{uniforms:wa([at.common,at.bumpmap,at.normalmap,at.displacementmap,at.fog,{matcap:{value:null}}]),vertexShader:Qt.meshmatcap_vert,fragmentShader:Qt.meshmatcap_frag},points:{uniforms:wa([at.points,at.fog]),vertexShader:Qt.points_vert,fragmentShader:Qt.points_frag},dashed:{uniforms:wa([at.common,at.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Qt.linedashed_vert,fragmentShader:Qt.linedashed_frag},depth:{uniforms:wa([at.common,at.displacementmap]),vertexShader:Qt.depth_vert,fragmentShader:Qt.depth_frag},normal:{uniforms:wa([at.common,at.bumpmap,at.normalmap,at.displacementmap,{opacity:{value:1}}]),vertexShader:Qt.meshnormal_vert,fragmentShader:Qt.meshnormal_frag},sprite:{uniforms:wa([at.sprite,at.fog]),vertexShader:Qt.sprite_vert,fragmentShader:Qt.sprite_frag},background:{uniforms:{uvTransform:{value:new Et},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Qt.background_vert,fragmentShader:Qt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Et}},vertexShader:Qt.backgroundCube_vert,fragmentShader:Qt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Qt.cube_vert,fragmentShader:Qt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Qt.equirect_vert,fragmentShader:Qt.equirect_frag},distanceRGBA:{uniforms:wa([at.common,at.displacementmap,{referencePosition:{value:new L},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Qt.distanceRGBA_vert,fragmentShader:Qt.distanceRGBA_frag},shadow:{uniforms:wa([at.lights,at.fog,{color:{value:new je(0)},opacity:{value:1}}]),vertexShader:Qt.shadow_vert,fragmentShader:Qt.shadow_frag}};bs.physical={uniforms:wa([bs.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Et},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Et},clearcoatNormalScale:{value:new de(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Et},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Et},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Et},sheen:{value:0},sheenColor:{value:new je(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Et},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Et},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Et},transmissionSamplerSize:{value:new de},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Et},attenuationDistance:{value:0},attenuationColor:{value:new je(0)},specularColor:{value:new je(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Et},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Et},anisotropyVector:{value:new de},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Et}}]),vertexShader:Qt.meshphysical_vert,fragmentShader:Qt.meshphysical_frag};const Iv={r:0,b:0,g:0},su=new Ei,dY=new ke;function pY(n,e,t,i,a,r,s){const o=new je(0);let c=r===!0?0:1,h,f,d=null,m=0,g=null;function x(E){let b=E.isScene===!0?E.background:null;return b&&b.isTexture&&(b=(E.backgroundBlurriness>0?t:e).get(b)),b}function T(E){let b=!1;const D=x(E);D===null?v(o,c):D&&D.isColor&&(v(D,1),b=!0);const C=n.xr.getEnvironmentBlendMode();C==="additive"?i.buffers.color.setClear(0,0,0,1,s):C==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,s),(n.autoClear||b)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function y(E,b){const D=x(b);D&&(D.isCubeTexture||D.mapping===Xd)?(f===void 0&&(f=new oi(new ch(1,1,1),new Vi({name:"BackgroundCubeMaterial",uniforms:wd(bs.backgroundCube.uniforms),vertexShader:bs.backgroundCube.vertexShader,fragmentShader:bs.backgroundCube.fragmentShader,side:Ui,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),f.geometry.deleteAttribute("normal"),f.geometry.deleteAttribute("uv"),f.onBeforeRender=function(C,I,P){this.matrixWorld.copyPosition(P.matrixWorld)},Object.defineProperty(f.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),a.update(f)),su.copy(b.backgroundRotation),su.x*=-1,su.y*=-1,su.z*=-1,D.isCubeTexture&&D.isRenderTargetTexture===!1&&(su.y*=-1,su.z*=-1),f.material.uniforms.envMap.value=D,f.material.uniforms.flipEnvMap.value=D.isCubeTexture&&D.isRenderTargetTexture===!1?-1:1,f.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,f.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,f.material.uniforms.backgroundRotation.value.setFromMatrix4(dY.makeRotationFromEuler(su)),f.material.toneMapped=rn.getTransfer(D.colorSpace)!==wn,(d!==D||m!==D.version||g!==n.toneMapping)&&(f.material.needsUpdate=!0,d=D,m=D.version,g=n.toneMapping),f.layers.enableAll(),E.unshift(f,f.geometry,f.material,0,0,null)):D&&D.isTexture&&(h===void 0&&(h=new oi(new uh(2,2),new Vi({name:"BackgroundMaterial",uniforms:wd(bs.background.uniforms),vertexShader:bs.background.vertexShader,fragmentShader:bs.background.fragmentShader,side:Ns,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),Object.defineProperty(h.material,"map",{get:function(){return this.uniforms.t2D.value}}),a.update(h)),h.material.uniforms.t2D.value=D,h.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,h.material.toneMapped=rn.getTransfer(D.colorSpace)!==wn,D.matrixAutoUpdate===!0&&D.updateMatrix(),h.material.uniforms.uvTransform.value.copy(D.matrix),(d!==D||m!==D.version||g!==n.toneMapping)&&(h.material.needsUpdate=!0,d=D,m=D.version,g=n.toneMapping),h.layers.enableAll(),E.unshift(h,h.geometry,h.material,0,0,null))}function v(E,b){E.getRGB(Iv,GU(n)),i.buffers.color.setClear(Iv.r,Iv.g,Iv.b,b,s)}function S(){f!==void 0&&(f.geometry.dispose(),f.material.dispose(),f=void 0),h!==void 0&&(h.geometry.dispose(),h.material.dispose(),h=void 0)}return{getClearColor:function(){return o},setClearColor:function(E,b=1){o.set(E),c=b,v(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(E){c=E,v(o,c)},render:T,addToRenderList:y,dispose:S}}function mY(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},a=m(null);let r=a,s=!1;function o(w,B,j,ee,se){let re=!1;const W=d(ee,j,B);r!==W&&(r=W,h(r.object)),re=g(w,ee,j,se),re&&x(w,ee,j,se),se!==null&&e.update(se,n.ELEMENT_ARRAY_BUFFER),(re||s)&&(s=!1,b(w,B,j,ee),se!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(se).buffer))}function c(){return n.createVertexArray()}function h(w){return n.bindVertexArray(w)}function f(w){return n.deleteVertexArray(w)}function d(w,B,j){const ee=j.wireframe===!0;let se=i[w.id];se===void 0&&(se={},i[w.id]=se);let re=se[B.id];re===void 0&&(re={},se[B.id]=re);let W=re[ee];return W===void 0&&(W=m(c()),re[ee]=W),W}function m(w){const B=[],j=[],ee=[];for(let se=0;se=0){const ie=se[K];let Ce=re[K];if(Ce===void 0&&(K==="instanceMatrix"&&w.instanceMatrix&&(Ce=w.instanceMatrix),K==="instanceColor"&&w.instanceColor&&(Ce=w.instanceColor)),ie===void 0||ie.attribute!==Ce||Ce&&ie.data!==Ce.data)return!0;W++}return r.attributesNum!==W||r.index!==ee}function x(w,B,j,ee){const se={},re=B.attributes;let W=0;const te=j.getAttributes();for(const K in te)if(te[K].location>=0){let ie=re[K];ie===void 0&&(K==="instanceMatrix"&&w.instanceMatrix&&(ie=w.instanceMatrix),K==="instanceColor"&&w.instanceColor&&(ie=w.instanceColor));const Ce={};Ce.attribute=ie,ie&&ie.data&&(Ce.data=ie.data),se[K]=Ce,W++}r.attributes=se,r.attributesNum=W,r.index=ee}function T(){const w=r.newAttributes;for(let B=0,j=w.length;B=0){let oe=se[te];if(oe===void 0&&(te==="instanceMatrix"&&w.instanceMatrix&&(oe=w.instanceMatrix),te==="instanceColor"&&w.instanceColor&&(oe=w.instanceColor)),oe!==void 0){const ie=oe.normalized,Ce=oe.itemSize,Xe=e.get(oe);if(Xe===void 0)continue;const nt=Xe.buffer,tt=Xe.type,gt=Xe.bytesPerElement,ge=tt===n.INT||tt===n.UNSIGNED_INT||oe.gpuType===L0;if(oe.isInterleavedBufferAttribute){const Ae=oe.data,Ze=Ae.stride,ue=oe.offset;if(Ae.isInstancedInterleavedBuffer){for(let it=0;it0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";I="mediump"}return I==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let h=t.precision!==void 0?t.precision:"highp";const f=c(h);f!==h&&(ut("WebGLRenderer:",h,"not supported, using",f,"instead."),h=f);const d=t.logarithmicDepthBuffer===!0,m=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),g=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),x=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),T=n.getParameter(n.MAX_TEXTURE_SIZE),y=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),v=n.getParameter(n.MAX_VERTEX_ATTRIBS),S=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),E=n.getParameter(n.MAX_VARYING_VECTORS),b=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),D=x>0,C=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:s,textureTypeReadable:o,precision:h,logarithmicDepthBuffer:d,reversedDepthBuffer:m,maxTextures:g,maxVertexTextures:x,maxTextureSize:T,maxCubemapSize:y,maxAttributes:v,maxVertexUniforms:S,maxVaryings:E,maxFragmentUniforms:b,vertexTextures:D,maxSamples:C}}function _Y(n){const e=this;let t=null,i=0,a=!1,r=!1;const s=new Go,o=new Et,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(d,m){const g=d.length!==0||m||i!==0||a;return a=m,i=d.length,g},this.beginShadows=function(){r=!0,f(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(d,m){t=f(d,m,0)},this.setState=function(d,m,g){const x=d.clippingPlanes,T=d.clipIntersection,y=d.clipShadows,v=n.get(d);if(!a||x===null||x.length===0||r&&!y)r?f(null):h();else{const S=r?0:i,E=S*4;let b=v.clippingState||null;c.value=b,b=f(x,m,E,g);for(let D=0;D!==E;++D)b[D]=t[D];v.clippingState=b,this.numIntersection=T?this.numPlanes:0,this.numPlanes+=S}};function h(){c.value!==t&&(c.value=t,c.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function f(d,m,g,x){const T=d!==null?d.length:0;let y=null;if(T!==0){if(y=c.value,x!==!0||y===null){const v=g+T*4,S=m.matrixWorldInverse;o.getNormalMatrix(S),(y===null||y.length0){const h=new kU(c.height);return h.fromEquirectangularTexture(n,s),e.set(s,h),s.addEventListener("dispose",a),t(h.texture,s.mapping)}else return null}}return s}function a(s){const o=s.target;o.removeEventListener("dispose",a);const c=e.get(o);c!==void 0&&(e.delete(o),c.dispose())}function r(){e=new WeakMap}return{get:i,dispose:r}}const $l=4,gN=[.125,.215,.35,.446,.526,.582],yu=20,yY=256,Xp=new ao,vN=new je;let h2=null,f2=0,d2=0,p2=!1;const SY=new L;class gE{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,i=.1,a=100,r={}){const{size:s=256,position:o=SY}=r;h2=this._renderer.getRenderTarget(),f2=this._renderer.getActiveCubeFace(),d2=this._renderer.getActiveMipmapLevel(),p2=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,i,a,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=yN(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=xN(),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?D:0,D,D),d.setRenderTarget(a),v&&d.render(T,c),d.render(e,c)}d.toneMapping=g,d.autoClear=m,e.background=S}_textureToCubeUV(e,t){const i=this._renderer,a=e.mapping===rl||e.mapping===gc;a?(this._cubemapMaterial===null&&(this._cubemapMaterial=yN()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=xN());const r=a?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=r;const o=r.uniforms;o.envMap.value=e;const c=this._cubeSize;ff(t,0,0,3*c,2*c),i.setRenderTarget(t),i.render(s,Xp)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const a=this._lodMeshes.length;for(let r=1;rx-$l?i-x+$l:0),v=4*(this._cubeSize-T);c.envMap.value=e.texture,c.roughness.value=g,c.mipInt.value=x-t,ff(r,y,v,3*T,2*T),a.setRenderTarget(r),a.render(o,Xp),c.envMap.value=r.texture,c.roughness.value=0,c.mipInt.value=x-i,ff(e,y,v,3*T,2*T),a.setRenderTarget(e),a.render(o,Xp)}_blur(e,t,i,a,r){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,i,a,"latitudinal",r),this._halfBlur(s,e,i,i,a,"longitudinal",r)}_halfBlur(e,t,i,a,r,s,o){const c=this._renderer,h=this._blurMaterial;s!=="latitudinal"&&s!=="longitudinal"&&Bt("blur direction must be either latitudinal or longitudinal!");const f=3,d=this._lodMeshes[a];d.material=h;const m=h.uniforms,g=this._sizeLods[i]-1,x=isFinite(r)?Math.PI/(2*g):2*Math.PI/(2*yu-1),T=r/x,y=isFinite(r)?1+Math.floor(f*T):yu;y>yu&&ut(`sigmaRadians, ${r}, is too large and will clip, as it requested ${y} samples when the maximum is set to ${yu}`);const v=[];let S=0;for(let I=0;IE-$l?a-E+$l:0),C=4*(this._cubeSize-b);ff(t,D,C,3*b,2*b),c.setRenderTarget(t),c.render(d,Xp)}}function TY(n){const e=[],t=[],i=[];let a=n;const r=n-$l+1+gN.length;for(let s=0;sn-$l?c=gN[s-n+$l-1]:s===0&&(c=0),t.push(c);const h=1/(o-2),f=-h,d=1+h,m=[f,f,d,f,d,d,f,f,d,d,f,d],g=6,x=6,T=3,y=2,v=1,S=new Float32Array(T*x*g),E=new Float32Array(y*x*g),b=new Float32Array(v*x*g);for(let C=0;C2?0:-1,O=[I,P,0,I+2/3,P,0,I+2/3,P+1,0,I,P,0,I+2/3,P+1,0,I,P+1,0];S.set(O,T*x*C),E.set(m,y*x*C);const w=[C,C,C,C,C,C];b.set(w,v*x*C)}const D=new Ct;D.setAttribute("position",new Ot(S,T)),D.setAttribute("uv",new Ot(E,y)),D.setAttribute("faceIndex",new Ot(b,v)),i.push(new oi(D,null)),a>$l&&a--}return{lodMeshes:i,sizeLods:e,sigmas:t}}function _N(n,e,t){const i=new xi(n,e,t);return i.texture.mapping=Xd,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function ff(n,e,t,i,a){n.viewport.set(e,t,i,a),n.scissor.set(e,t,i,a)}function EY(n,e,t){return new Vi({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:yY,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:sy(),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 3.2: Transform view direction to hemisphere configuration - vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z)); - - // Section 4.1: Orthonormal basis - float lensq = Vh.x * Vh.x + Vh.y * Vh.y; - vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0); - vec3 T2 = cross(Vh, T1); - - // Section 4.2: Parameterization of projected area - float r = sqrt(Xi.x); - float phi = 2.0 * PI * Xi.y; - float t1 = r * cos(phi); - float t2 = r * sin(phi); - float s = 0.5 * (1.0 + Vh.z); - t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; - - // Section 4.3: Reprojection onto hemisphere - vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh; - - // Section 3.4: Transform back to ellipsoid configuration - return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); - } - - void main() { - vec3 N = normalize(vOutputDirection); - vec3 V = N; // Assume view direction equals normal for pre-filtering - - vec3 prefilteredColor = vec3(0.0); - float totalWeight = 0.0; - - // For very low roughness, just sample the environment directly - if (roughness < 0.001) { - gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); - return; - } - - // Tangent space basis for VNDF sampling - vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); - vec3 tangent = normalize(cross(up, N)); - vec3 bitangent = cross(N, tangent); - - for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { - vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); - - // For PMREM, V = N, so in tangent space V is always (0, 0, 1) - vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); - - // Transform H back to world space - vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); - vec3 L = normalize(2.0 * dot(V, H) * H - V); - - float NdotL = max(dot(N, L), 0.0); - - if(NdotL > 0.0) { - // Sample environment at fixed mip level - // VNDF importance sampling handles the distribution filtering - vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); - - // Weight by NdotL for the split-sum approximation - // VNDF PDF naturally accounts for the visible microfacet distribution - prefilteredColor += sampleColor * NdotL; - totalWeight += NdotL; - } - } - - if (totalWeight > 0.0) { - prefilteredColor = prefilteredColor / totalWeight; - } - - gl_FragColor = vec4(prefilteredColor, 1.0); - } - `,blending:Ta,depthTest:!1,depthWrite:!1})}function MY(n,e,t){const i=new Float32Array(yu),a=new L(0,1,0);return new Vi({name:"SphericalGaussianBlur",defines:{n:yu,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:a}},vertexShader:sy(),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:Ta,depthTest:!1,depthWrite:!1})}function xN(){return new Vi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:sy(),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:Ta,depthTest:!1,depthWrite:!1})}function yN(){return new Vi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:sy(),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:Ta,depthTest:!1,depthWrite:!1})}function sy(){return` - - precision mediump float; - precision mediump int; - - attribute float faceIndex; - - varying vec3 vOutputDirection; - - // RH coordinate system; PMREM face-indexing convention - vec3 getDirection( vec2 uv, float face ) { - - uv = 2.0 * uv - 1.0; - - vec3 direction = vec3( uv, 1.0 ); - - if ( face == 0.0 ) { - - direction = direction.zyx; // ( 1, v, u ) pos x - - } else if ( face == 1.0 ) { - - direction = direction.xzy; - direction.xz *= -1.0; // ( -u, 1, -v ) pos y - - } else if ( face == 2.0 ) { - - direction.x *= -1.0; // ( -u, v, 1 ) pos z - - } else if ( face == 3.0 ) { - - direction = direction.zyx; - direction.xz *= -1.0; // ( -1, v, -u ) neg x - - } else if ( face == 4.0 ) { - - direction = direction.xzy; - direction.xy *= -1.0; // ( -u, -1, v ) neg y - - } else if ( face == 5.0 ) { - - direction.z *= -1.0; // ( u, v, -1 ) neg z - - } - - return direction; - - } - - void main() { - - vOutputDirection = getDirection( uv, faceIndex ); - gl_Position = vec4( position, 1.0 ); - - } - `}function bY(n){let e=new WeakMap,t=null;function i(o){if(o&&o.isTexture){const c=o.mapping,h=c===s0||c===o0,f=c===rl||c===gc;if(h||f){let d=e.get(o);const m=d!==void 0?d.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==m)return t===null&&(t=new gE(n)),d=h?t.fromEquirectangular(o,d):t.fromCubemap(o,d),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),d.texture;if(d!==void 0)return d.texture;{const g=o.image;return h&&g&&g.height>0||f&&g&&a(g)?(t===null&&(t=new gE(n)),d=h?t.fromEquirectangular(o):t.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),o.addEventListener("dispose",r),d.texture):null}}}return o}function a(o){let c=0;const h=6;for(let f=0;fe.maxTextureSize&&(C=Math.ceil(D/e.maxTextureSize),D=e.maxTextureSize);const I=new Float32Array(D*C*4*d),P=new B1(I,D,C,d);P.type=si,P.needsUpdate=!0;const O=b*4;for(let B=0;B0)return n;const a=e*t;let r=TN[a];if(r===void 0&&(r=new Float32Array(a),TN[a]=r),e!==0){i.toArray(r,0);for(let s=1,o=0;s!==e;++s)o+=t,n[s].toArray(r,o)}return r}function ki(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t":" "} ${o}: ${t[s]}`)}return i.join(` -`)}const CN=new Et;function bq(n){rn._getMatrix(CN,rn.workingColorSpace,n);const e=`mat3( ${CN.elements.map(t=>t.toFixed(4))} )`;switch(rn.getTransfer(n)){case c0:return[e,"LinearTransferOETF"];case wn:return[e,"sRGBTransferOETF"];default:return ut("WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function NN(n,e,t){const i=n.getShaderParameter(e,n.COMPILE_STATUS),r=(n.getShaderInfoLog(e)||"").trim();if(i&&r==="")return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const o=parseInt(s[1]);return t.toUpperCase()+` - -`+r+` - -`+Mq(n.getShaderSource(e),o)}else return r}function Aq(n,e){const t=bq(e);return[`vec4 ${n}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` -`)}function wq(n,e){let t;switch(e){case pU:t="Linear";break;case mU:t="Reinhard";break;case gU:t="Cineon";break;case hb:t="ACESFilmic";break;case _U:t="AgX";break;case xU:t="Neutral";break;case vU:t="Custom";break;default:ut("WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const Uv=new L;function Rq(){rn.getLuminanceCoefficients(Uv);const n=Uv.x.toFixed(4),e=Uv.y.toFixed(4),t=Uv.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` -`)}function Cq(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(hm).join(` -`)}function Nq(n){const e=[];for(const t in n){const i=n[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(` -`)}function Dq(n,e){const t={},i=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let a=0;a/gm;function vE(n){return n.replace(Oq,Iq)}const Lq=new Map;function Iq(n,e){let t=Qt[e];if(t===void 0){const i=Lq.get(e);if(i!==void 0)t=Qt[i],ut('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return vE(t)}const Uq=/#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 LN(n){return n.replace(Uq,Pq)}function Pq(n,e,t,i){let a="";for(let r=parseInt(e);r0&&(y+=` -`),v=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,x].filter(hm).join(` -`),v.length>0&&(v+=` -`)):(y=[IN(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,x,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+f:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.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(hm).join(` -`),v=[IN(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,x,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.envMap?"#define "+f:"",t.envMap?"#define "+d:"",m?"#define CUBEUV_TEXEL_WIDTH "+m.texelWidth:"",m?"#define CUBEUV_TEXEL_HEIGHT "+m.texelHeight:"",m?"#define CUBEUV_MAX_MIP "+m.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==is?"#define TONE_MAPPING":"",t.toneMapping!==is?Qt.tonemapping_pars_fragment:"",t.toneMapping!==is?wq("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Qt.colorspace_pars_fragment,Aq("linearToOutputTexel",t.outputColorSpace),Rq(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` -`].filter(hm).join(` -`)),s=vE(s),s=DN(s,t),s=ON(s,t),o=vE(o),o=DN(o,t),o=ON(o,t),s=LN(s),o=LN(o),t.isRawShaderMaterial!==!0&&(S=`#version 300 es -`,y=[g,"#define attribute in","#define varying out","#define texture2D texture"].join(` -`)+` -`+y,v=["#define varying in",t.glslVersion===ro?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===ro?"":"#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(` -`)+` -`+v);const E=S+y+s,b=S+v+o,D=RN(a,a.VERTEX_SHADER,E),C=RN(a,a.FRAGMENT_SHADER,b);a.attachShader(T,D),a.attachShader(T,C),t.index0AttributeName!==void 0?a.bindAttribLocation(T,0,t.index0AttributeName):t.morphTargets===!0&&a.bindAttribLocation(T,0,"position"),a.linkProgram(T);function I(B){if(n.debug.checkShaderErrors){const j=a.getProgramInfoLog(T)||"",ee=a.getShaderInfoLog(D)||"",se=a.getShaderInfoLog(C)||"",re=j.trim(),W=ee.trim(),te=se.trim();let K=!0,oe=!0;if(a.getProgramParameter(T,a.LINK_STATUS)===!1)if(K=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(a,T,D,C);else{const ie=NN(a,D,"vertex"),Ce=NN(a,C,"fragment");Bt("THREE.WebGLProgram: Shader Error "+a.getError()+" - VALIDATE_STATUS "+a.getProgramParameter(T,a.VALIDATE_STATUS)+` - -Material Name: `+B.name+` -Material Type: `+B.type+` - -Program Info Log: `+re+` -`+ie+` -`+Ce)}else re!==""?ut("WebGLProgram: Program Info Log:",re):(W===""||te==="")&&(oe=!1);oe&&(B.diagnostics={runnable:K,programLog:re,vertexShader:{log:W,prefix:y},fragmentShader:{log:te,prefix:v}})}a.deleteShader(D),a.deleteShader(C),P=new v_(a,T),O=Dq(a,T)}let P;this.getUniforms=function(){return P===void 0&&I(this),P};let O;this.getAttributes=function(){return O===void 0&&I(this),O};let w=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return w===!1&&(w=a.getProgramParameter(T,Tq)),w},this.destroy=function(){i.releaseStatesOfProgram(this),a.deleteProgram(T),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=Eq++,this.cacheKey=e,this.usedTimes=1,this.program=T,this.vertexShader=D,this.fragmentShader=C,this}let kq=0;class Wq{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,a=this._getShaderStage(t),r=this._getShaderStage(i),s=this._getShaderCacheForMaterial(e);return s.has(a)===!1&&(s.add(a),a.usedTimes++),s.has(r)===!1&&(s.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new Xq(e),t.set(e,i)),i}}class Xq{constructor(e){this.id=kq++,this.code=e,this.usedTimes=0}}function Yq(n,e,t,i,a,r,s){const o=new Ad,c=new Wq,h=new Set,f=[],d=a.logarithmicDepthBuffer,m=a.vertexTextures;let g=a.precision;const x={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function T(O){return h.add(O),O===0?"uv":`uv${O}`}function y(O,w,B,j,ee){const se=j.fog,re=ee.geometry,W=O.isMeshStandardMaterial?j.environment:null,te=(O.isMeshStandardMaterial?t:e).get(O.envMap||W),K=te&&te.mapping===Xd?te.image.height:null,oe=x[O.type];O.precision!==null&&(g=a.getMaxPrecision(O.precision),g!==O.precision&&ut("WebGLProgram.getParameters:",O.precision,"not supported, using",g,"instead."));const ie=re.morphAttributes.position||re.morphAttributes.normal||re.morphAttributes.color,Ce=ie!==void 0?ie.length:0;let Xe=0;re.morphAttributes.position!==void 0&&(Xe=1),re.morphAttributes.normal!==void 0&&(Xe=2),re.morphAttributes.color!==void 0&&(Xe=3);let nt,tt,gt,ge;if(oe){const Vt=bs[oe];nt=Vt.vertexShader,tt=Vt.fragmentShader}else nt=O.vertexShader,tt=O.fragmentShader,c.update(O),gt=c.getVertexShaderID(O),ge=c.getFragmentShaderID(O);const Ae=n.getRenderTarget(),Ze=n.state.buffers.depth.getReversed(),ue=ee.isInstancedMesh===!0,it=ee.isBatchedMesh===!0,Mt=!!O.map,ot=!!O.matcap,Ke=!!te,Te=!!O.aoMap,G=!!O.lightMap,be=!!O.bumpMap,De=!!O.normalMap,Fe=!!O.displacementMap,Be=!!O.emissiveMap,$e=!!O.metalnessMap,Je=!!O.roughnessMap,ct=O.anisotropy>0,k=O.clearcoat>0,U=O.dispersion>0,ce=O.iridescence>0,Ee=O.sheen>0,Le=O.transmission>0,ye=ct&&!!O.anisotropyMap,vt=k&&!!O.clearcoatMap,qe=k&&!!O.clearcoatNormalMap,_t=k&&!!O.clearcoatRoughnessMap,pt=ce&&!!O.iridescenceMap,Ie=ce&&!!O.iridescenceThicknessMap,He=Ee&&!!O.sheenColorMap,ht=Ee&&!!O.sheenRoughnessMap,Q=!!O.specularMap,pe=!!O.specularColorMap,Oe=!!O.specularIntensityMap,q=Le&&!!O.transmissionMap,Ve=Le&&!!O.thicknessMap,me=!!O.gradientMap,We=!!O.alphaMap,Ge=O.alphaTest>0,we=!!O.alphaHash,rt=!!O.extensions;let yt=is;O.toneMapped&&(Ae===null||Ae.isXRRenderTarget===!0)&&(yt=n.toneMapping);const Gt={shaderID:oe,shaderType:O.type,shaderName:O.name,vertexShader:nt,fragmentShader:tt,defines:O.defines,customVertexShaderID:gt,customFragmentShaderID:ge,isRawShaderMaterial:O.isRawShaderMaterial===!0,glslVersion:O.glslVersion,precision:g,batching:it,batchingColor:it&&ee._colorsTexture!==null,instancing:ue,instancingColor:ue&&ee.instanceColor!==null,instancingMorph:ue&&ee.morphTexture!==null,supportsVertexTextures:m,outputColorSpace:Ae===null?n.outputColorSpace:Ae.isXRRenderTarget===!0?Ae.texture.colorSpace:Wn,alphaToCoverage:!!O.alphaToCoverage,map:Mt,matcap:ot,envMap:Ke,envMapMode:Ke&&te.mapping,envMapCubeUVHeight:K,aoMap:Te,lightMap:G,bumpMap:be,normalMap:De,displacementMap:m&&Fe,emissiveMap:Be,normalMapObjectSpace:De&&O.normalMapType===AU,normalMapTangentSpace:De&&O.normalMapType===ll,metalnessMap:$e,roughnessMap:Je,anisotropy:ct,anisotropyMap:ye,clearcoat:k,clearcoatMap:vt,clearcoatNormalMap:qe,clearcoatRoughnessMap:_t,dispersion:U,iridescence:ce,iridescenceMap:pt,iridescenceThicknessMap:Ie,sheen:Ee,sheenColorMap:He,sheenRoughnessMap:ht,specularMap:Q,specularColorMap:pe,specularIntensityMap:Oe,transmission:Le,transmissionMap:q,thicknessMap:Ve,gradientMap:me,opaque:O.transparent===!1&&O.blending===Iu&&O.alphaToCoverage===!1,alphaMap:We,alphaTest:Ge,alphaHash:we,combine:O.combine,mapUv:Mt&&T(O.map.channel),aoMapUv:Te&&T(O.aoMap.channel),lightMapUv:G&&T(O.lightMap.channel),bumpMapUv:be&&T(O.bumpMap.channel),normalMapUv:De&&T(O.normalMap.channel),displacementMapUv:Fe&&T(O.displacementMap.channel),emissiveMapUv:Be&&T(O.emissiveMap.channel),metalnessMapUv:$e&&T(O.metalnessMap.channel),roughnessMapUv:Je&&T(O.roughnessMap.channel),anisotropyMapUv:ye&&T(O.anisotropyMap.channel),clearcoatMapUv:vt&&T(O.clearcoatMap.channel),clearcoatNormalMapUv:qe&&T(O.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:_t&&T(O.clearcoatRoughnessMap.channel),iridescenceMapUv:pt&&T(O.iridescenceMap.channel),iridescenceThicknessMapUv:Ie&&T(O.iridescenceThicknessMap.channel),sheenColorMapUv:He&&T(O.sheenColorMap.channel),sheenRoughnessMapUv:ht&&T(O.sheenRoughnessMap.channel),specularMapUv:Q&&T(O.specularMap.channel),specularColorMapUv:pe&&T(O.specularColorMap.channel),specularIntensityMapUv:Oe&&T(O.specularIntensityMap.channel),transmissionMapUv:q&&T(O.transmissionMap.channel),thicknessMapUv:Ve&&T(O.thicknessMap.channel),alphaMapUv:We&&T(O.alphaMap.channel),vertexTangents:!!re.attributes.tangent&&(De||ct),vertexColors:O.vertexColors,vertexAlphas:O.vertexColors===!0&&!!re.attributes.color&&re.attributes.color.itemSize===4,pointsUvs:ee.isPoints===!0&&!!re.attributes.uv&&(Mt||We),fog:!!se,useFog:O.fog===!0,fogExp2:!!se&&se.isFogExp2,flatShading:O.flatShading===!0&&O.wireframe===!1,sizeAttenuation:O.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:Ze,skinning:ee.isSkinnedMesh===!0,morphTargets:re.morphAttributes.position!==void 0,morphNormals:re.morphAttributes.normal!==void 0,morphColors:re.morphAttributes.color!==void 0,morphTargetsCount:Ce,morphTextureStride:Xe,numDirLights:w.directional.length,numPointLights:w.point.length,numSpotLights:w.spot.length,numSpotLightMaps:w.spotLightMap.length,numRectAreaLights:w.rectArea.length,numHemiLights:w.hemi.length,numDirLightShadows:w.directionalShadowMap.length,numPointLightShadows:w.pointShadowMap.length,numSpotLightShadows:w.spotShadowMap.length,numSpotLightShadowsWithMaps:w.numSpotLightShadowsWithMaps,numLightProbes:w.numLightProbes,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:O.dithering,shadowMapEnabled:n.shadowMap.enabled&&B.length>0,shadowMapType:n.shadowMap.type,toneMapping:yt,decodeVideoTexture:Mt&&O.map.isVideoTexture===!0&&rn.getTransfer(O.map.colorSpace)===wn,decodeVideoTextureEmissive:Be&&O.emissiveMap.isVideoTexture===!0&&rn.getTransfer(O.emissiveMap.colorSpace)===wn,premultipliedAlpha:O.premultipliedAlpha,doubleSided:O.side===ca,flipSided:O.side===Ui,useDepthPacking:O.depthPacking>=0,depthPacking:O.depthPacking||0,index0AttributeName:O.index0AttributeName,extensionClipCullDistance:rt&&O.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(rt&&O.extensions.multiDraw===!0||it)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:O.customProgramCacheKey()};return Gt.vertexUv1s=h.has(1),Gt.vertexUv2s=h.has(2),Gt.vertexUv3s=h.has(3),h.clear(),Gt}function v(O){const w=[];if(O.shaderID?w.push(O.shaderID):(w.push(O.customVertexShaderID),w.push(O.customFragmentShaderID)),O.defines!==void 0)for(const B in O.defines)w.push(B),w.push(O.defines[B]);return O.isRawShaderMaterial===!1&&(S(w,O),E(w,O),w.push(n.outputColorSpace)),w.push(O.customProgramCacheKey),w.join()}function S(O,w){O.push(w.precision),O.push(w.outputColorSpace),O.push(w.envMapMode),O.push(w.envMapCubeUVHeight),O.push(w.mapUv),O.push(w.alphaMapUv),O.push(w.lightMapUv),O.push(w.aoMapUv),O.push(w.bumpMapUv),O.push(w.normalMapUv),O.push(w.displacementMapUv),O.push(w.emissiveMapUv),O.push(w.metalnessMapUv),O.push(w.roughnessMapUv),O.push(w.anisotropyMapUv),O.push(w.clearcoatMapUv),O.push(w.clearcoatNormalMapUv),O.push(w.clearcoatRoughnessMapUv),O.push(w.iridescenceMapUv),O.push(w.iridescenceThicknessMapUv),O.push(w.sheenColorMapUv),O.push(w.sheenRoughnessMapUv),O.push(w.specularMapUv),O.push(w.specularColorMapUv),O.push(w.specularIntensityMapUv),O.push(w.transmissionMapUv),O.push(w.thicknessMapUv),O.push(w.combine),O.push(w.fogExp2),O.push(w.sizeAttenuation),O.push(w.morphTargetsCount),O.push(w.morphAttributeCount),O.push(w.numDirLights),O.push(w.numPointLights),O.push(w.numSpotLights),O.push(w.numSpotLightMaps),O.push(w.numHemiLights),O.push(w.numRectAreaLights),O.push(w.numDirLightShadows),O.push(w.numPointLightShadows),O.push(w.numSpotLightShadows),O.push(w.numSpotLightShadowsWithMaps),O.push(w.numLightProbes),O.push(w.shadowMapType),O.push(w.toneMapping),O.push(w.numClippingPlanes),O.push(w.numClipIntersection),O.push(w.depthPacking)}function E(O,w){o.disableAll(),w.supportsVertexTextures&&o.enable(0),w.instancing&&o.enable(1),w.instancingColor&&o.enable(2),w.instancingMorph&&o.enable(3),w.matcap&&o.enable(4),w.envMap&&o.enable(5),w.normalMapObjectSpace&&o.enable(6),w.normalMapTangentSpace&&o.enable(7),w.clearcoat&&o.enable(8),w.iridescence&&o.enable(9),w.alphaTest&&o.enable(10),w.vertexColors&&o.enable(11),w.vertexAlphas&&o.enable(12),w.vertexUv1s&&o.enable(13),w.vertexUv2s&&o.enable(14),w.vertexUv3s&&o.enable(15),w.vertexTangents&&o.enable(16),w.anisotropy&&o.enable(17),w.alphaHash&&o.enable(18),w.batching&&o.enable(19),w.dispersion&&o.enable(20),w.batchingColor&&o.enable(21),w.gradientMap&&o.enable(22),O.push(o.mask),o.disableAll(),w.fog&&o.enable(0),w.useFog&&o.enable(1),w.flatShading&&o.enable(2),w.logarithmicDepthBuffer&&o.enable(3),w.reversedDepthBuffer&&o.enable(4),w.skinning&&o.enable(5),w.morphTargets&&o.enable(6),w.morphNormals&&o.enable(7),w.morphColors&&o.enable(8),w.premultipliedAlpha&&o.enable(9),w.shadowMapEnabled&&o.enable(10),w.doubleSided&&o.enable(11),w.flipSided&&o.enable(12),w.useDepthPacking&&o.enable(13),w.dithering&&o.enable(14),w.transmission&&o.enable(15),w.sheen&&o.enable(16),w.opaque&&o.enable(17),w.pointsUvs&&o.enable(18),w.decodeVideoTexture&&o.enable(19),w.decodeVideoTextureEmissive&&o.enable(20),w.alphaToCoverage&&o.enable(21),O.push(o.mask)}function b(O){const w=x[O.type];let B;if(w){const j=bs[w];B=Mb.clone(j.uniforms)}else B=O.uniforms;return B}function D(O,w){let B;for(let j=0,ee=f.length;j0?i.push(v):g.transparent===!0?a.push(v):t.push(v)}function c(d,m,g,x,T,y){const v=s(d,m,g,x,T,y);g.transmission>0?i.unshift(v):g.transparent===!0?a.unshift(v):t.unshift(v)}function h(d,m){t.length>1&&t.sort(d||jq),i.length>1&&i.sort(m||UN),a.length>1&&a.sort(m||UN)}function f(){for(let d=e,m=n.length;d=r.length?(s=new PN,r.push(s)):s=r[a],s}function t(){n=new WeakMap}return{get:e,dispose:t}}function Kq(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new L,color:new je};break;case"SpotLight":t={position:new L,direction:new L,color:new je,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new L,color:new je,distance:0,decay:0};break;case"HemisphereLight":t={direction:new L,skyColor:new je,groundColor:new je};break;case"RectAreaLight":t={color:new je,position:new L,halfWidth:new L,halfHeight:new L};break}return n[e.id]=t,t}}}function Qq(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new de};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new de};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new de,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let Jq=0;function $q(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function ej(n){const e=new Kq,t=Qq(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let h=0;h<9;h++)i.probe.push(new L);const a=new L,r=new ke,s=new ke;function o(h){let f=0,d=0,m=0;for(let O=0;O<9;O++)i.probe[O].set(0,0,0);let g=0,x=0,T=0,y=0,v=0,S=0,E=0,b=0,D=0,C=0,I=0;h.sort($q);for(let O=0,w=h.length;O0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=at.LTC_FLOAT_1,i.rectAreaLTC2=at.LTC_FLOAT_2):(i.rectAreaLTC1=at.LTC_HALF_1,i.rectAreaLTC2=at.LTC_HALF_2)),i.ambient[0]=f,i.ambient[1]=d,i.ambient[2]=m;const P=i.hash;(P.directionalLength!==g||P.pointLength!==x||P.spotLength!==T||P.rectAreaLength!==y||P.hemiLength!==v||P.numDirectionalShadows!==S||P.numPointShadows!==E||P.numSpotShadows!==b||P.numSpotMaps!==D||P.numLightProbes!==I)&&(i.directional.length=g,i.spot.length=T,i.rectArea.length=y,i.point.length=x,i.hemi.length=v,i.directionalShadow.length=S,i.directionalShadowMap.length=S,i.pointShadow.length=E,i.pointShadowMap.length=E,i.spotShadow.length=b,i.spotShadowMap.length=b,i.directionalShadowMatrix.length=S,i.pointShadowMatrix.length=E,i.spotLightMatrix.length=b+D-C,i.spotLightMap.length=D,i.numSpotLightShadowsWithMaps=C,i.numLightProbes=I,P.directionalLength=g,P.pointLength=x,P.spotLength=T,P.rectAreaLength=y,P.hemiLength=v,P.numDirectionalShadows=S,P.numPointShadows=E,P.numSpotShadows=b,P.numSpotMaps=D,P.numLightProbes=I,i.version=Jq++)}function c(h,f){let d=0,m=0,g=0,x=0,T=0;const y=f.matrixWorldInverse;for(let v=0,S=h.length;v=s.length?(o=new zN(n),s.push(o)):o=s[r],o}function i(){e=new WeakMap}return{get:t,dispose:i}}const nj=`void main() { - gl_Position = vec4( position, 1.0 ); -}`,ij=`uniform sampler2D shadow_pass; -uniform vec2 resolution; -uniform float radius; -#include -void main() { - const float samples = float( VSM_SAMPLES ); - float mean = 0.0; - float squared_mean = 0.0; - float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); - float uvStart = samples <= 1.0 ? 0.0 : - 1.0; - for ( float i = 0.0; i < samples; i ++ ) { - float uvOffset = uvStart + i * uvStride; - #ifdef HORIZONTAL_PASS - vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); - mean += distribution.x; - squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; - #else - float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); - mean += depth; - squared_mean += depth * depth; - #endif - } - mean = mean / samples; - squared_mean = squared_mean / samples; - float std_dev = sqrt( squared_mean - mean * mean ); - gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); -}`;function aj(n,e,t){let i=new Yd;const a=new de,r=new de,s=new zt,o=new zb({depthPacking:bU}),c=new Bb,h={},f=t.maxTextureSize,d={[Ns]:Ui,[Ui]:Ns,[ca]:ca},m=new Vi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new de},radius:{value:4}},vertexShader:nj,fragmentShader:ij}),g=m.clone();g.defines.HORIZONTAL_PASS=1;const x=new Ct;x.setAttribute("position",new Ot(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const T=new oi(x,m),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=R1;let v=this.type;this.render=function(C,I,P){if(y.enabled===!1||y.autoUpdate===!1&&y.needsUpdate===!1||C.length===0)return;const O=n.getRenderTarget(),w=n.getActiveCubeFace(),B=n.getActiveMipmapLevel(),j=n.state;j.setBlending(Ta),j.buffers.depth.getReversed()===!0?j.buffers.color.setClear(0,0,0,0):j.buffers.color.setClear(1,1,1,1),j.buffers.depth.setTest(!0),j.setScissorTest(!1);const ee=v!==Ss&&this.type===Ss,se=v===Ss&&this.type!==Ss;for(let re=0,W=C.length;ref||a.y>f)&&(a.x>f&&(r.x=Math.floor(f/oe.x),a.x=r.x*oe.x,K.mapSize.x=r.x),a.y>f&&(r.y=Math.floor(f/oe.y),a.y=r.y*oe.y,K.mapSize.y=r.y)),K.map===null||ee===!0||se===!0){const Ce=this.type!==Ss?{minFilter:Fn,magFilter:Fn}:{};K.map!==null&&K.map.dispose(),K.map=new xi(a.x,a.y,Ce),K.map.texture.name=te.name+".shadowMap",K.camera.updateProjectionMatrix()}n.setRenderTarget(K.map),n.clear();const ie=K.getViewportCount();for(let Ce=0;Ce0||I.map&&I.alphaTest>0||I.alphaToCoverage===!0){const j=w.uuid,ee=I.uuid;let se=h[j];se===void 0&&(se={},h[j]=se);let re=se[ee];re===void 0&&(re=w.clone(),se[ee]=re,I.addEventListener("dispose",D)),w=re}if(w.visible=I.visible,w.wireframe=I.wireframe,O===Ss?w.side=I.shadowSide!==null?I.shadowSide:I.side:w.side=I.shadowSide!==null?I.shadowSide:d[I.side],w.alphaMap=I.alphaMap,w.alphaTest=I.alphaToCoverage===!0?.5:I.alphaTest,w.map=I.map,w.clipShadows=I.clipShadows,w.clippingPlanes=I.clippingPlanes,w.clipIntersection=I.clipIntersection,w.displacementMap=I.displacementMap,w.displacementScale=I.displacementScale,w.displacementBias=I.displacementBias,w.wireframeLinewidth=I.wireframeLinewidth,w.linewidth=I.linewidth,P.isPointLight===!0&&w.isMeshDistanceMaterial===!0){const j=n.properties.get(w);j.light=P}return w}function b(C,I,P,O,w){if(C.visible===!1)return;if(C.layers.test(I.layers)&&(C.isMesh||C.isLine||C.isPoints)&&(C.castShadow||C.receiveShadow&&w===Ss)&&(!C.frustumCulled||i.intersectsObject(C))){C.modelViewMatrix.multiplyMatrices(P.matrixWorldInverse,C.matrixWorld);const ee=e.update(C),se=C.material;if(Array.isArray(se)){const re=ee.groups;for(let W=0,te=re.length;W=1):K.indexOf("OpenGL ES")!==-1&&(te=parseFloat(/^OpenGL ES (\d)/.exec(K)[1]),W=te>=2);let oe=null,ie={};const Ce=n.getParameter(n.SCISSOR_BOX),Xe=n.getParameter(n.VIEWPORT),nt=new zt().fromArray(Ce),tt=new zt().fromArray(Xe);function gt(q,Ve,me,We){const Ge=new Uint8Array(4),we=n.createTexture();n.bindTexture(q,we),n.texParameteri(q,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(q,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let rt=0;rt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),h=new de,f=new WeakMap;let d;const m=new WeakMap;let g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function x(k,U){return g?new OffscreenCanvas(k,U):h0("canvas")}function T(k,U,ce){let Ee=1;const Le=ct(k);if((Le.width>ce||Le.height>ce)&&(Ee=ce/Math.max(Le.width,Le.height)),Ee<1)if(typeof HTMLImageElement<"u"&&k instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&k instanceof ImageBitmap||typeof VideoFrame<"u"&&k instanceof VideoFrame){const ye=Math.floor(Ee*Le.width),vt=Math.floor(Ee*Le.height);d===void 0&&(d=x(ye,vt));const qe=U?x(ye,vt):d;return qe.width=ye,qe.height=vt,qe.getContext("2d").drawImage(k,0,0,ye,vt),ut("WebGLRenderer: Texture has been resized from ("+Le.width+"x"+Le.height+") to ("+ye+"x"+vt+")."),qe}else return"data"in k&&ut("WebGLRenderer: Image in DataTexture is too big ("+Le.width+"x"+Le.height+")."),k;return k}function y(k){return k.generateMipmaps}function v(k){n.generateMipmap(k)}function S(k){return k.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:k.isWebGL3DRenderTarget?n.TEXTURE_3D:k.isWebGLArrayRenderTarget||k.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function E(k,U,ce,Ee,Le=!1){if(k!==null){if(n[k]!==void 0)return n[k];ut("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+k+"'")}let ye=U;if(U===n.RED&&(ce===n.FLOAT&&(ye=n.R32F),ce===n.HALF_FLOAT&&(ye=n.R16F),ce===n.UNSIGNED_BYTE&&(ye=n.R8)),U===n.RED_INTEGER&&(ce===n.UNSIGNED_BYTE&&(ye=n.R8UI),ce===n.UNSIGNED_SHORT&&(ye=n.R16UI),ce===n.UNSIGNED_INT&&(ye=n.R32UI),ce===n.BYTE&&(ye=n.R8I),ce===n.SHORT&&(ye=n.R16I),ce===n.INT&&(ye=n.R32I)),U===n.RG&&(ce===n.FLOAT&&(ye=n.RG32F),ce===n.HALF_FLOAT&&(ye=n.RG16F),ce===n.UNSIGNED_BYTE&&(ye=n.RG8)),U===n.RG_INTEGER&&(ce===n.UNSIGNED_BYTE&&(ye=n.RG8UI),ce===n.UNSIGNED_SHORT&&(ye=n.RG16UI),ce===n.UNSIGNED_INT&&(ye=n.RG32UI),ce===n.BYTE&&(ye=n.RG8I),ce===n.SHORT&&(ye=n.RG16I),ce===n.INT&&(ye=n.RG32I)),U===n.RGB_INTEGER&&(ce===n.UNSIGNED_BYTE&&(ye=n.RGB8UI),ce===n.UNSIGNED_SHORT&&(ye=n.RGB16UI),ce===n.UNSIGNED_INT&&(ye=n.RGB32UI),ce===n.BYTE&&(ye=n.RGB8I),ce===n.SHORT&&(ye=n.RGB16I),ce===n.INT&&(ye=n.RGB32I)),U===n.RGBA_INTEGER&&(ce===n.UNSIGNED_BYTE&&(ye=n.RGBA8UI),ce===n.UNSIGNED_SHORT&&(ye=n.RGBA16UI),ce===n.UNSIGNED_INT&&(ye=n.RGBA32UI),ce===n.BYTE&&(ye=n.RGBA8I),ce===n.SHORT&&(ye=n.RGBA16I),ce===n.INT&&(ye=n.RGBA32I)),U===n.RGB&&(ce===n.UNSIGNED_INT_5_9_9_9_REV&&(ye=n.RGB9_E5),ce===n.UNSIGNED_INT_10F_11F_11F_REV&&(ye=n.R11F_G11F_B10F)),U===n.RGBA){const vt=Le?c0:rn.getTransfer(Ee);ce===n.FLOAT&&(ye=n.RGBA32F),ce===n.HALF_FLOAT&&(ye=n.RGBA16F),ce===n.UNSIGNED_BYTE&&(ye=vt===wn?n.SRGB8_ALPHA8:n.RGBA8),ce===n.UNSIGNED_SHORT_4_4_4_4&&(ye=n.RGBA4),ce===n.UNSIGNED_SHORT_5_5_5_1&&(ye=n.RGB5_A1)}return(ye===n.R16F||ye===n.R32F||ye===n.RG16F||ye===n.RG32F||ye===n.RGBA16F||ye===n.RGBA32F)&&e.get("EXT_color_buffer_float"),ye}function b(k,U){let ce;return k?U===null||U===Ds||U===qu?ce=n.DEPTH24_STENCIL8:U===si?ce=n.DEPTH32F_STENCIL8:U===Yu&&(ce=n.DEPTH24_STENCIL8,ut("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):U===null||U===Ds||U===qu?ce=n.DEPTH_COMPONENT24:U===si?ce=n.DEPTH_COMPONENT32F:U===Yu&&(ce=n.DEPTH_COMPONENT16),ce}function D(k,U){return y(k)===!0||k.isFramebufferTexture&&k.minFilter!==Fn&&k.minFilter!==Ht?Math.log2(Math.max(U.width,U.height))+1:k.mipmaps!==void 0&&k.mipmaps.length>0?k.mipmaps.length:k.isCompressedTexture&&Array.isArray(k.image)?U.mipmaps.length:1}function C(k){const U=k.target;U.removeEventListener("dispose",C),P(U),U.isVideoTexture&&f.delete(U)}function I(k){const U=k.target;U.removeEventListener("dispose",I),w(U)}function P(k){const U=i.get(k);if(U.__webglInit===void 0)return;const ce=k.source,Ee=m.get(ce);if(Ee){const Le=Ee[U.__cacheKey];Le.usedTimes--,Le.usedTimes===0&&O(k),Object.keys(Ee).length===0&&m.delete(ce)}i.remove(k)}function O(k){const U=i.get(k);n.deleteTexture(U.__webglTexture);const ce=k.source,Ee=m.get(ce);delete Ee[U.__cacheKey],s.memory.textures--}function w(k){const U=i.get(k);if(k.depthTexture&&(k.depthTexture.dispose(),i.remove(k.depthTexture)),k.isWebGLCubeRenderTarget)for(let Ee=0;Ee<6;Ee++){if(Array.isArray(U.__webglFramebuffer[Ee]))for(let Le=0;Le=a.maxTextures&&ut("WebGLTextures: Trying to use "+k+" texture units while this GPU supports only "+a.maxTextures),B+=1,k}function se(k){const U=[];return U.push(k.wrapS),U.push(k.wrapT),U.push(k.wrapR||0),U.push(k.magFilter),U.push(k.minFilter),U.push(k.anisotropy),U.push(k.internalFormat),U.push(k.format),U.push(k.type),U.push(k.generateMipmaps),U.push(k.premultiplyAlpha),U.push(k.flipY),U.push(k.unpackAlignment),U.push(k.colorSpace),U.join()}function re(k,U){const ce=i.get(k);if(k.isVideoTexture&&$e(k),k.isRenderTargetTexture===!1&&k.isExternalTexture!==!0&&k.version>0&&ce.__version!==k.version){const Ee=k.image;if(Ee===null)ut("WebGLRenderer: Texture marked for update but no image data found.");else if(Ee.complete===!1)ut("WebGLRenderer: Texture marked for update but image is incomplete");else{ge(ce,k,U);return}}else k.isExternalTexture&&(ce.__webglTexture=k.sourceTexture?k.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,ce.__webglTexture,n.TEXTURE0+U)}function W(k,U){const ce=i.get(k);if(k.isRenderTargetTexture===!1&&k.version>0&&ce.__version!==k.version){ge(ce,k,U);return}else k.isExternalTexture&&(ce.__webglTexture=k.sourceTexture?k.sourceTexture:null);t.bindTexture(n.TEXTURE_2D_ARRAY,ce.__webglTexture,n.TEXTURE0+U)}function te(k,U){const ce=i.get(k);if(k.isRenderTargetTexture===!1&&k.version>0&&ce.__version!==k.version){ge(ce,k,U);return}t.bindTexture(n.TEXTURE_3D,ce.__webglTexture,n.TEXTURE0+U)}function K(k,U){const ce=i.get(k);if(k.version>0&&ce.__version!==k.version){Ae(ce,k,U);return}t.bindTexture(n.TEXTURE_CUBE_MAP,ce.__webglTexture,n.TEXTURE0+U)}const oe={[Ea]:n.REPEAT,[Pi]:n.CLAMP_TO_EDGE,[xd]:n.MIRRORED_REPEAT},ie={[Fn]:n.NEAREST,[N1]:n.NEAREST_MIPMAP_NEAREST,[Tu]:n.NEAREST_MIPMAP_LINEAR,[Ht]:n.LINEAR,[id]:n.LINEAR_MIPMAP_NEAREST,[Mr]:n.LINEAR_MIPMAP_LINEAR},Ce={[wU]:n.NEVER,[LU]:n.ALWAYS,[RU]:n.LESS,[xb]:n.LEQUAL,[CU]:n.EQUAL,[OU]:n.GEQUAL,[NU]:n.GREATER,[DU]:n.NOTEQUAL};function Xe(k,U){if(U.type===si&&e.has("OES_texture_float_linear")===!1&&(U.magFilter===Ht||U.magFilter===id||U.magFilter===Tu||U.magFilter===Mr||U.minFilter===Ht||U.minFilter===id||U.minFilter===Tu||U.minFilter===Mr)&&ut("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(k,n.TEXTURE_WRAP_S,oe[U.wrapS]),n.texParameteri(k,n.TEXTURE_WRAP_T,oe[U.wrapT]),(k===n.TEXTURE_3D||k===n.TEXTURE_2D_ARRAY)&&n.texParameteri(k,n.TEXTURE_WRAP_R,oe[U.wrapR]),n.texParameteri(k,n.TEXTURE_MAG_FILTER,ie[U.magFilter]),n.texParameteri(k,n.TEXTURE_MIN_FILTER,ie[U.minFilter]),U.compareFunction&&(n.texParameteri(k,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(k,n.TEXTURE_COMPARE_FUNC,Ce[U.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(U.magFilter===Fn||U.minFilter!==Tu&&U.minFilter!==Mr||U.type===si&&e.has("OES_texture_float_linear")===!1)return;if(U.anisotropy>1||i.get(U).__currentAnisotropy){const ce=e.get("EXT_texture_filter_anisotropic");n.texParameterf(k,ce.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(U.anisotropy,a.getMaxAnisotropy())),i.get(U).__currentAnisotropy=U.anisotropy}}}function nt(k,U){let ce=!1;k.__webglInit===void 0&&(k.__webglInit=!0,U.addEventListener("dispose",C));const Ee=U.source;let Le=m.get(Ee);Le===void 0&&(Le={},m.set(Ee,Le));const ye=se(U);if(ye!==k.__cacheKey){Le[ye]===void 0&&(Le[ye]={texture:n.createTexture(),usedTimes:0},s.memory.textures++,ce=!0),Le[ye].usedTimes++;const vt=Le[k.__cacheKey];vt!==void 0&&(Le[k.__cacheKey].usedTimes--,vt.usedTimes===0&&O(U)),k.__cacheKey=ye,k.__webglTexture=Le[ye].texture}return ce}function tt(k,U,ce){return Math.floor(Math.floor(k/ce)/U)}function gt(k,U,ce,Ee){const ye=k.updateRanges;if(ye.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,U.width,U.height,ce,Ee,U.data);else{ye.sort((Ie,He)=>Ie.start-He.start);let vt=0;for(let Ie=1;Ie0){q&&Ve&&t.texStorage2D(n.TEXTURE_2D,We,Q,Oe[0].width,Oe[0].height);for(let Ge=0,we=Oe.length;Ge0){const rt=mE(pe.width,pe.height,U.format,U.type);for(const yt of U.layerUpdates){const Gt=pe.data.subarray(yt*rt/pe.data.BYTES_PER_ELEMENT,(yt+1)*rt/pe.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ge,0,0,yt,pe.width,pe.height,1,He,Gt)}U.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ge,0,0,0,pe.width,pe.height,Ie.depth,He,pe.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,Ge,Q,pe.width,pe.height,Ie.depth,0,pe.data,0,0);else ut("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else q?me&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,Ge,0,0,0,pe.width,pe.height,Ie.depth,He,ht,pe.data):t.texImage3D(n.TEXTURE_2D_ARRAY,Ge,Q,pe.width,pe.height,Ie.depth,0,He,ht,pe.data)}else{q&&Ve&&t.texStorage2D(n.TEXTURE_2D,We,Q,Oe[0].width,Oe[0].height);for(let Ge=0,we=Oe.length;Ge0){const Ge=mE(Ie.width,Ie.height,U.format,U.type);for(const we of U.layerUpdates){const rt=Ie.data.subarray(we*Ge/Ie.data.BYTES_PER_ELEMENT,(we+1)*Ge/Ie.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,we,Ie.width,Ie.height,1,He,ht,rt)}U.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,Ie.width,Ie.height,Ie.depth,He,ht,Ie.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,Q,Ie.width,Ie.height,Ie.depth,0,He,ht,Ie.data);else if(U.isData3DTexture)q?(Ve&&t.texStorage3D(n.TEXTURE_3D,We,Q,Ie.width,Ie.height,Ie.depth),me&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,Ie.width,Ie.height,Ie.depth,He,ht,Ie.data)):t.texImage3D(n.TEXTURE_3D,0,Q,Ie.width,Ie.height,Ie.depth,0,He,ht,Ie.data);else if(U.isFramebufferTexture){if(Ve)if(q)t.texStorage2D(n.TEXTURE_2D,We,Q,Ie.width,Ie.height);else{let Ge=Ie.width,we=Ie.height;for(let rt=0;rt>=1,we>>=1}}else if(Oe.length>0){if(q&&Ve){const Ge=ct(Oe[0]);t.texStorage2D(n.TEXTURE_2D,We,Q,Ge.width,Ge.height)}for(let Ge=0,we=Oe.length;Ge0&&We++;const we=ct(He[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,We,Oe,we.width,we.height)}for(let we=0;we<6;we++)if(Ie){q?me&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+we,0,0,0,He[we].width,He[we].height,Q,pe,He[we].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+we,0,Oe,He[we].width,He[we].height,0,Q,pe,He[we].data);for(let rt=0;rt>ye),ht=Math.max(1,U.height>>ye);Le===n.TEXTURE_3D||Le===n.TEXTURE_2D_ARRAY?t.texImage3D(Le,ye,_t,He,ht,U.depth,0,vt,qe,null):t.texImage2D(Le,ye,_t,He,ht,0,vt,qe,null)}t.bindFramebuffer(n.FRAMEBUFFER,k),Be(U)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,Ee,Le,Ie.__webglTexture,0,Fe(U)):(Le===n.TEXTURE_2D||Le>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&Le<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,Ee,Le,Ie.__webglTexture,ye),t.bindFramebuffer(n.FRAMEBUFFER,null)}function ue(k,U,ce){if(n.bindRenderbuffer(n.RENDERBUFFER,k),U.depthBuffer){const Ee=U.depthTexture,Le=Ee&&Ee.isDepthTexture?Ee.type:null,ye=b(U.stencilBuffer,Le),vt=U.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,qe=Fe(U);Be(U)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,qe,ye,U.width,U.height):ce?n.renderbufferStorageMultisample(n.RENDERBUFFER,qe,ye,U.width,U.height):n.renderbufferStorage(n.RENDERBUFFER,ye,U.width,U.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,vt,n.RENDERBUFFER,k)}else{const Ee=U.textures;for(let Le=0;Le{delete U.__boundDepthTexture,delete U.__depthDisposeCallback,Ee.removeEventListener("dispose",Le)};Ee.addEventListener("dispose",Le),U.__depthDisposeCallback=Le}U.__boundDepthTexture=Ee}if(k.depthTexture&&!U.__autoAllocateDepthBuffer){if(ce)throw new Error("target.depthTexture not supported in Cube render targets");const Ee=k.texture.mipmaps;Ee&&Ee.length>0?it(U.__webglFramebuffer[0],k):it(U.__webglFramebuffer,k)}else if(ce){U.__webglDepthbuffer=[];for(let Ee=0;Ee<6;Ee++)if(t.bindFramebuffer(n.FRAMEBUFFER,U.__webglFramebuffer[Ee]),U.__webglDepthbuffer[Ee]===void 0)U.__webglDepthbuffer[Ee]=n.createRenderbuffer(),ue(U.__webglDepthbuffer[Ee],k,!1);else{const Le=k.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ye=U.__webglDepthbuffer[Ee];n.bindRenderbuffer(n.RENDERBUFFER,ye),n.framebufferRenderbuffer(n.FRAMEBUFFER,Le,n.RENDERBUFFER,ye)}}else{const Ee=k.texture.mipmaps;if(Ee&&Ee.length>0?t.bindFramebuffer(n.FRAMEBUFFER,U.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,U.__webglFramebuffer),U.__webglDepthbuffer===void 0)U.__webglDepthbuffer=n.createRenderbuffer(),ue(U.__webglDepthbuffer,k,!1);else{const Le=k.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ye=U.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ye),n.framebufferRenderbuffer(n.FRAMEBUFFER,Le,n.RENDERBUFFER,ye)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function ot(k,U,ce){const Ee=i.get(k);U!==void 0&&Ze(Ee.__webglFramebuffer,k,k.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),ce!==void 0&&Mt(k)}function Ke(k){const U=k.texture,ce=i.get(k),Ee=i.get(U);k.addEventListener("dispose",I);const Le=k.textures,ye=k.isWebGLCubeRenderTarget===!0,vt=Le.length>1;if(vt||(Ee.__webglTexture===void 0&&(Ee.__webglTexture=n.createTexture()),Ee.__version=U.version,s.memory.textures++),ye){ce.__webglFramebuffer=[];for(let qe=0;qe<6;qe++)if(U.mipmaps&&U.mipmaps.length>0){ce.__webglFramebuffer[qe]=[];for(let _t=0;_t0){ce.__webglFramebuffer=[];for(let qe=0;qe0&&Be(k)===!1){ce.__webglMultisampledFramebuffer=n.createFramebuffer(),ce.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,ce.__webglMultisampledFramebuffer);for(let qe=0;qe0)for(let _t=0;_t0)for(let _t=0;_t0){if(Be(k)===!1){const U=k.textures,ce=k.width,Ee=k.height;let Le=n.COLOR_BUFFER_BIT;const ye=k.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,vt=i.get(k),qe=U.length>1;if(qe)for(let pt=0;pt0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,vt.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,vt.__webglFramebuffer);for(let pt=0;pt0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&U.__useRenderToTexture!==!1}function $e(k){const U=s.render.frame;f.get(k)!==U&&(f.set(k,U),k.update())}function Je(k,U){const ce=k.colorSpace,Ee=k.format,Le=k.type;return k.isCompressedTexture===!0||k.isVideoTexture===!0||ce!==Wn&&ce!==Da&&(rn.getTransfer(ce)===wn?(Ee!==$n||Le!==zi)&&ut("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Bt("WebGLTextures: Unsupported texture color space:",ce)),U}function ct(k){return typeof HTMLImageElement<"u"&&k instanceof HTMLImageElement?(h.width=k.naturalWidth||k.width,h.height=k.naturalHeight||k.height):typeof VideoFrame<"u"&&k instanceof VideoFrame?(h.width=k.displayWidth,h.height=k.displayHeight):(h.width=k.width,h.height=k.height),h}this.allocateTextureUnit=ee,this.resetTextureUnits=j,this.setTexture2D=re,this.setTexture2DArray=W,this.setTexture3D=te,this.setTextureCube=K,this.rebindTextures=ot,this.setupRenderTarget=Ke,this.updateRenderTargetMipmap=Te,this.updateMultisampleRenderTarget=De,this.setupDepthRenderbuffer=Mt,this.setupFrameBufferTexture=Ze,this.useMultisampledRTT=Be}function F6(n,e){function t(i,a=Da){let r;const s=rn.getTransfer(a);if(i===zi)return n.UNSIGNED_BYTE;if(i===L1)return n.UNSIGNED_SHORT_4_4_4_4;if(i===I1)return n.UNSIGNED_SHORT_5_5_5_1;if(i===fb)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===db)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===D1)return n.BYTE;if(i===O1)return n.SHORT;if(i===Yu)return n.UNSIGNED_SHORT;if(i===L0)return n.INT;if(i===Ds)return n.UNSIGNED_INT;if(i===si)return n.FLOAT;if(i===Xn)return n.HALF_FLOAT;if(i===pb)return n.ALPHA;if(i===mb)return n.RGB;if(i===$n)return n.RGBA;if(i===yd)return n.DEPTH_COMPONENT;if(i===ju)return n.DEPTH_STENCIL;if(i===As)return n.RED;if(i===I0)return n.RED_INTEGER;if(i===ko)return n.RG;if(i===U1)return n.RG_INTEGER;if(i===P1)return n.RGBA_INTEGER;if(i===Om||i===Lm||i===Im||i===Um)if(s===wn)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(i===Om)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Lm)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Im)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Um)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(i===Om)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Lm)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Im)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Um)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===lx||i===cx||i===ux||i===hx)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(i===lx)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===cx)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===ux)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===hx)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===fx||i===dx||i===px)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(i===fx||i===dx)return s===wn?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(i===px)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===mx||i===gx||i===vx||i===_x||i===xx||i===yx||i===Sx||i===Tx||i===Ex||i===Mx||i===bx||i===Ax||i===wx||i===Rx)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(i===mx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===gx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===vx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===_x)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===xx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===yx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Sx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Tx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===Ex)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===Mx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===bx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Ax)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===wx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===Rx)return s===wn?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Cx||i===Nx||i===Dx)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(i===Cx)return s===wn?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===Nx)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Dx)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===Ox||i===Lx||i===Ix||i===Ux)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(i===Ox)return r.COMPRESSED_RED_RGTC1_EXT;if(i===Lx)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===Ix)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Ux)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===qu?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const lj=` -void main() { - - gl_Position = vec4( position, 1.0 ); - -}`,cj=` -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 uj{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new Cb(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new Vi({vertexShader:lj,fragmentShader:cj,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new oi(new uh(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class hj extends nr{constructor(e,t){super();const i=this;let a=null,r=1,s=null,o="local-floor",c=1,h=null,f=null,d=null,m=null,g=null,x=null;const T=typeof XRWebGLBinding<"u",y=new uj,v={},S=t.getContextAttributes();let E=null,b=null;const D=[],C=[],I=new de;let P=null;const O=new hi;O.viewport=new zt;const w=new hi;w.viewport=new zt;const B=[O,w],j=new w6;let ee=null,se=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ge){let Ae=D[ge];return Ae===void 0&&(Ae=new g_,D[ge]=Ae),Ae.getTargetRaySpace()},this.getControllerGrip=function(ge){let Ae=D[ge];return Ae===void 0&&(Ae=new g_,D[ge]=Ae),Ae.getGripSpace()},this.getHand=function(ge){let Ae=D[ge];return Ae===void 0&&(Ae=new g_,D[ge]=Ae),Ae.getHandSpace()};function re(ge){const Ae=C.indexOf(ge.inputSource);if(Ae===-1)return;const Ze=D[Ae];Ze!==void 0&&(Ze.update(ge.inputSource,ge.frame,h||s),Ze.dispatchEvent({type:ge.type,data:ge.inputSource}))}function W(){a.removeEventListener("select",re),a.removeEventListener("selectstart",re),a.removeEventListener("selectend",re),a.removeEventListener("squeeze",re),a.removeEventListener("squeezestart",re),a.removeEventListener("squeezeend",re),a.removeEventListener("end",W),a.removeEventListener("inputsourceschange",te);for(let ge=0;ge=0&&(C[ue]=null,D[ue].disconnect(Ze))}for(let Ae=0;Ae=C.length){C.push(Ze),ue=Mt;break}else if(C[Mt]===null){C[Mt]=Ze,ue=Mt;break}if(ue===-1)break}const it=D[ue];it&&it.connect(Ze)}}const K=new L,oe=new L;function ie(ge,Ae,Ze){K.setFromMatrixPosition(Ae.matrixWorld),oe.setFromMatrixPosition(Ze.matrixWorld);const ue=K.distanceTo(oe),it=Ae.projectionMatrix.elements,Mt=Ze.projectionMatrix.elements,ot=it[14]/(it[10]-1),Ke=it[14]/(it[10]+1),Te=(it[9]+1)/it[5],G=(it[9]-1)/it[5],be=(it[8]-1)/it[0],De=(Mt[8]+1)/Mt[0],Fe=ot*be,Be=ot*De,$e=ue/(-be+De),Je=$e*-be;if(Ae.matrixWorld.decompose(ge.position,ge.quaternion,ge.scale),ge.translateX(Je),ge.translateZ($e),ge.matrixWorld.compose(ge.position,ge.quaternion,ge.scale),ge.matrixWorldInverse.copy(ge.matrixWorld).invert(),it[10]===-1)ge.projectionMatrix.copy(Ae.projectionMatrix),ge.projectionMatrixInverse.copy(Ae.projectionMatrixInverse);else{const ct=ot+$e,k=Ke+$e,U=Fe-Je,ce=Be+(ue-Je),Ee=Te*Ke/k*ct,Le=G*Ke/k*ct;ge.projectionMatrix.makePerspective(U,ce,Ee,Le,ct,k),ge.projectionMatrixInverse.copy(ge.projectionMatrix).invert()}}function Ce(ge,Ae){Ae===null?ge.matrixWorld.copy(ge.matrix):ge.matrixWorld.multiplyMatrices(Ae.matrixWorld,ge.matrix),ge.matrixWorldInverse.copy(ge.matrixWorld).invert()}this.updateCamera=function(ge){if(a===null)return;let Ae=ge.near,Ze=ge.far;y.texture!==null&&(y.depthNear>0&&(Ae=y.depthNear),y.depthFar>0&&(Ze=y.depthFar)),j.near=w.near=O.near=Ae,j.far=w.far=O.far=Ze,(ee!==j.near||se!==j.far)&&(a.updateRenderState({depthNear:j.near,depthFar:j.far}),ee=j.near,se=j.far),j.layers.mask=ge.layers.mask|6,O.layers.mask=j.layers.mask&3,w.layers.mask=j.layers.mask&5;const ue=ge.parent,it=j.cameras;Ce(j,ue);for(let Mt=0;Mt0&&(y.alphaTest.value=v.alphaTest);const S=e.get(v),E=S.envMap,b=S.envMapRotation;E&&(y.envMap.value=E,ou.copy(b),ou.x*=-1,ou.y*=-1,ou.z*=-1,E.isCubeTexture&&E.isRenderTargetTexture===!1&&(ou.y*=-1,ou.z*=-1),y.envMapRotation.value.setFromMatrix4(fj.makeRotationFromEuler(ou)),y.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,y.reflectivity.value=v.reflectivity,y.ior.value=v.ior,y.refractionRatio.value=v.refractionRatio),v.lightMap&&(y.lightMap.value=v.lightMap,y.lightMapIntensity.value=v.lightMapIntensity,t(v.lightMap,y.lightMapTransform)),v.aoMap&&(y.aoMap.value=v.aoMap,y.aoMapIntensity.value=v.aoMapIntensity,t(v.aoMap,y.aoMapTransform))}function s(y,v){y.diffuse.value.copy(v.color),y.opacity.value=v.opacity,v.map&&(y.map.value=v.map,t(v.map,y.mapTransform))}function o(y,v){y.dashSize.value=v.dashSize,y.totalSize.value=v.dashSize+v.gapSize,y.scale.value=v.scale}function c(y,v,S,E){y.diffuse.value.copy(v.color),y.opacity.value=v.opacity,y.size.value=v.size*S,y.scale.value=E*.5,v.map&&(y.map.value=v.map,t(v.map,y.uvTransform)),v.alphaMap&&(y.alphaMap.value=v.alphaMap,t(v.alphaMap,y.alphaMapTransform)),v.alphaTest>0&&(y.alphaTest.value=v.alphaTest)}function h(y,v){y.diffuse.value.copy(v.color),y.opacity.value=v.opacity,y.rotation.value=v.rotation,v.map&&(y.map.value=v.map,t(v.map,y.mapTransform)),v.alphaMap&&(y.alphaMap.value=v.alphaMap,t(v.alphaMap,y.alphaMapTransform)),v.alphaTest>0&&(y.alphaTest.value=v.alphaTest)}function f(y,v){y.specular.value.copy(v.specular),y.shininess.value=Math.max(v.shininess,1e-4)}function d(y,v){v.gradientMap&&(y.gradientMap.value=v.gradientMap)}function m(y,v){y.metalness.value=v.metalness,v.metalnessMap&&(y.metalnessMap.value=v.metalnessMap,t(v.metalnessMap,y.metalnessMapTransform)),y.roughness.value=v.roughness,v.roughnessMap&&(y.roughnessMap.value=v.roughnessMap,t(v.roughnessMap,y.roughnessMapTransform)),v.envMap&&(y.envMapIntensity.value=v.envMapIntensity)}function g(y,v,S){y.ior.value=v.ior,v.sheen>0&&(y.sheenColor.value.copy(v.sheenColor).multiplyScalar(v.sheen),y.sheenRoughness.value=v.sheenRoughness,v.sheenColorMap&&(y.sheenColorMap.value=v.sheenColorMap,t(v.sheenColorMap,y.sheenColorMapTransform)),v.sheenRoughnessMap&&(y.sheenRoughnessMap.value=v.sheenRoughnessMap,t(v.sheenRoughnessMap,y.sheenRoughnessMapTransform))),v.clearcoat>0&&(y.clearcoat.value=v.clearcoat,y.clearcoatRoughness.value=v.clearcoatRoughness,v.clearcoatMap&&(y.clearcoatMap.value=v.clearcoatMap,t(v.clearcoatMap,y.clearcoatMapTransform)),v.clearcoatRoughnessMap&&(y.clearcoatRoughnessMap.value=v.clearcoatRoughnessMap,t(v.clearcoatRoughnessMap,y.clearcoatRoughnessMapTransform)),v.clearcoatNormalMap&&(y.clearcoatNormalMap.value=v.clearcoatNormalMap,t(v.clearcoatNormalMap,y.clearcoatNormalMapTransform),y.clearcoatNormalScale.value.copy(v.clearcoatNormalScale),v.side===Ui&&y.clearcoatNormalScale.value.negate())),v.dispersion>0&&(y.dispersion.value=v.dispersion),v.iridescence>0&&(y.iridescence.value=v.iridescence,y.iridescenceIOR.value=v.iridescenceIOR,y.iridescenceThicknessMinimum.value=v.iridescenceThicknessRange[0],y.iridescenceThicknessMaximum.value=v.iridescenceThicknessRange[1],v.iridescenceMap&&(y.iridescenceMap.value=v.iridescenceMap,t(v.iridescenceMap,y.iridescenceMapTransform)),v.iridescenceThicknessMap&&(y.iridescenceThicknessMap.value=v.iridescenceThicknessMap,t(v.iridescenceThicknessMap,y.iridescenceThicknessMapTransform))),v.transmission>0&&(y.transmission.value=v.transmission,y.transmissionSamplerMap.value=S.texture,y.transmissionSamplerSize.value.set(S.width,S.height),v.transmissionMap&&(y.transmissionMap.value=v.transmissionMap,t(v.transmissionMap,y.transmissionMapTransform)),y.thickness.value=v.thickness,v.thicknessMap&&(y.thicknessMap.value=v.thicknessMap,t(v.thicknessMap,y.thicknessMapTransform)),y.attenuationDistance.value=v.attenuationDistance,y.attenuationColor.value.copy(v.attenuationColor)),v.anisotropy>0&&(y.anisotropyVector.value.set(v.anisotropy*Math.cos(v.anisotropyRotation),v.anisotropy*Math.sin(v.anisotropyRotation)),v.anisotropyMap&&(y.anisotropyMap.value=v.anisotropyMap,t(v.anisotropyMap,y.anisotropyMapTransform))),y.specularIntensity.value=v.specularIntensity,y.specularColor.value.copy(v.specularColor),v.specularColorMap&&(y.specularColorMap.value=v.specularColorMap,t(v.specularColorMap,y.specularColorMapTransform)),v.specularIntensityMap&&(y.specularIntensityMap.value=v.specularIntensityMap,t(v.specularIntensityMap,y.specularIntensityMapTransform))}function x(y,v){v.matcap&&(y.matcap.value=v.matcap)}function T(y,v){const S=e.get(v).light;y.referencePosition.value.setFromMatrixPosition(S.matrixWorld),y.nearDistance.value=S.shadow.camera.near,y.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:a}}function pj(n,e,t,i){let a={},r={},s=[];const o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function c(S,E){const b=E.program;i.uniformBlockBinding(S,b)}function h(S,E){let b=a[S.id];b===void 0&&(x(S),b=f(S),a[S.id]=b,S.addEventListener("dispose",y));const D=E.program;i.updateUBOMapping(S,D);const C=e.render.frame;r[S.id]!==C&&(m(S),r[S.id]=C)}function f(S){const E=d();S.__bindingPointIndex=E;const b=n.createBuffer(),D=S.__size,C=S.usage;return n.bindBuffer(n.UNIFORM_BUFFER,b),n.bufferData(n.UNIFORM_BUFFER,D,C),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,E,b),b}function d(){for(let S=0;S0&&(b+=D-C),S.__size=b,S.__cache={},this}function T(S){const E={boundary:0,storage:0};return typeof S=="number"||typeof S=="boolean"?(E.boundary=4,E.storage=4):S.isVector2?(E.boundary=8,E.storage=8):S.isVector3||S.isColor?(E.boundary=16,E.storage=12):S.isVector4?(E.boundary=16,E.storage=16):S.isMatrix3?(E.boundary=48,E.storage=48):S.isMatrix4?(E.boundary=64,E.storage=64):S.isTexture?ut("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ut("WebGLRenderer: Unsupported uniform value type.",S),E}function y(S){const E=S.target;E.removeEventListener("dispose",y);const b=s.indexOf(E.__bindingPointIndex);s.splice(b,1),n.deleteBuffer(a[E.id]),delete a[E.id],delete r[E.id]}function v(){for(const S in a)n.deleteBuffer(a[S]);s=[],a={},r={}}return{bind:c,update:h,dispose:v}}const mj=new Uint16Array([11481,15204,11534,15171,11808,15015,12385,14843,12894,14716,13396,14600,13693,14483,13976,14366,14237,14171,14405,13961,14511,13770,14605,13598,14687,13444,14760,13305,14822,13066,14876,12857,14923,12675,14963,12517,14997,12379,15025,12230,15049,12023,15070,11843,15086,11687,15100,11551,15111,11433,15120,11330,15127,11217,15132,11060,15135,10922,15138,10801,15139,10695,15139,10600,13012,14923,13020,14917,13064,14886,13176,14800,13349,14666,13513,14526,13724,14398,13960,14230,14200,14020,14383,13827,14488,13651,14583,13491,14667,13348,14740,13132,14803,12908,14856,12713,14901,12542,14938,12394,14968,12241,14992,12017,15010,11822,15024,11654,15034,11507,15041,11380,15044,11269,15044,11081,15042,10913,15037,10764,15031,10635,15023,10520,15014,10419,15003,10330,13657,14676,13658,14673,13670,14660,13698,14622,13750,14547,13834,14442,13956,14317,14112,14093,14291,13889,14407,13704,14499,13538,14586,13389,14664,13201,14733,12966,14792,12758,14842,12577,14882,12418,14915,12272,14940,12033,14959,11826,14972,11646,14980,11490,14983,11355,14983,11212,14979,11008,14971,10830,14961,10675,14950,10540,14936,10420,14923,10315,14909,10204,14894,10041,14089,14460,14090,14459,14096,14452,14112,14431,14141,14388,14186,14305,14252,14130,14341,13941,14399,13756,14467,13585,14539,13430,14610,13272,14677,13026,14737,12808,14790,12617,14833,12449,14869,12303,14896,12065,14916,11845,14929,11655,14937,11490,14939,11347,14936,11184,14930,10970,14921,10783,14912,10621,14900,10480,14885,10356,14867,10247,14848,10062,14827,9894,14805,9745,14400,14208,14400,14206,14402,14198,14406,14174,14415,14122,14427,14035,14444,13913,14469,13767,14504,13613,14548,13463,14598,13324,14651,13082,14704,12858,14752,12658,14795,12483,14831,12330,14860,12106,14881,11875,14895,11675,14903,11501,14905,11351,14903,11178,14900,10953,14892,10757,14880,10589,14865,10442,14847,10313,14827,10162,14805,9965,14782,9792,14757,9642,14731,9507,14562,13883,14562,13883,14563,13877,14566,13862,14570,13830,14576,13773,14584,13689,14595,13582,14613,13461,14637,13336,14668,13120,14704,12897,14741,12695,14776,12516,14808,12358,14835,12150,14856,11910,14870,11701,14878,11519,14882,11361,14884,11187,14880,10951,14871,10748,14858,10572,14842,10418,14823,10286,14801,10099,14777,9897,14751,9722,14725,9567,14696,9430,14666,9309,14702,13604,14702,13604,14702,13600,14703,13591,14705,13570,14707,13533,14709,13477,14712,13400,14718,13305,14727,13106,14743,12907,14762,12716,14784,12539,14807,12380,14827,12190,14844,11943,14855,11727,14863,11539,14870,11376,14871,11204,14868,10960,14858,10748,14845,10565,14829,10406,14809,10269,14786,10058,14761,9852,14734,9671,14705,9512,14674,9374,14641,9253,14608,9076,14821,13366,14821,13365,14821,13364,14821,13358,14821,13344,14821,13320,14819,13252,14817,13145,14815,13011,14814,12858,14817,12698,14823,12539,14832,12389,14841,12214,14850,11968,14856,11750,14861,11558,14866,11390,14867,11226,14862,10972,14853,10754,14840,10565,14823,10401,14803,10259,14780,10032,14754,9820,14725,9635,14694,9473,14661,9333,14627,9203,14593,8988,14557,8798,14923,13014,14922,13014,14922,13012,14922,13004,14920,12987,14919,12957,14915,12907,14909,12834,14902,12738,14894,12623,14888,12498,14883,12370,14880,12203,14878,11970,14875,11759,14873,11569,14874,11401,14872,11243,14865,10986,14855,10762,14842,10568,14825,10401,14804,10255,14781,10017,14754,9799,14725,9611,14692,9445,14658,9301,14623,9139,14587,8920,14548,8729,14509,8562,15008,12672,15008,12672,15008,12671,15007,12667,15005,12656,15001,12637,14997,12605,14989,12556,14978,12490,14966,12407,14953,12313,14940,12136,14927,11934,14914,11742,14903,11563,14896,11401,14889,11247,14879,10992,14866,10767,14851,10570,14833,10400,14812,10252,14789,10007,14761,9784,14731,9592,14698,9424,14663,9279,14627,9088,14588,8868,14548,8676,14508,8508,14467,8360,15080,12386,15080,12386,15079,12385,15078,12383,15076,12378,15072,12367,15066,12347,15057,12315,15045,12253,15030,12138,15012,11998,14993,11845,14972,11685,14951,11530,14935,11383,14920,11228,14904,10981,14887,10762,14870,10567,14850,10397,14827,10248,14803,9997,14774,9771,14743,9578,14710,9407,14674,9259,14637,9048,14596,8826,14555,8632,14514,8464,14471,8317,14427,8182,15139,12008,15139,12008,15138,12008,15137,12007,15135,12003,15130,11990,15124,11969,15115,11929,15102,11872,15086,11794,15064,11693,15041,11581,15013,11459,14987,11336,14966,11170,14944,10944,14921,10738,14898,10552,14875,10387,14850,10239,14824,9983,14794,9758,14762,9563,14728,9392,14692,9244,14653,9014,14611,8791,14569,8597,14526,8427,14481,8281,14436,8110,14391,7885,15188,11617,15188,11617,15187,11617,15186,11618,15183,11617,15179,11612,15173,11601,15163,11581,15150,11546,15133,11495,15110,11427,15083,11346,15051,11246,15024,11057,14996,10868,14967,10687,14938,10517,14911,10362,14882,10206,14853,9956,14821,9737,14787,9543,14752,9375,14715,9228,14675,8980,14632,8760,14589,8565,14544,8395,14498,8248,14451,8049,14404,7824,14357,7630,15228,11298,15228,11298,15227,11299,15226,11301,15223,11303,15219,11302,15213,11299,15204,11290,15191,11271,15174,11217,15150,11129,15119,11015,15087,10886,15057,10744,15024,10599,14990,10455,14957,10318,14924,10143,14891,9911,14856,9701,14820,9516,14782,9352,14744,9200,14703,8946,14659,8725,14615,8533,14568,8366,14521,8220,14472,7992,14423,7770,14374,7578,14315,7408,15260,10819,15260,10819,15259,10822,15258,10826,15256,10832,15251,10836,15246,10841,15237,10838,15225,10821,15207,10788,15183,10734,15151,10660,15120,10571,15087,10469,15049,10359,15012,10249,14974,10041,14937,9837,14900,9647,14860,9475,14820,9320,14779,9147,14736,8902,14691,8688,14646,8499,14598,8335,14549,8189,14499,7940,14448,7720,14397,7529,14347,7363,14256,7218,15285,10410,15285,10411,15285,10413,15284,10418,15282,10425,15278,10434,15272,10442,15264,10449,15252,10445,15235,10433,15210,10403,15179,10358,15149,10301,15113,10218,15073,10059,15033,9894,14991,9726,14951,9565,14909,9413,14865,9273,14822,9073,14777,8845,14730,8641,14682,8459,14633,8300,14583,8129,14531,7883,14479,7670,14426,7482,14373,7321,14305,7176,14201,6939,15305,9939,15305,9940,15305,9945,15304,9955,15302,9967,15298,9989,15293,10010,15286,10033,15274,10044,15258,10045,15233,10022,15205,9975,15174,9903,15136,9808,15095,9697,15053,9578,15009,9451,14965,9327,14918,9198,14871,8973,14825,8766,14775,8579,14725,8408,14675,8259,14622,8058,14569,7821,14515,7615,14460,7435,14405,7276,14350,7108,14256,6866,14149,6653,15321,9444,15321,9445,15321,9448,15320,9458,15317,9470,15314,9490,15310,9515,15302,9540,15292,9562,15276,9579,15251,9577,15226,9559,15195,9519,15156,9463,15116,9389,15071,9304,15025,9208,14978,9023,14927,8838,14878,8661,14827,8496,14774,8344,14722,8206,14667,7973,14612,7749,14556,7555,14499,7382,14443,7229,14385,7025,14322,6791,14210,6588,14100,6409,15333,8920,15333,8921,15332,8927,15332,8943,15329,8965,15326,9002,15322,9048,15316,9106,15307,9162,15291,9204,15267,9221,15244,9221,15212,9196,15175,9134,15133,9043,15088,8930,15040,8801,14990,8665,14938,8526,14886,8391,14830,8261,14775,8087,14719,7866,14661,7664,14603,7482,14544,7322,14485,7178,14426,6936,14367,6713,14281,6517,14166,6348,14054,6198,15341,8360,15341,8361,15341,8366,15341,8379,15339,8399,15336,8431,15332,8473,15326,8527,15318,8585,15302,8632,15281,8670,15258,8690,15227,8690,15191,8664,15149,8612,15104,8543,15055,8456,15001,8360,14948,8259,14892,8122,14834,7923,14776,7734,14716,7558,14656,7397,14595,7250,14534,7070,14472,6835,14410,6628,14350,6443,14243,6283,14125,6135,14010,5889,15348,7715,15348,7717,15348,7725,15347,7745,15345,7780,15343,7836,15339,7905,15334,8e3,15326,8103,15310,8193,15293,8239,15270,8270,15240,8287,15204,8283,15163,8260,15118,8223,15067,8143,15014,8014,14958,7873,14899,7723,14839,7573,14778,7430,14715,7293,14652,7164,14588,6931,14524,6720,14460,6531,14396,6362,14330,6210,14207,6015,14086,5781,13969,5576,15352,7114,15352,7116,15352,7128,15352,7159,15350,7195,15348,7237,15345,7299,15340,7374,15332,7457,15317,7544,15301,7633,15280,7703,15251,7754,15216,7775,15176,7767,15131,7733,15079,7670,15026,7588,14967,7492,14906,7387,14844,7278,14779,7171,14714,6965,14648,6770,14581,6587,14515,6420,14448,6269,14382,6123,14299,5881,14172,5665,14049,5477,13929,5310,15355,6329,15355,6330,15355,6339,15355,6362,15353,6410,15351,6472,15349,6572,15344,6688,15337,6835,15323,6985,15309,7142,15287,7220,15260,7277,15226,7310,15188,7326,15142,7318,15090,7285,15036,7239,14976,7177,14914,7045,14849,6892,14782,6736,14714,6581,14645,6433,14576,6293,14506,6164,14438,5946,14369,5733,14270,5540,14140,5369,14014,5216,13892,5043,15357,5483,15357,5484,15357,5496,15357,5528,15356,5597,15354,5692,15351,5835,15347,6011,15339,6195,15328,6317,15314,6446,15293,6566,15268,6668,15235,6746,15197,6796,15152,6811,15101,6790,15046,6748,14985,6673,14921,6583,14854,6479,14785,6371,14714,6259,14643,6149,14571,5946,14499,5750,14428,5567,14358,5401,14242,5250,14109,5111,13980,4870,13856,4657,15359,4555,15359,4557,15358,4573,15358,4633,15357,4715,15355,4841,15353,5061,15349,5216,15342,5391,15331,5577,15318,5770,15299,5967,15274,6150,15243,6223,15206,6280,15161,6310,15111,6317,15055,6300,14994,6262,14928,6208,14860,6141,14788,5994,14715,5838,14641,5684,14566,5529,14492,5384,14418,5247,14346,5121,14216,4892,14079,4682,13948,4496,13822,4330,15359,3498,15359,3501,15359,3520,15359,3598,15358,3719,15356,3860,15355,4137,15351,4305,15344,4563,15334,4809,15321,5116,15303,5273,15280,5418,15250,5547,15214,5653,15170,5722,15120,5761,15064,5763,15002,5733,14935,5673,14865,5597,14792,5504,14716,5400,14640,5294,14563,5185,14486,5041,14410,4841,14335,4655,14191,4482,14051,4325,13918,4183,13790,4012,15360,2282,15360,2285,15360,2306,15360,2401,15359,2547,15357,2748,15355,3103,15352,3349,15345,3675,15336,4020,15324,4272,15307,4496,15285,4716,15255,4908,15220,5086,15178,5170,15128,5214,15072,5234,15010,5231,14943,5206,14871,5166,14796,5102,14718,4971,14639,4833,14559,4687,14480,4541,14402,4401,14315,4268,14167,4142,14025,3958,13888,3747,13759,3556,15360,923,15360,925,15360,946,15360,1052,15359,1214,15357,1494,15356,1892,15352,2274,15346,2663,15338,3099,15326,3393,15309,3679,15288,3980,15260,4183,15226,4325,15185,4437,15136,4517,15080,4570,15018,4591,14950,4581,14877,4545,14800,4485,14720,4411,14638,4325,14556,4231,14475,4136,14395,3988,14297,3803,14145,3628,13999,3465,13861,3314,13729,3177,15360,263,15360,264,15360,272,15360,325,15359,407,15358,548,15356,780,15352,1144,15347,1580,15339,2099,15328,2425,15312,2795,15292,3133,15264,3329,15232,3517,15191,3689,15143,3819,15088,3923,15025,3978,14956,3999,14882,3979,14804,3931,14722,3855,14639,3756,14554,3645,14470,3529,14388,3409,14279,3289,14124,3173,13975,3055,13834,2848,13701,2658,15360,49,15360,49,15360,52,15360,75,15359,111,15358,201,15356,283,15353,519,15348,726,15340,1045,15329,1415,15314,1795,15295,2173,15269,2410,15237,2649,15197,2866,15150,3054,15095,3140,15032,3196,14963,3228,14888,3236,14808,3224,14725,3191,14639,3146,14553,3088,14466,2976,14382,2836,14262,2692,14103,2549,13952,2409,13808,2278,13674,2154,15360,4,15360,4,15360,4,15360,13,15359,33,15358,59,15357,112,15353,199,15348,302,15341,456,15331,628,15316,827,15297,1082,15272,1332,15241,1601,15202,1851,15156,2069,15101,2172,15039,2256,14970,2314,14894,2348,14813,2358,14728,2344,14640,2311,14551,2263,14463,2203,14376,2133,14247,2059,14084,1915,13930,1761,13784,1609,13648,1464,15360,0,15360,0,15360,0,15360,3,15359,18,15358,26,15357,53,15354,80,15348,97,15341,165,15332,238,15318,326,15299,427,15275,529,15245,654,15207,771,15161,885,15108,994,15046,1089,14976,1170,14900,1229,14817,1266,14731,1284,14641,1282,14550,1260,14460,1223,14370,1174,14232,1116,14066,1050,13909,981,13761,910,13623,839]);let Io=null;function gj(){return Io===null&&(Io=new $a(mj,32,32,ko,Xn),Io.minFilter=Ht,Io.magFilter=Ht,Io.wrapS=Pi,Io.wrapT=Pi,Io.generateMipmaps=!1,Io.needsUpdate=!0),Io}class $b{constructor(e={}){const{canvas:t=PU(),context:i=null,depth:a=!0,stencil:r=!1,alpha:s=!1,antialias:o=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:h=!1,powerPreference:f="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:m=!1}=e;this.isWebGLRenderer=!0;let g;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=i.getContextAttributes().alpha}else g=s;const x=new Set([P1,U1,I0]),T=new Set([zi,Ds,Yu,qu,L1,I1]),y=new Uint32Array(4),v=new Int32Array(4);let S=null,E=null;const b=[],D=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=is,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const C=this;let I=!1;this._outputColorSpace=En;let P=0,O=0,w=null,B=-1,j=null;const ee=new zt,se=new zt;let re=null;const W=new je(0);let te=0,K=t.width,oe=t.height,ie=1,Ce=null,Xe=null;const nt=new zt(0,0,K,oe),tt=new zt(0,0,K,oe);let gt=!1;const ge=new Yd;let Ae=!1,Ze=!1;const ue=new ke,it=new L,Mt=new zt,ot={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Ke=!1;function Te(){return w===null?ie:1}let G=i;function be(N,V){return t.getContext(N,V)}try{const N={alpha:!0,depth:a,stencil:r,antialias:o,premultipliedAlpha:c,preserveDrawingBuffer:h,powerPreference:f,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Cs}`),t.addEventListener("webglcontextlost",Ge,!1),t.addEventListener("webglcontextrestored",we,!1),t.addEventListener("webglcontextcreationerror",rt,!1),G===null){const V="webgl2";if(G=be(V,N),G===null)throw be(V)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(N){throw N("WebGLRenderer: "+N.message),N}let De,Fe,Be,$e,Je,ct,k,U,ce,Ee,Le,ye,vt,qe,_t,pt,Ie,He,ht,Q,pe,Oe,q,Ve;function me(){De=new AY(G),De.init(),Oe=new F6(G,De),Fe=new vY(G,De,e,Oe),Be=new sj(G,De),Fe.reversedDepthBuffer&&m&&Be.buffers.depth.setReversed(!0),$e=new CY(G),Je=new qq,ct=new oj(G,De,Be,Je,Fe,Oe,$e),k=new xY(C),U=new bY(C),ce=new Lk(G),q=new mY(G,ce),Ee=new wY(G,ce,$e,q),Le=new DY(G,Ee,ce,$e),ht=new NY(G,Fe,ct),pt=new _Y(Je),ye=new Yq(C,k,U,De,Fe,q,pt),vt=new dj(C,Je),qe=new Zq,_t=new tj(De),He=new pY(C,k,U,Be,Le,g,c),Ie=new aj(C,Le,Fe),Ve=new pj(G,$e,Fe,Be),Q=new gY(G,De,$e),pe=new RY(G,De,$e),$e.programs=ye.programs,C.capabilities=Fe,C.extensions=De,C.properties=Je,C.renderLists=qe,C.shadowMap=Ie,C.state=Be,C.info=$e}me();const We=new hj(C,G);this.xr=We,this.getContext=function(){return G},this.getContextAttributes=function(){return G.getContextAttributes()},this.forceContextLoss=function(){const N=De.get("WEBGL_lose_context");N&&N.loseContext()},this.forceContextRestore=function(){const N=De.get("WEBGL_lose_context");N&&N.restoreContext()},this.getPixelRatio=function(){return ie},this.setPixelRatio=function(N){N!==void 0&&(ie=N,this.setSize(K,oe,!1))},this.getSize=function(N){return N.set(K,oe)},this.setSize=function(N,V,Z=!0){if(We.isPresenting){ut("WebGLRenderer: Can't change size while VR device is presenting.");return}K=N,oe=V,t.width=Math.floor(N*ie),t.height=Math.floor(V*ie),Z===!0&&(t.style.width=N+"px",t.style.height=V+"px"),this.setViewport(0,0,N,V)},this.getDrawingBufferSize=function(N){return N.set(K*ie,oe*ie).floor()},this.setDrawingBufferSize=function(N,V,Z){K=N,oe=V,ie=Z,t.width=Math.floor(N*Z),t.height=Math.floor(V*Z),this.setViewport(0,0,N,V)},this.getCurrentViewport=function(N){return N.copy(ee)},this.getViewport=function(N){return N.copy(nt)},this.setViewport=function(N,V,Z,H){N.isVector4?nt.set(N.x,N.y,N.z,N.w):nt.set(N,V,Z,H),Be.viewport(ee.copy(nt).multiplyScalar(ie).round())},this.getScissor=function(N){return N.copy(tt)},this.setScissor=function(N,V,Z,H){N.isVector4?tt.set(N.x,N.y,N.z,N.w):tt.set(N,V,Z,H),Be.scissor(se.copy(tt).multiplyScalar(ie).round())},this.getScissorTest=function(){return gt},this.setScissorTest=function(N){Be.setScissorTest(gt=N)},this.setOpaqueSort=function(N){Ce=N},this.setTransparentSort=function(N){Xe=N},this.getClearColor=function(N){return N.copy(He.getClearColor())},this.setClearColor=function(){He.setClearColor(...arguments)},this.getClearAlpha=function(){return He.getClearAlpha()},this.setClearAlpha=function(){He.setClearAlpha(...arguments)},this.clear=function(N=!0,V=!0,Z=!0){let H=0;if(N){let X=!1;if(w!==null){const ne=w.texture.format;X=x.has(ne)}if(X){const ne=w.texture.type,ae=T.has(ne),fe=He.getClearColor(),_e=He.getClearAlpha(),Se=fe.r,Re=fe.g,Pe=fe.b;ae?(y[0]=Se,y[1]=Re,y[2]=Pe,y[3]=_e,G.clearBufferuiv(G.COLOR,0,y)):(v[0]=Se,v[1]=Re,v[2]=Pe,v[3]=_e,G.clearBufferiv(G.COLOR,0,v))}else H|=G.COLOR_BUFFER_BIT}V&&(H|=G.DEPTH_BUFFER_BIT),Z&&(H|=G.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),G.clear(H)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Ge,!1),t.removeEventListener("webglcontextrestored",we,!1),t.removeEventListener("webglcontextcreationerror",rt,!1),He.dispose(),qe.dispose(),_t.dispose(),Je.dispose(),k.dispose(),U.dispose(),Le.dispose(),q.dispose(),Ve.dispose(),ye.dispose(),We.dispose(),We.removeEventListener("sessionstart",Is),We.removeEventListener("sessionend",Us),bi.stop()};function Ge(N){N.preventDefault(),f0("WebGLRenderer: Context Lost."),I=!0}function we(){f0("WebGLRenderer: Context Restored."),I=!1;const N=$e.autoReset,V=Ie.enabled,Z=Ie.autoUpdate,H=Ie.needsUpdate,X=Ie.type;me(),$e.autoReset=N,Ie.enabled=V,Ie.autoUpdate=Z,Ie.needsUpdate=H,Ie.type=X}function rt(N){Bt("WebGLRenderer: A WebGL context could not be created. Reason: ",N.statusMessage)}function yt(N){const V=N.target;V.removeEventListener("dispose",yt),Gt(V)}function Gt(N){Vt(N),Je.remove(N)}function Vt(N){const V=Je.get(N).programs;V!==void 0&&(V.forEach(function(Z){ye.releaseProgram(Z)}),N.isShaderMaterial&&ye.releaseShaderCache(N))}this.renderBufferDirect=function(N,V,Z,H,X,ne){V===null&&(V=ot);const ae=X.isMesh&&X.matrixWorld.determinant()<0,fe=ho(N,V,Z,H,X);Be.setMaterial(H,ae);let _e=Z.index,Se=1;if(H.wireframe===!0){if(_e=Ee.getWireframeAttribute(Z),_e===void 0)return;Se=2}const Re=Z.drawRange,Pe=Z.attributes.position;let ze=Re.start*Se,Ye=(Re.start+Re.count)*Se;ne!==null&&(ze=Math.max(ze,ne.start*Se),Ye=Math.min(Ye,(ne.start+ne.count)*Se)),_e!==null?(ze=Math.max(ze,0),Ye=Math.min(Ye,_e.count)):Pe!=null&&(ze=Math.max(ze,0),Ye=Math.min(Ye,Pe.count));const lt=Ye-ze;if(lt<0||lt===1/0)return;q.setup(X,H,fe,Z,_e);let Tt,bt=Q;if(_e!==null&&(Tt=ce.get(_e),bt=pe,bt.setIndex(Tt)),X.isMesh)H.wireframe===!0?(Be.setLineWidth(H.wireframeLinewidth*Te()),bt.setMode(G.LINES)):bt.setMode(G.TRIANGLES);else if(X.isLine){let ft=H.linewidth;ft===void 0&&(ft=1),Be.setLineWidth(ft*Te()),X.isLineSegments?bt.setMode(G.LINES):X.isLineLoop?bt.setMode(G.LINE_LOOP):bt.setMode(G.LINE_STRIP)}else X.isPoints?bt.setMode(G.POINTS):X.isSprite&&bt.setMode(G.TRIANGLES);if(X.isBatchedMesh)if(X._multiDrawInstances!==null)Md("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),bt.renderMultiDrawInstances(X._multiDrawStarts,X._multiDrawCounts,X._multiDrawCount,X._multiDrawInstances);else if(De.get("WEBGL_multi_draw"))bt.renderMultiDraw(X._multiDrawStarts,X._multiDrawCounts,X._multiDrawCount);else{const ft=X._multiDrawStarts,At=X._multiDrawCounts,st=X._multiDrawCount,Kt=_e?ce.get(_e).bytesPerElement:1,On=Je.get(H).currentProgram.getUniforms();for(let Yt=0;Yt{function ne(){if(H.forEach(function(ae){Je.get(ae).currentProgram.isReady()&&H.delete(ae)}),H.size===0){X(N);return}setTimeout(ne,10)}De.get("KHR_parallel_shader_compile")!==null?ne():setTimeout(ne,10)})};let ci=null;function uo(N){ci&&ci(N)}function Is(){bi.stop()}function Us(){bi.start()}const bi=new U6;bi.setAnimationLoop(uo),typeof self<"u"&&bi.setContext(self),this.setAnimationLoop=function(N){ci=N,We.setAnimationLoop(N),N===null?bi.stop():bi.start()},We.addEventListener("sessionstart",Is),We.addEventListener("sessionend",Us),this.render=function(N,V){if(V!==void 0&&V.isCamera!==!0){Bt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(I===!0)return;if(N.matrixWorldAutoUpdate===!0&&N.updateMatrixWorld(),V.parent===null&&V.matrixWorldAutoUpdate===!0&&V.updateMatrixWorld(),We.enabled===!0&&We.isPresenting===!0&&(We.cameraAutoUpdate===!0&&We.updateCamera(V),V=We.getCamera()),N.isScene===!0&&N.onBeforeRender(C,N,V,w),E=_t.get(N,D.length),E.init(V),D.push(E),ue.multiplyMatrices(V.projectionMatrix,V.matrixWorldInverse),ge.setFromProjectionMatrix(ue,br,V.reversedDepth),Ze=this.localClippingEnabled,Ae=pt.init(this.clippingPlanes,Ze),S=qe.get(N,b.length),S.init(),b.push(S),We.enabled===!0&&We.isPresenting===!0){const ne=C.xr.getDepthSensingMesh();ne!==null&&Ps(ne,V,-1/0,C.sortObjects)}Ps(N,V,0,C.sortObjects),S.finish(),C.sortObjects===!0&&S.sort(Ce,Xe),Ke=We.enabled===!1||We.isPresenting===!1||We.hasDepthSensing()===!1,Ke&&He.addToRenderList(S,N),this.info.render.frame++,Ae===!0&&pt.beginShadows();const Z=E.state.shadowsArray;Ie.render(Z,N,V),Ae===!0&&pt.endShadows(),this.info.autoReset===!0&&this.info.reset();const H=S.opaque,X=S.transmissive;if(E.setupLights(),V.isArrayCamera){const ne=V.cameras;if(X.length>0)for(let ae=0,fe=ne.length;ae0&&Xi(H,X,N,V),Ke&&He.render(N),fa(S,N,V);w!==null&&O===0&&(ct.updateMultisampleRenderTarget(w),ct.updateRenderTargetMipmap(w)),N.isScene===!0&&N.onAfterRender(C,N,V),q.resetDefaultState(),B=-1,j=null,D.pop(),D.length>0?(E=D[D.length-1],Ae===!0&&pt.setGlobalState(C.clippingPlanes,E.state.camera)):E=null,b.pop(),b.length>0?S=b[b.length-1]:S=null};function Ps(N,V,Z,H){if(N.visible===!1)return;if(N.layers.test(V.layers)){if(N.isGroup)Z=N.renderOrder;else if(N.isLOD)N.autoUpdate===!0&&N.update(V);else if(N.isLight)E.pushLight(N),N.castShadow&&E.pushShadow(N);else if(N.isSprite){if(!N.frustumCulled||ge.intersectsSprite(N)){H&&Mt.setFromMatrixPosition(N.matrixWorld).applyMatrix4(ue);const ae=Le.update(N),fe=N.material;fe.visible&&S.push(N,ae,fe,Z,Mt.z,null)}}else if((N.isMesh||N.isLine||N.isPoints)&&(!N.frustumCulled||ge.intersectsObject(N))){const ae=Le.update(N),fe=N.material;if(H&&(N.boundingSphere!==void 0?(N.boundingSphere===null&&N.computeBoundingSphere(),Mt.copy(N.boundingSphere.center)):(ae.boundingSphere===null&&ae.computeBoundingSphere(),Mt.copy(ae.boundingSphere.center)),Mt.applyMatrix4(N.matrixWorld).applyMatrix4(ue)),Array.isArray(fe)){const _e=ae.groups;for(let Se=0,Re=_e.length;Se0&&Fa(X,V,Z),ne.length>0&&Fa(ne,V,Z),ae.length>0&&Fa(ae,V,Z),Be.buffers.depth.setTest(!0),Be.buffers.depth.setMask(!0),Be.buffers.color.setMask(!0),Be.setPolygonOffset(!1)}function Xi(N,V,Z,H){if((Z.isScene===!0?Z.overrideMaterial:null)!==null)return;E.state.transmissionRenderTarget[H.id]===void 0&&(E.state.transmissionRenderTarget[H.id]=new xi(1,1,{generateMipmaps:!0,type:De.has("EXT_color_buffer_half_float")||De.has("EXT_color_buffer_float")?Xn:zi,minFilter:Mr,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:rn.workingColorSpace}));const ne=E.state.transmissionRenderTarget[H.id],ae=H.viewport||ee;ne.setSize(ae.z*C.transmissionResolutionScale,ae.w*C.transmissionResolutionScale);const fe=C.getRenderTarget(),_e=C.getActiveCubeFace(),Se=C.getActiveMipmapLevel();C.setRenderTarget(ne),C.getClearColor(W),te=C.getClearAlpha(),te<1&&C.setClearColor(16777215,.5),C.clear(),Ke&&He.render(Z);const Re=C.toneMapping;C.toneMapping=is;const Pe=H.viewport;if(H.viewport!==void 0&&(H.viewport=void 0),E.setupLightsView(H),Ae===!0&&pt.setGlobalState(C.clippingPlanes,H),Fa(N,Z,H),ct.updateMultisampleRenderTarget(ne),ct.updateRenderTargetMipmap(ne),De.has("WEBGL_multisampled_render_to_texture")===!1){let ze=!1;for(let Ye=0,lt=V.length;Ye0),Pe=!!Z.morphAttributes.position,ze=!!Z.morphAttributes.normal,Ye=!!Z.morphAttributes.color;let lt=is;H.toneMapped&&(w===null||w.isXRRenderTarget===!0)&&(lt=C.toneMapping);const Tt=Z.morphAttributes.position||Z.morphAttributes.normal||Z.morphAttributes.color,bt=Tt!==void 0?Tt.length:0,ft=Je.get(H),At=E.state.lights;if(Ae===!0&&(Ze===!0||N!==j)){const Mn=N===j&&H.id===B;pt.setState(H,N,Mn)}let st=!1;H.version===ft.__version?(ft.needsLights&&ft.lightsStateVersion!==At.state.version||ft.outputColorSpace!==fe||X.isBatchedMesh&&ft.batching===!1||!X.isBatchedMesh&&ft.batching===!0||X.isBatchedMesh&&ft.batchingColor===!0&&X.colorTexture===null||X.isBatchedMesh&&ft.batchingColor===!1&&X.colorTexture!==null||X.isInstancedMesh&&ft.instancing===!1||!X.isInstancedMesh&&ft.instancing===!0||X.isSkinnedMesh&&ft.skinning===!1||!X.isSkinnedMesh&&ft.skinning===!0||X.isInstancedMesh&&ft.instancingColor===!0&&X.instanceColor===null||X.isInstancedMesh&&ft.instancingColor===!1&&X.instanceColor!==null||X.isInstancedMesh&&ft.instancingMorph===!0&&X.morphTexture===null||X.isInstancedMesh&&ft.instancingMorph===!1&&X.morphTexture!==null||ft.envMap!==_e||H.fog===!0&&ft.fog!==ne||ft.numClippingPlanes!==void 0&&(ft.numClippingPlanes!==pt.numPlanes||ft.numIntersection!==pt.numIntersection)||ft.vertexAlphas!==Se||ft.vertexTangents!==Re||ft.morphTargets!==Pe||ft.morphNormals!==ze||ft.morphColors!==Ye||ft.toneMapping!==lt||ft.morphTargetsCount!==bt)&&(st=!0):(st=!0,ft.__version=H.version);let Kt=ft.currentProgram;st===!0&&(Kt=Lr(H,V,X));let On=!1,Yt=!1,kt=!1;const Nt=Kt.getUniforms(),Bn=ft.uniforms;if(Be.useProgram(Kt.program)&&(On=!0,Yt=!0,kt=!0),H.id!==B&&(B=H.id,Yt=!0),On||j!==N){Be.buffers.depth.getReversed()&&N.reversedDepth!==!0&&(N._reversedDepth=!0,N.updateProjectionMatrix()),Nt.setValue(G,"projectionMatrix",N.projectionMatrix),Nt.setValue(G,"viewMatrix",N.matrixWorldInverse);const Gn=Nt.map.cameraPosition;Gn!==void 0&&Gn.setValue(G,it.setFromMatrixPosition(N.matrixWorld)),Fe.logarithmicDepthBuffer&&Nt.setValue(G,"logDepthBufFC",2/(Math.log(N.far+1)/Math.LN2)),(H.isMeshPhongMaterial||H.isMeshToonMaterial||H.isMeshLambertMaterial||H.isMeshBasicMaterial||H.isMeshStandardMaterial||H.isShaderMaterial)&&Nt.setValue(G,"isOrthographic",N.isOrthographicCamera===!0),j!==N&&(j=N,Yt=!0,kt=!0)}if(X.isSkinnedMesh){Nt.setOptional(G,X,"bindMatrix"),Nt.setOptional(G,X,"bindMatrixInverse");const Mn=X.skeleton;Mn&&(Mn.boneTexture===null&&Mn.computeBoneTexture(),Nt.setValue(G,"boneTexture",Mn.boneTexture,ct))}X.isBatchedMesh&&(Nt.setOptional(G,X,"batchingTexture"),Nt.setValue(G,"batchingTexture",X._matricesTexture,ct),Nt.setOptional(G,X,"batchingIdTexture"),Nt.setValue(G,"batchingIdTexture",X._indirectTexture,ct),Nt.setOptional(G,X,"batchingColorTexture"),X._colorsTexture!==null&&Nt.setValue(G,"batchingColorTexture",X._colorsTexture,ct));const Ai=Z.morphAttributes;if((Ai.position!==void 0||Ai.normal!==void 0||Ai.color!==void 0)&&ht.update(X,Z,Kt),(Yt||ft.receiveShadow!==X.receiveShadow)&&(ft.receiveShadow=X.receiveShadow,Nt.setValue(G,"receiveShadow",X.receiveShadow)),H.isMeshGouraudMaterial&&H.envMap!==null&&(Bn.envMap.value=_e,Bn.flipEnvMap.value=_e.isCubeTexture&&_e.isRenderTargetTexture===!1?-1:1),H.isMeshStandardMaterial&&H.envMap===null&&V.environment!==null&&(Bn.envMapIntensity.value=V.environmentIntensity),Bn.dfgLUT!==void 0&&(Bn.dfgLUT.value=gj()),Yt&&(Nt.setValue(G,"toneMappingExposure",C.toneMappingExposure),ft.needsLights&&sr(Bn,kt),ne&&H.fog===!0&&vt.refreshFogUniforms(Bn,ne),vt.refreshMaterialUniforms(Bn,H,ie,oe,E.state.transmissionRenderTarget[N.id]),v_.upload(G,zs(ft),Bn,ct)),H.isShaderMaterial&&H.uniformsNeedUpdate===!0&&(v_.upload(G,zs(ft),Bn,ct),H.uniformsNeedUpdate=!1),H.isSpriteMaterial&&Nt.setValue(G,"center",X.center),Nt.setValue(G,"modelViewMatrix",X.modelViewMatrix),Nt.setValue(G,"normalMatrix",X.normalMatrix),Nt.setValue(G,"modelMatrix",X.matrixWorld),H.isShaderMaterial||H.isRawShaderMaterial){const Mn=H.uniformsGroups;for(let Gn=0,_h=Mn.length;Gn<_h;Gn++){const Ir=Mn[Gn];Ve.update(Ir,Kt),Ve.bind(Ir,Kt)}}return Kt}function sr(N,V){N.ambientLightColor.needsUpdate=V,N.lightProbe.needsUpdate=V,N.directionalLights.needsUpdate=V,N.directionalLightShadows.needsUpdate=V,N.pointLights.needsUpdate=V,N.pointLightShadows.needsUpdate=V,N.spotLights.needsUpdate=V,N.spotLightShadows.needsUpdate=V,N.rectAreaLights.needsUpdate=V,N.hemisphereLights.needsUpdate=V}function da(N){return N.isMeshLambertMaterial||N.isMeshToonMaterial||N.isMeshPhongMaterial||N.isMeshStandardMaterial||N.isShadowMaterial||N.isShaderMaterial&&N.lights===!0}this.getActiveCubeFace=function(){return P},this.getActiveMipmapLevel=function(){return O},this.getRenderTarget=function(){return w},this.setRenderTargetTextures=function(N,V,Z){const H=Je.get(N);H.__autoAllocateDepthBuffer=N.resolveDepthBuffer===!1,H.__autoAllocateDepthBuffer===!1&&(H.__useRenderToTexture=!1),Je.get(N.texture).__webglTexture=V,Je.get(N.depthTexture).__webglTexture=H.__autoAllocateDepthBuffer?void 0:Z,H.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(N,V){const Z=Je.get(N);Z.__webglFramebuffer=V,Z.__useDefaultFramebuffer=V===void 0};const R=G.createFramebuffer();this.setRenderTarget=function(N,V=0,Z=0){w=N,P=V,O=Z;let H=!0,X=null,ne=!1,ae=!1;if(N){const _e=Je.get(N);if(_e.__useDefaultFramebuffer!==void 0)Be.bindFramebuffer(G.FRAMEBUFFER,null),H=!1;else if(_e.__webglFramebuffer===void 0)ct.setupRenderTarget(N);else if(_e.__hasExternalTextures)ct.rebindTextures(N,Je.get(N.texture).__webglTexture,Je.get(N.depthTexture).__webglTexture);else if(N.depthBuffer){const Pe=N.depthTexture;if(_e.__boundDepthTexture!==Pe){if(Pe!==null&&Je.has(Pe)&&(N.width!==Pe.image.width||N.height!==Pe.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");ct.setupDepthRenderbuffer(N)}}const Se=N.texture;(Se.isData3DTexture||Se.isDataArrayTexture||Se.isCompressedArrayTexture)&&(ae=!0);const Re=Je.get(N).__webglFramebuffer;N.isWebGLCubeRenderTarget?(Array.isArray(Re[V])?X=Re[V][Z]:X=Re[V],ne=!0):N.samples>0&&ct.useMultisampledRTT(N)===!1?X=Je.get(N).__webglMultisampledFramebuffer:Array.isArray(Re)?X=Re[Z]:X=Re,ee.copy(N.viewport),se.copy(N.scissor),re=N.scissorTest}else ee.copy(nt).multiplyScalar(ie).floor(),se.copy(tt).multiplyScalar(ie).floor(),re=gt;if(Z!==0&&(X=R),Be.bindFramebuffer(G.FRAMEBUFFER,X)&&H&&Be.drawBuffers(N,X),Be.viewport(ee),Be.scissor(se),Be.setScissorTest(re),ne){const _e=Je.get(N.texture);G.framebufferTexture2D(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_CUBE_MAP_POSITIVE_X+V,_e.__webglTexture,Z)}else if(ae){const _e=V;for(let Se=0;Se=0&&V<=N.width-H&&Z>=0&&Z<=N.height-X&&(N.textures.length>1&&G.readBuffer(G.COLOR_ATTACHMENT0+fe),G.readPixels(V,Z,H,X,Oe.convert(Re),Oe.convert(Pe),ne))}finally{const Se=w!==null?Je.get(w).__webglFramebuffer:null;Be.bindFramebuffer(G.FRAMEBUFFER,Se)}}},this.readRenderTargetPixelsAsync=async function(N,V,Z,H,X,ne,ae,fe=0){if(!(N&&N.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let _e=Je.get(N).__webglFramebuffer;if(N.isWebGLCubeRenderTarget&&ae!==void 0&&(_e=_e[ae]),_e)if(V>=0&&V<=N.width-H&&Z>=0&&Z<=N.height-X){Be.bindFramebuffer(G.FRAMEBUFFER,_e);const Se=N.textures[fe],Re=Se.format,Pe=Se.type;if(!Fe.textureFormatReadable(Re))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Fe.textureTypeReadable(Pe))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const ze=G.createBuffer();G.bindBuffer(G.PIXEL_PACK_BUFFER,ze),G.bufferData(G.PIXEL_PACK_BUFFER,ne.byteLength,G.STREAM_READ),N.textures.length>1&&G.readBuffer(G.COLOR_ATTACHMENT0+fe),G.readPixels(V,Z,H,X,Oe.convert(Re),Oe.convert(Pe),0);const Ye=w!==null?Je.get(w).__webglFramebuffer:null;Be.bindFramebuffer(G.FRAMEBUFFER,Ye);const lt=G.fenceSync(G.SYNC_GPU_COMMANDS_COMPLETE,0);return G.flush(),await WF(G,lt,4),G.bindBuffer(G.PIXEL_PACK_BUFFER,ze),G.getBufferSubData(G.PIXEL_PACK_BUFFER,0,ne),G.deleteBuffer(ze),G.deleteSync(lt),ne}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(N,V=null,Z=0){const H=Math.pow(2,-Z),X=Math.floor(N.image.width*H),ne=Math.floor(N.image.height*H),ae=V!==null?V.x:0,fe=V!==null?V.y:0;ct.setTexture2D(N,0),G.copyTexSubImage2D(G.TEXTURE_2D,Z,0,0,ae,fe,X,ne),Be.unbindTexture()};const z=G.createFramebuffer(),Y=G.createFramebuffer();this.copyTextureToTexture=function(N,V,Z=null,H=null,X=0,ne=null){ne===null&&(X!==0?(Md("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),ne=X,X=0):ne=0);let ae,fe,_e,Se,Re,Pe,ze,Ye,lt;const Tt=N.isCompressedTexture?N.mipmaps[ne]:N.image;if(Z!==null)ae=Z.max.x-Z.min.x,fe=Z.max.y-Z.min.y,_e=Z.isBox3?Z.max.z-Z.min.z:1,Se=Z.min.x,Re=Z.min.y,Pe=Z.isBox3?Z.min.z:0;else{const Ai=Math.pow(2,-X);ae=Math.floor(Tt.width*Ai),fe=Math.floor(Tt.height*Ai),N.isDataArrayTexture?_e=Tt.depth:N.isData3DTexture?_e=Math.floor(Tt.depth*Ai):_e=1,Se=0,Re=0,Pe=0}H!==null?(ze=H.x,Ye=H.y,lt=H.z):(ze=0,Ye=0,lt=0);const bt=Oe.convert(V.format),ft=Oe.convert(V.type);let At;V.isData3DTexture?(ct.setTexture3D(V,0),At=G.TEXTURE_3D):V.isDataArrayTexture||V.isCompressedArrayTexture?(ct.setTexture2DArray(V,0),At=G.TEXTURE_2D_ARRAY):(ct.setTexture2D(V,0),At=G.TEXTURE_2D),G.pixelStorei(G.UNPACK_FLIP_Y_WEBGL,V.flipY),G.pixelStorei(G.UNPACK_PREMULTIPLY_ALPHA_WEBGL,V.premultiplyAlpha),G.pixelStorei(G.UNPACK_ALIGNMENT,V.unpackAlignment);const st=G.getParameter(G.UNPACK_ROW_LENGTH),Kt=G.getParameter(G.UNPACK_IMAGE_HEIGHT),On=G.getParameter(G.UNPACK_SKIP_PIXELS),Yt=G.getParameter(G.UNPACK_SKIP_ROWS),kt=G.getParameter(G.UNPACK_SKIP_IMAGES);G.pixelStorei(G.UNPACK_ROW_LENGTH,Tt.width),G.pixelStorei(G.UNPACK_IMAGE_HEIGHT,Tt.height),G.pixelStorei(G.UNPACK_SKIP_PIXELS,Se),G.pixelStorei(G.UNPACK_SKIP_ROWS,Re),G.pixelStorei(G.UNPACK_SKIP_IMAGES,Pe);const Nt=N.isDataArrayTexture||N.isData3DTexture,Bn=V.isDataArrayTexture||V.isData3DTexture;if(N.isDepthTexture){const Ai=Je.get(N),Mn=Je.get(V),Gn=Je.get(Ai.__renderTarget),_h=Je.get(Mn.__renderTarget);Be.bindFramebuffer(G.READ_FRAMEBUFFER,Gn.__webglFramebuffer),Be.bindFramebuffer(G.DRAW_FRAMEBUFFER,_h.__webglFramebuffer);for(let Ir=0;Ir<_e;Ir++)Nt&&(G.framebufferTextureLayer(G.READ_FRAMEBUFFER,G.COLOR_ATTACHMENT0,Je.get(N).__webglTexture,X,Pe+Ir),G.framebufferTextureLayer(G.DRAW_FRAMEBUFFER,G.COLOR_ATTACHMENT0,Je.get(V).__webglTexture,ne,lt+Ir)),G.blitFramebuffer(Se,Re,ae,fe,ze,Ye,ae,fe,G.DEPTH_BUFFER_BIT,G.NEAREST);Be.bindFramebuffer(G.READ_FRAMEBUFFER,null),Be.bindFramebuffer(G.DRAW_FRAMEBUFFER,null)}else if(X!==0||N.isRenderTargetTexture||Je.has(N)){const Ai=Je.get(N),Mn=Je.get(V);Be.bindFramebuffer(G.READ_FRAMEBUFFER,z),Be.bindFramebuffer(G.DRAW_FRAMEBUFFER,Y);for(let Gn=0;Gn<_e;Gn++)Nt?G.framebufferTextureLayer(G.READ_FRAMEBUFFER,G.COLOR_ATTACHMENT0,Ai.__webglTexture,X,Pe+Gn):G.framebufferTexture2D(G.READ_FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_2D,Ai.__webglTexture,X),Bn?G.framebufferTextureLayer(G.DRAW_FRAMEBUFFER,G.COLOR_ATTACHMENT0,Mn.__webglTexture,ne,lt+Gn):G.framebufferTexture2D(G.DRAW_FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_2D,Mn.__webglTexture,ne),X!==0?G.blitFramebuffer(Se,Re,ae,fe,ze,Ye,ae,fe,G.COLOR_BUFFER_BIT,G.NEAREST):Bn?G.copyTexSubImage3D(At,ne,ze,Ye,lt+Gn,Se,Re,ae,fe):G.copyTexSubImage2D(At,ne,ze,Ye,Se,Re,ae,fe);Be.bindFramebuffer(G.READ_FRAMEBUFFER,null),Be.bindFramebuffer(G.DRAW_FRAMEBUFFER,null)}else Bn?N.isDataTexture||N.isData3DTexture?G.texSubImage3D(At,ne,ze,Ye,lt,ae,fe,_e,bt,ft,Tt.data):V.isCompressedArrayTexture?G.compressedTexSubImage3D(At,ne,ze,Ye,lt,ae,fe,_e,bt,Tt.data):G.texSubImage3D(At,ne,ze,Ye,lt,ae,fe,_e,bt,ft,Tt):N.isDataTexture?G.texSubImage2D(G.TEXTURE_2D,ne,ze,Ye,ae,fe,bt,ft,Tt.data):N.isCompressedTexture?G.compressedTexSubImage2D(G.TEXTURE_2D,ne,ze,Ye,Tt.width,Tt.height,bt,Tt.data):G.texSubImage2D(G.TEXTURE_2D,ne,ze,Ye,ae,fe,bt,ft,Tt);G.pixelStorei(G.UNPACK_ROW_LENGTH,st),G.pixelStorei(G.UNPACK_IMAGE_HEIGHT,Kt),G.pixelStorei(G.UNPACK_SKIP_PIXELS,On),G.pixelStorei(G.UNPACK_SKIP_ROWS,Yt),G.pixelStorei(G.UNPACK_SKIP_IMAGES,kt),ne===0&&V.generateMipmaps&&G.generateMipmap(At),Be.unbindTexture()},this.initRenderTarget=function(N){Je.get(N).__webglFramebuffer===void 0&&ct.setupRenderTarget(N)},this.initTexture=function(N){N.isCubeTexture?ct.setTextureCube(N,0):N.isData3DTexture?ct.setTexture3D(N,0):N.isDataArrayTexture||N.isCompressedArrayTexture?ct.setTexture2DArray(N,0):ct.setTexture2D(N,0),Be.unbindTexture()},this.resetState=function(){P=0,O=0,w=null,Be.reset(),q.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return br}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=rn._getDrawingBufferColorSpace(e),t.unpackColorSpace=rn._getUnpackColorSpace()}}const vj=Object.freeze(Object.defineProperty({__proto__:null,ACESFilmicToneMapping:hb,AddEquation:Js,AddOperation:dU,AdditiveAnimationBlendMode:vb,AdditiveBlending:nE,AgXToneMapping:_U,AlphaFormat:pb,AlwaysCompare:LU,AlwaysDepth:r0,AlwaysStencilFunc:sE,AmbientLight:y6,AnimationAction:N6,AnimationClip:Ju,AnimationLoader:NV,AnimationMixer:D6,AnimationObjectGroup:ek,AnimationUtils:AV,ArcCurve:KU,ArrayCamera:w6,ArrowHelper:bk,AttachedBindMode:rE,Audio:R6,AudioAnalyser:WV,AudioContext:jb,AudioListener:GV,AudioLoader:BV,AxesHelper:I6,BackSide:Ui,BasicDepthPacking:Mc,BasicShadowMap:ZI,BatchedMesh:qU,Bone:V1,BooleanKeyframeTrack:fh,Box2:ck,Box3:ta,Box3Helper:Ek,BoxGeometry:ch,BoxHelper:Tk,BufferAttribute:Ot,BufferGeometry:Ct,BufferGeometryLoader:b6,ByteType:D1,Cache:no,Camera:bc,CameraHelper:Sk,CanvasTexture:ZG,CapsuleGeometry:Y1,CatmullRomCurve3:QU,CineonToneMapping:gU,CircleGeometry:q1,ClampToEdgeWrapping:Pi,Clock:Zb,Color:je,ColorKeyframeTrack:Gb,ColorManagement:rn,CompressedArrayTexture:qG,CompressedCubeTexture:jG,CompressedTexture:X1,CompressedTextureLoader:DV,ConeGeometry:H0,ConstantAlphaFactor:uU,ConstantColorFactor:lU,Controls:wk,CubeCamera:VU,CubeReflectionMapping:rl,CubeRefractionMapping:gc,CubeTexture:U0,CubeTextureLoader:OV,CubeUVReflectionMapping:Xd,CubicBezierCurve:Db,CubicBezierCurve3:JU,CubicInterpolant:p6,CullFaceBack:tE,CullFaceFront:jI,CullFaceFrontBack:cF,CullFaceNone:qI,Curve:Ls,CurvePath:e6,CustomBlending:ub,CustomToneMapping:vU,CylinderGeometry:B0,Cylindrical:lk,Data3DTexture:as,DataArrayTexture:B1,DataTexture:$a,DataTextureLoader:_6,DataUtils:oE,DecrementStencilOp:xF,DecrementWrapStencilOp:SF,DefaultLoadingManager:v6,DepthFormat:yd,DepthStencilFormat:ju,DepthTexture:z0,DetachedBindMode:yU,DirectionalLight:qb,DirectionalLightHelper:yk,DiscreteInterpolant:m6,DodecahedronGeometry:j1,DoubleSide:ca,DstAlphaFactor:iU,DstColorFactor:rU,DynamicCopyUsage:UF,DynamicDrawUsage:IU,DynamicReadUsage:OF,EdgesGeometry:ZU,EllipseCurve:Z1,EqualCompare:CU,EqualDepth:ax,EqualStencilFunc:bF,EquirectangularReflectionMapping:s0,EquirectangularRefractionMapping:o0,Euler:Ei,EventDispatcher:nr,ExternalTexture:Cb,ExtrudeGeometry:K1,FileLoader:os,Float16BufferAttribute:bG,Float32BufferAttribute:xt,FloatType:si,Fog:F1,FogExp2:H1,FramebufferTexture:YG,FrontSide:Ns,Frustum:Yd,FrustumArray:k1,GLBufferAttribute:fE,GLSL1:zF,GLSL3:ro,GreaterCompare:NU,GreaterDepth:sx,GreaterEqualCompare:OU,GreaterEqualDepth:rx,GreaterEqualStencilFunc:CF,GreaterStencilFunc:wF,GridHelper:_k,Group:Ua,HalfFloatType:Xn,HemisphereLight:x6,HemisphereLightHelper:vk,IcosahedronGeometry:Q1,ImageBitmapLoader:A6,ImageLoader:Nd,ImageUtils:zU,IncrementStencilOp:_F,IncrementWrapStencilOp:yF,InstancedBufferAttribute:Zu,InstancedBufferGeometry:M6,InstancedInterleavedBuffer:rk,InstancedMesh:Ab,Int16BufferAttribute:EG,Int32BufferAttribute:MG,Int8BufferAttribute:yG,IntType:L0,InterleavedBuffer:P0,InterleavedBufferAttribute:_c,Interpolant:qd,InterpolateDiscrete:Sd,InterpolateLinear:Td,InterpolateSmooth:m_,InterpolationSamplingMode:FF,InterpolationSamplingType:HF,InvertStencilOp:TF,KeepStencilOp:xu,KeyframeTrack:cs,LOD:YU,LatheGeometry:J1,Layers:Ad,LessCompare:RU,LessDepth:ix,LessEqualCompare:xb,LessEqualDepth:Xu,LessEqualStencilFunc:AF,LessStencilFunc:MF,Light:Rc,LightProbe:E6,Line:so,Line3:fk,LineBasicMaterial:Bi,LineCurve:Ob,LineCurve3:$U,LineDashedMaterial:h6,LineLoop:wb,LineSegments:ir,LinearFilter:Ht,LinearInterpolant:Fb,LinearMipMapLinearFilter:SU,LinearMipMapNearestFilter:fF,LinearMipmapLinearFilter:Mr,LinearMipmapNearestFilter:id,LinearSRGBColorSpace:Wn,LinearToneMapping:pU,LinearTransfer:c0,Loader:Mi,LoaderUtils:uc,LoadingManager:Vb,LoopOnce:gb,LoopPingPong:EU,LoopRepeat:TU,MOUSE:vu,Material:qn,MaterialLoader:ry,MathUtils:$t,Matrix2:Jb,Matrix3:Et,Matrix4:ke,MaxEquation:$I,Mesh:oi,MeshBasicMaterial:Ia,MeshDepthMaterial:zb,MeshDistanceMaterial:Bb,MeshLambertMaterial:c6,MeshMatcapMaterial:u6,MeshNormalMaterial:Pb,MeshPhongMaterial:o6,MeshPhysicalMaterial:ls,MeshStandardMaterial:V0,MeshToonMaterial:l6,MinEquation:JI,MirroredRepeatWrapping:xd,MixOperation:fU,MultiplyBlending:aE,MultiplyOperation:O0,NearestFilter:Fn,NearestMipMapLinearFilter:hF,NearestMipMapNearestFilter:uF,NearestMipmapLinearFilter:Tu,NearestMipmapNearestFilter:N1,NeutralToneMapping:xU,NeverCompare:wU,NeverDepth:nx,NeverStencilFunc:EF,NoBlending:Ta,NoColorSpace:Da,NoToneMapping:is,NormalAnimationBlendMode:z1,NormalBlending:Iu,NotEqualCompare:DU,NotEqualDepth:ox,NotEqualStencilFunc:RF,NumberKeyframeTrack:xc,Object3D:Wt,ObjectLoader:PV,ObjectSpaceNormalMap:AU,OctahedronGeometry:F0,OneFactor:kf,OneMinusConstantAlphaFactor:hU,OneMinusConstantColorFactor:cU,OneMinusDstAlphaFactor:aU,OneMinusDstColorFactor:sU,OneMinusSrcAlphaFactor:tx,OneMinusSrcColorFactor:nU,OrthographicCamera:ao,PCFShadowMap:R1,PCFSoftShadowMap:Dm,PMREMGenerator:gE,Path:Fx,PerspectiveCamera:hi,Plane:Go,PlaneGeometry:uh,PlaneHelper:Mk,PointLight:Yb,PointLightHelper:mk,Points:Rb,PointsMaterial:W1,PolarGridHelper:xk,PolyhedronGeometry:wc,PositionalAudio:kV,PropertyBinding:fn,PropertyMixer:C6,QuadraticBezierCurve:Lb,QuadraticBezierCurve3:Ib,Quaternion:St,QuaternionKeyframeTrack:yc,QuaternionLinearInterpolant:g6,RED_GREEN_RGTC2_Format:Ix,RED_RGTC1_Format:Ox,REVISION:Cs,RGBADepthPacking:bU,RGBAFormat:$n,RGBAIntegerFormat:P1,RGBA_ASTC_10x10_Format:Ax,RGBA_ASTC_10x5_Format:Ex,RGBA_ASTC_10x6_Format:Mx,RGBA_ASTC_10x8_Format:bx,RGBA_ASTC_12x10_Format:wx,RGBA_ASTC_12x12_Format:Rx,RGBA_ASTC_4x4_Format:mx,RGBA_ASTC_5x4_Format:gx,RGBA_ASTC_5x5_Format:vx,RGBA_ASTC_6x5_Format:_x,RGBA_ASTC_6x6_Format:xx,RGBA_ASTC_8x5_Format:yx,RGBA_ASTC_8x6_Format:Sx,RGBA_ASTC_8x8_Format:Tx,RGBA_BPTC_Format:Cx,RGBA_ETC2_EAC_Format:px,RGBA_PVRTC_2BPPV1_Format:hx,RGBA_PVRTC_4BPPV1_Format:ux,RGBA_S3TC_DXT1_Format:Lm,RGBA_S3TC_DXT3_Format:Im,RGBA_S3TC_DXT5_Format:Um,RGBDepthPacking:pF,RGBFormat:mb,RGBIntegerFormat:dF,RGB_BPTC_SIGNED_Format:Nx,RGB_BPTC_UNSIGNED_Format:Dx,RGB_ETC1_Format:fx,RGB_ETC2_Format:dx,RGB_PVRTC_2BPPV1_Format:cx,RGB_PVRTC_4BPPV1_Format:lx,RGB_S3TC_DXT1_Format:Om,RGDepthPacking:mF,RGFormat:ko,RGIntegerFormat:U1,RawShaderMaterial:hh,Ray:lh,Raycaster:O6,RectAreaLight:S6,RedFormat:As,RedIntegerFormat:I0,ReinhardToneMapping:mU,RenderTarget:Sb,RenderTarget3D:nk,RepeatWrapping:Ea,ReplaceStencilOp:vF,ReverseSubtractEquation:QI,RingGeometry:$1,SIGNED_RED_GREEN_RGTC2_Format:Ux,SIGNED_RED_RGTC1_Format:Lx,SRGBColorSpace:En,SRGBTransfer:wn,Scene:Rd,ShaderChunk:Qt,ShaderLib:bs,ShaderMaterial:Vi,ShadowMaterial:s6,Shape:Pu,ShapeGeometry:ey,ShapePath:Ak,ShapeUtils:ws,ShortType:O1,Skeleton:Ac,SkeletonHelper:pk,SkinnedMesh:G1,Source:Jl,Sphere:na,SphereGeometry:G0,Spherical:pE,SphericalHarmonics3:T6,SplineCurve:Ub,SpotLight:Xb,SpotLightHelper:dk,Sprite:XU,SpriteMaterial:bb,SrcAlphaFactor:ex,SrcAlphaSaturateFactor:oU,SrcColorFactor:tU,StaticCopyUsage:IF,StaticDrawUsage:u0,StaticReadUsage:DF,StereoCamera:HV,StreamCopyUsage:PF,StreamDrawUsage:NF,StreamReadUsage:LF,StringKeyframeTrack:dh,SubtractEquation:KI,SubtractiveBlending:iE,TOUCH:_u,TangentSpaceNormalMap:ll,TetrahedronGeometry:ty,Texture:Nn,TextureLoader:kb,TextureUtils:Ok,Timer:sk,TimestampQuery:BF,TorusGeometry:ny,TorusKnotGeometry:iy,Triangle:Qa,TriangleFanDrawMode:Px,TriangleStripDrawMode:_b,TrianglesDrawMode:MU,TubeGeometry:ay,UVMapping:C1,Uint16BufferAttribute:Tb,Uint32BufferAttribute:Eb,Uint8BufferAttribute:SG,Uint8ClampedBufferAttribute:TG,Uniform:J,UniformsGroup:ak,UniformsLib:at,UniformsUtils:Mb,UnsignedByteType:zi,UnsignedInt101111Type:db,UnsignedInt248Type:qu,UnsignedInt5999Type:fb,UnsignedIntType:Ds,UnsignedShort4444Type:L1,UnsignedShort5551Type:I1,UnsignedShortType:Yu,VSMShadowMap:Ss,Vector2:de,Vector3:L,Vector4:zt,VectorKeyframeTrack:Qu,VideoFrameTexture:XG,VideoTexture:jU,WebGL3DRenderTarget:HU,WebGLArrayRenderTarget:BU,WebGLCoordinateSystem:br,WebGLCubeRenderTarget:kU,WebGLRenderTarget:xi,WebGLRenderer:$b,WebGLUtils:F6,WebGPUCoordinateSystem:Ed,WebXRController:g_,WireframeGeometry:r6,WrapAroundEnding:l0,ZeroCurvatureEnding:Eu,ZeroFactor:eU,ZeroSlopeEnding:Mu,ZeroStencilOp:gF,createCanvasElement:PU,error:Bt,getConsoleFunction:kF,log:f0,setConsoleFunction:VF,warn:ut,warnOnce:Md},Symbol.toStringTag,{value:"Module"}));var G6={exports:{}},V6={},k6={exports:{}},W6={};/** - * @license React - * use-sync-external-store-shim.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Dd=Me;function _j(n,e){return n===e&&(n!==0||1/n===1/e)||n!==n&&e!==e}var xj=typeof Object.is=="function"?Object.is:_j,yj=Dd.useState,Sj=Dd.useEffect,Tj=Dd.useLayoutEffect,Ej=Dd.useDebugValue;function Mj(n,e){var t=e(),i=yj({inst:{value:t,getSnapshot:e}}),a=i[0].inst,r=i[1];return Tj(function(){a.value=t,a.getSnapshot=e,g2(a)&&r({inst:a})},[n,t,e]),Sj(function(){return g2(a)&&r({inst:a}),n(function(){g2(a)&&r({inst:a})})},[n]),Ej(t),t}function g2(n){var e=n.getSnapshot;n=n.value;try{var t=e();return!xj(n,t)}catch{return!0}}function bj(n,e){return e()}var Aj=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?bj:Mj;W6.useSyncExternalStore=Dd.useSyncExternalStore!==void 0?Dd.useSyncExternalStore:Aj;k6.exports=W6;var wj=k6.exports;/** - * @license React - * use-sync-external-store-shim/with-selector.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ly=Me,Rj=wj;function Cj(n,e){return n===e&&(n!==0||1/n===1/e)||n!==n&&e!==e}var Nj=typeof Object.is=="function"?Object.is:Cj,Dj=Rj.useSyncExternalStore,Oj=ly.useRef,Lj=ly.useEffect,Ij=ly.useMemo,Uj=ly.useDebugValue;V6.useSyncExternalStoreWithSelector=function(n,e,t,i,a){var r=Oj(null);if(r.current===null){var s={hasValue:!1,value:null};r.current=s}else s=r.current;r=Ij(function(){function c(g){if(!h){if(h=!0,f=g,g=i(g),a!==void 0&&s.hasValue){var x=s.value;if(a(x,g))return d=x}return d=g}if(x=d,Nj(f,g))return x;var T=i(g);return a!==void 0&&a(x,T)?(f=g,x):(f=g,d=T)}var h=!1,f,d,m=t===void 0?null:t;return[function(){return c(e())},m===null?void 0:function(){return c(m())}]},[e,t,i,a]);var o=Dj(n,r[0],r[1]);return Lj(function(){s.hasValue=!0,s.value=o},[o]),Uj(o),o};G6.exports=V6;var Pj=G6.exports;const zj=l1(Pj),BN=n=>{let e;const t=new Set,i=(h,f)=>{const d=typeof h=="function"?h(e):h;if(!Object.is(d,e)){const m=e;e=f??(typeof d!="object"||d===null)?d:Object.assign({},e,d),t.forEach(g=>g(e,m))}},a=()=>e,o={setState:i,getState:a,getInitialState:()=>c,subscribe:h=>(t.add(h),()=>t.delete(h))},c=e=n(i,a,o);return o},Bj=n=>n?BN(n):BN,{useSyncExternalStoreWithSelector:Hj}=zj,Fj=n=>n;function Gj(n,e=Fj,t){const i=Hj(n.subscribe,n.getState,n.getInitialState,e,t);return dM.useDebugValue(i),i}const HN=(n,e)=>{const t=Bj(n),i=(a,r=e)=>Gj(t,a,r);return Object.assign(i,t),i},Vj=(n,e)=>n?HN(n,e):HN,kj=n=>typeof n=="object"&&typeof n.then=="function",Au=[];function X6(n,e,t=(i,a)=>i===a){if(n===e)return!0;if(!n||!e)return!1;const i=n.length;if(e.length!==i)return!1;for(let a=0;a0&&(r.timeout&&clearTimeout(r.timeout),r.timeout=setTimeout(r.remove,i.lifespan)),r.response;if(!t)throw r.promise}const a={keys:e,equal:i.equal,remove:()=>{const r=Au.indexOf(a);r!==-1&&Au.splice(r,1)},promise:(kj(n)?n:n(...e)).then(r=>{a.response=r,i.lifespan&&i.lifespan>0&&(a.timeout=setTimeout(a.remove,i.lifespan))}).catch(r=>a.error=r)};if(Au.push(a),!t)throw a.promise}const Wj=(n,e,t)=>Y6(n,e,!1,t),Xj=(n,e,t)=>void Y6(n,e,!0,t),Yj=n=>{if(n===void 0||n.length===0)Au.splice(0,Au.length);else{const e=Au.find(t=>X6(n,t.keys,t.equal));e&&e.remove()}};var q6={exports:{}},j6={exports:{}},Z6={exports:{}},K6={};/** - * @license React - * scheduler.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */(function(n){function e(W,te){var K=W.length;W.push(te);e:for(;0>>1,ie=W[oe];if(0>>1;oea(nt,K))tta(gt,nt)?(W[oe]=gt,W[tt]=K,oe=tt):(W[oe]=nt,W[Xe]=K,oe=Xe);else if(tta(gt,K))W[oe]=gt,W[tt]=K,oe=tt;else break e}}return te}function a(W,te){var K=W.sortIndex-te.sortIndex;return K!==0?K:W.id-te.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var r=performance;n.unstable_now=function(){return r.now()}}else{var s=Date,o=s.now();n.unstable_now=function(){return s.now()-o}}var c=[],h=[],f=1,d=null,m=3,g=!1,x=!1,T=!1,y=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function E(W){for(var te=t(h);te!==null;){if(te.callback===null)i(h);else if(te.startTime<=W)i(h),te.sortIndex=te.expirationTime,e(c,te);else break;te=t(h)}}function b(W){if(T=!1,E(W),!x)if(t(c)!==null)x=!0,se();else{var te=t(h);te!==null&&re(b,te.startTime-W)}}var D=!1,C=-1,I=5,P=-1;function O(){return!(n.unstable_now()-PW&&O());){var oe=d.callback;if(typeof oe=="function"){d.callback=null,m=d.priorityLevel;var ie=oe(d.expirationTime<=W);if(W=n.unstable_now(),typeof ie=="function"){d.callback=ie,E(W),te=!0;break t}d===t(c)&&i(c),E(W)}else i(c);d=t(c)}if(d!==null)te=!0;else{var Ce=t(h);Ce!==null&&re(b,Ce.startTime-W),te=!1}}break e}finally{d=null,m=K,g=!1}te=void 0}}finally{te?B():D=!1}}}var B;if(typeof S=="function")B=function(){S(w)};else if(typeof MessageChannel<"u"){var j=new MessageChannel,ee=j.port2;j.port1.onmessage=w,B=function(){ee.postMessage(null)}}else B=function(){y(w,0)};function se(){D||(D=!0,B())}function re(W,te){C=y(function(){W(n.unstable_now())},te)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(W){W.callback=null},n.unstable_continueExecution=function(){x||g||(x=!0,se())},n.unstable_forceFrameRate=function(W){0>W||125oe?(W.sortIndex=K,e(h,W),t(c)===null&&W===t(h)&&(T?(v(C),C=-1):T=!0,re(b,K-oe))):(W.sortIndex=ie,e(c,W),x||g||(x=!0,se())),W},n.unstable_shouldYield=O,n.unstable_wrapCallback=function(W){var te=m;return function(){var K=m;m=te;try{return W.apply(this,arguments)}finally{m=K}}}})(K6);Z6.exports=K6;var _E=Z6.exports;/** - * @license React - * react-reconciler.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */(function(n){n.exports=function(e){function t(l,u,p,_){return new R9(l,u,p,_)}function i(){}function a(l){var u="https://react.dev/errors/"+l;if(1)":-1M||he[_]!==Ne[M]){var et=` -`+he[_].replace(" at new "," at ");return l.displayName&&et.includes("")&&(et=et.replace("",l.displayName)),et}while(1<=_&&0<=M);break}}}finally{vS=!1,Error.prepareStackTrace=p}return(p=l?l.displayName||l.name:"")?o(p):""}function h(l){switch(l.tag){case 26:case 27:case 5:return o(l.type);case 16:return o("Lazy");case 13:return o("Suspense");case 19:return o("SuspenseList");case 0:case 15:return l=c(l.type,!1),l;case 11:return l=c(l.type.render,!1),l;case 1:return l=c(l.type,!0),l;default:return""}}function f(l){try{var u="";do u+=h(l),l=l.return;while(l);return u}catch(p){return` -Error generating stack: `+p.message+` -`+p.stack}}function d(l){var u=l,p=l;if(l.alternate)for(;u.return;)u=u.return;else{l=u;do u=l,u.flags&4098&&(p=u.return),l=u.return;while(l)}return u.tag===3?p:null}function m(l){if(d(l)!==l)throw Error(a(188))}function g(l){var u=l.alternate;if(!u){if(u=d(l),u===null)throw Error(a(188));return u!==l?null:l}for(var p=l,_=u;;){var M=p.return;if(M===null)break;var A=M.alternate;if(A===null){if(_=M.return,_!==null){p=_;continue}break}if(M.child===A.child){for(A=M.child;A;){if(A===p)return m(M),l;if(A===_)return m(M),u;A=A.sibling}throw Error(a(188))}if(p.return!==_.return)p=M,_=A;else{for(var F=!1,$=M.child;$;){if($===p){F=!0,p=M,_=A;break}if($===_){F=!0,_=M,p=A;break}$=$.sibling}if(!F){for($=A.child;$;){if($===p){F=!0,p=A,_=M;break}if($===_){F=!0,_=A,p=M;break}$=$.sibling}if(!F)throw Error(a(189))}}if(p.alternate!==_)throw Error(a(190))}if(p.tag!==3)throw Error(a(188));return p.stateNode.current===p?l:u}function x(l){var u=l.tag;if(u===5||u===26||u===27||u===6)return l;for(l=l.child;l!==null;){if(u=x(l),u!==null)return u;l=l.sibling}return null}function T(l){var u=l.tag;if(u===5||u===26||u===27||u===6)return l;for(l=l.child;l!==null;){if(l.tag!==4&&(u=T(l),u!==null))return u;l=l.sibling}return null}function y(l){return{current:l}}function v(l){0>Ah||(l.current=ES[Ah],ES[Ah]=null,Ah--)}function S(l,u){Ah++,ES[Ah]=l.current,l.current=u}function E(l){return l>>>=0,l===0?32:31-(Z7(l)/K7|0)|0}function b(l){var u=l&42;if(u!==0)return u;switch(l&-l){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: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 l&4194176;case 4194304:case 8388608:case 16777216:case 33554432:return l&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return l}}function D(l,u){var p=l.pendingLanes;if(p===0)return 0;var _=0,M=l.suspendedLanes,A=l.pingedLanes,F=l.warmLanes;l=l.finishedLanes!==0;var $=p&134217727;return $!==0?(p=$&~M,p!==0?_=b(p):(A&=$,A!==0?_=b(A):l||(F=$&~F,F!==0&&(_=b(F))))):($=p&~M,$!==0?_=b($):A!==0?_=b(A):l||(F=p&~F,F!==0&&(_=b(F)))),_===0?0:u!==0&&u!==_&&!(u&M)&&(M=_&-_,F=u&-u,M>=F||M===32&&(F&4194176)!==0)?u:_}function C(l,u){return(l.pendingLanes&~(l.suspendedLanes&~l.pingedLanes)&u)===0}function I(l,u){switch(l){case 1:case 2:case 4:case 8:return u+250;case 16:case 32:case 64: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 u+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 P(){var l=ug;return ug<<=1,!(ug&4194176)&&(ug=128),l}function O(){var l=hg;return hg<<=1,!(hg&62914560)&&(hg=4194304),l}function w(l){for(var u=[],p=0;31>p;p++)u.push(l);return u}function B(l,u){l.pendingLanes|=u,u!==268435456&&(l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0)}function j(l,u,p,_,M,A){var F=l.pendingLanes;l.pendingLanes=p,l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0,l.expiredLanes&=p,l.entangledLanes&=p,l.errorRecoveryDisabledLanes&=p,l.shellSuspendCounter=0;var $=l.entanglements,he=l.expirationTimes,Ne=l.hiddenUpdates;for(p=F&~p;0>=F,M-=F,_o=1<<32-fr(u)+M|p<mn?(ji=Pt,Pt=null):ji=Pt.sibling;var gn=mt(ve,Pt,xe[mn],Qe);if(gn===null){Pt===null&&(Pt=ji);break}l&&Pt&&gn.alternate===null&&u(ve,Pt),le=A(gn,le,mn),Zn===null?wt=gn:Zn.sibling=gn,Zn=gn,Pt=ji}if(mn===xe.length)return p(ve,Pt),pn&&ie(ve,mn),wt;if(Pt===null){for(;mnmn?(ji=Pt,Pt=null):ji=Pt.sibling;var bl=mt(ve,Pt,gn.value,Qe);if(bl===null){Pt===null&&(Pt=ji);break}l&&Pt&&bl.alternate===null&&u(ve,Pt),le=A(bl,le,mn),Zn===null?wt=bl:Zn.sibling=bl,Zn=bl,Pt=ji}if(gn.done)return p(ve,Pt),pn&&ie(ve,mn),wt;if(Pt===null){for(;!gn.done;mn++,gn=xe.next())gn=dt(ve,gn.value,Qe),gn!==null&&(le=A(gn,le,mn),Zn===null?wt=gn:Zn.sibling=gn,Zn=gn);return pn&&ie(ve,mn),wt}for(Pt=_(Pt);!gn.done;mn++,gn=xe.next())gn=qt(Pt,ve,mn,gn.value,Qe),gn!==null&&(l&&gn.alternate!==null&&Pt.delete(gn.key===null?mn:gn.key),le=A(gn,le,mn),Zn===null?wt=gn:Zn.sibling=gn,Zn=gn);return l&&Pt.forEach(function(uz){return u(ve,uz)}),pn&&ie(ve,mn),wt}function Yc(ve,le,xe,Qe){if(typeof xe=="object"&&xe!==null&&xe.type===Mh&&xe.key===null&&(xe=xe.props.children),typeof xe=="object"&&xe!==null){switch(xe.$$typeof){case og:e:{for(var wt=xe.key;le!==null;){if(le.key===wt){if(wt=xe.type,wt===Mh){if(le.tag===7){p(ve,le.sibling),Qe=M(le,xe.props.children),Qe.return=ve,ve=Qe;break e}}else if(le.elementType===wt||typeof wt=="object"&&wt!==null&&wt.$$typeof===vl&&li(wt)===le.type){p(ve,le.sibling),Qe=M(le,xe.props),Gt(Qe,xe),Qe.return=ve,ve=Qe;break e}p(ve,le);break}else u(ve,le);le=le.sibling}xe.type===Mh?(Qe=Ic(xe.props.children,ve.mode,Qe,xe.key),Qe.return=ve,ve=Qe):(Qe=sg(xe.type,xe.key,xe.props,null,ve.mode,Qe),Gt(Qe,xe),Qe.return=ve,ve=Qe)}return F(ve);case Eh:e:{for(wt=xe.key;le!==null;){if(le.key===wt)if(le.tag===4&&le.stateNode.containerInfo===xe.containerInfo&&le.stateNode.implementation===xe.implementation){p(ve,le.sibling),Qe=M(le,xe.children||[]),Qe.return=ve,ve=Qe;break e}else{p(ve,le);break}else u(ve,le);le=le.sibling}Qe=lS(xe,ve.mode,Qe),Qe.return=ve,ve=Qe}return F(ve);case vl:return wt=xe._init,xe=wt(xe._payload),Yc(ve,le,xe,Qe)}if(lg(xe))return Vr(ve,le,xe,Qe);if(r(xe)){if(wt=r(xe),typeof wt!="function")throw Error(a(150));return xe=wt.call(xe),bp(ve,le,xe,Qe)}if(typeof xe.then=="function")return Yc(ve,le,yt(xe),Qe);if(xe.$$typeof===gl)return Yc(ve,le,eg(ve,xe),Qe);Vt(ve,xe)}return typeof xe=="string"&&xe!==""||typeof xe=="number"||typeof xe=="bigint"?(xe=""+xe,le!==null&&le.tag===6?(p(ve,le.sibling),Qe=M(le,xe),Qe.return=ve,ve=Qe):(p(ve,le),Qe=oS(xe,ve.mode,Qe),Qe.return=ve,ve=Qe),F(ve)):p(ve,le)}return function(ve,le,xe,Qe){try{_p=0;var wt=Yc(ve,le,xe,Qe);return Ph=null,wt}catch(Pt){if(Pt===vp)throw Pt;var Zn=t(29,Pt,null,ve.mode);return Zn.lanes=Qe,Zn.return=ve,Zn}finally{}}}function uo(l,u){l=Eo,S(xg,l),S(zh,u),Eo=l|u.baseLanes}function Is(){S(xg,Eo),S(zh,zh.current)}function Us(){Eo=xg.current,v(zh),v(xg)}function bi(l){var u=l.alternate;S(Hi,Hi.current&1),S(Fr,l),Fs===null&&(u===null||zh.current!==null||u.memoizedState!==null)&&(Fs=l)}function Ps(l){if(l.tag===22){if(S(Hi,Hi.current),S(Fr,l),Fs===null){var u=l.alternate;u!==null&&u.memoizedState!==null&&(Fs=l)}}else fa()}function fa(){S(Hi,Hi.current),S(Fr,Fr.current)}function Xi(l){v(Fr),Fs===l&&(Fs=null),v(Hi)}function Fa(l){for(var u=l;u!==null;){if(u.tag===13){var p=u.memoizedState;if(p!==null&&(p=p.dehydrated,p===null||yS(p)||SS(p)))return u}else if(u.tag===19&&u.memoizedProps.revealOrder!==void 0){if(u.flags&128)return u}else if(u.child!==null){u.child.return=u,u=u.child;continue}if(u===l)break;for(;u.sibling===null;){if(u.return===null||u.return===l)return null;u=u.return}u.sibling.return=u.return,u=u.sibling}return null}function Dn(){throw Error(a(321))}function Lr(l,u){if(u===null)return!1;for(var p=0;pA?A:8);var F=Ft.T,$={};Ft.T=$,wy(l,!1,u,p);try{var he=M(),Ne=Ft.S;if(Ne!==null&&Ne($,he),he!==null&&typeof he=="object"&&typeof he.then=="function"){var et=qe(he,_);ip(l,u,et,ur(l))}else ip(l,u,_,ur(l))}catch(dt){ip(l,u,{then:function(){},status:"rejected",reason:dt},ur())}finally{Va(A),Ft.T=F}}function zA(l){var u=l.memoizedState;if(u!==null)return u;u={memoizedState:bh,baseState:bh,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:X,lastRenderedState:bh},next:null};var p={};return u.next={memoizedState:p,baseState:p,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:X,lastRenderedState:p},next:null},l.memoizedState=u,l=l.alternate,l!==null&&(l.memoizedState=u),u}function Ay(){return pa(Pc)}function BA(){return N().memoizedState}function HA(){return N().memoizedState}function h9(l){for(var u=l.return;u!==null;){switch(u.tag){case 24:case 3:var p=ur();l=Ie(p);var _=He(u,l,p);_!==null&&(Ma(_,u,p),ht(_,u,p)),u={cache:Fy()},l.payload=u;return}u=u.return}}function f9(l,u,p){var _=ur();p={lane:_,revertLane:0,action:p,hasEagerState:!1,eagerState:null,next:null},Q0(l)?GA(u,p):(p=be(l,u,p,_),p!==null&&(Ma(p,l,_),VA(p,u,_)))}function FA(l,u,p){var _=ur();ip(l,u,p,_)}function ip(l,u,p,_){var M={lane:_,revertLane:0,action:p,hasEagerState:!1,eagerState:null,next:null};if(Q0(l))GA(u,M);else{var A=l.alternate;if(l.lanes===0&&(A===null||A.lanes===0)&&(A=u.lastRenderedReducer,A!==null))try{var F=u.lastRenderedState,$=A(F,p);if(M.hasEagerState=!0,M.eagerState=$,pr($,F))return G(l,u,M,0),Vn===null&&Te(),!1}catch{}finally{}if(p=be(l,u,M,_),p!==null)return Ma(p,l,_),VA(p,u,_),!0}return!1}function wy(l,u,p,_){if(_={lane:2,revertLane:Le(),action:_,hasEagerState:!1,eagerState:null,next:null},Q0(l)){if(u)throw Error(a(479))}else u=be(l,p,_,2),u!==null&&Ma(u,l,2)}function Q0(l){var u=l.alternate;return l===en||u!==null&&u===en}function GA(l,u){Bh=yg=!0;var p=l.pending;p===null?u.next=u:(u.next=p.next,p.next=u),l.pending=u}function VA(l,u,p){if(p&4194176){var _=u.lanes;_&=l.pendingLanes,p|=_,u.lanes=p,se(l,p)}}function Ry(l,u,p,_){u=l.memoizedState,p=p(_,u),p=p==null?u:uS({},u,p),l.memoizedState=p,l.lanes===0&&(l.updateQueue.baseState=p)}function kA(l,u,p,_,M,A,F){return l=l.stateNode,typeof l.shouldComponentUpdate=="function"?l.shouldComponentUpdate(_,A,F):u.prototype&&u.prototype.isPureReactComponent?!me(p,_)||!me(M,A):!0}function WA(l,u,p,_){l=u.state,typeof u.componentWillReceiveProps=="function"&&u.componentWillReceiveProps(p,_),typeof u.UNSAFE_componentWillReceiveProps=="function"&&u.UNSAFE_componentWillReceiveProps(p,_),u.state!==l&&IS.enqueueReplaceState(u,u.state,null)}function Cc(l,u){var p=u;if("ref"in u){p={};for(var _ in u)_!=="ref"&&(p[_]=u[_])}if(l=l.defaultProps){p===u&&(p=uS({},p));for(var M in l)p[M]===void 0&&(p[M]=l[M])}return p}function J0(l,u){try{var p=l.onUncaughtError;p(u.value,{componentStack:u.stack})}catch(_){setTimeout(function(){throw _})}}function XA(l,u,p){try{var _=l.onCaughtError;_(p.value,{componentStack:p.stack,errorBoundary:u.tag===1?u.stateNode:null})}catch(M){setTimeout(function(){throw M})}}function Cy(l,u,p){return p=Ie(p),p.tag=3,p.payload={element:null},p.callback=function(){J0(l,u)},p}function YA(l){return l=Ie(l),l.tag=3,l}function qA(l,u,p,_){var M=p.type.getDerivedStateFromError;if(typeof M=="function"){var A=_.value;l.payload=function(){return M(A)},l.callback=function(){XA(u,p,_)}}var F=p.stateNode;F!==null&&typeof F.componentDidCatch=="function"&&(l.callback=function(){XA(u,p,_),typeof M!="function"&&(Ml===null?Ml=new Set([this]):Ml.add(this));var $=_.stack;this.componentDidCatch(_.value,{componentStack:$!==null?$:""})})}function d9(l,u,p,_,M){if(p.flags|=32768,_!==null&&typeof _=="object"&&typeof _.then=="function"){if(u=p.alternate,u!==null&&rp(u,p,M,!0),p=Fr.current,p!==null){switch(p.tag){case 13:return Fs===null?iS():p.alternate===null&&mi===0&&(mi=3),p.flags&=-257,p.flags|=65536,p.lanes=M,_===_g?p.flags|=16384:(u=p.updateQueue,u===null?p.updateQueue=new Set([_]):u.add(_),rS(l,_,M)),!1;case 22:return p.flags|=65536,_===_g?p.flags|=16384:(u=p.updateQueue,u===null?(u={transitions:null,markerInstances:null,retryQueue:new Set([_])},p.updateQueue=u):(p=u.retryQueue,p===null?u.retryQueue=new Set([_]):p.add(_)),rS(l,_,M)),!1}throw Error(a(435,p.tag))}return rS(l,_,M),iS(),!1}if(pn)return u=Fr.current,u!==null?(!(u.flags&65536)&&(u.flags|=256),u.flags|=65536,u.lanes=M,_!==AS&&(l=Error(a(422),{cause:_}),Ke(oe(l,p)))):(_!==AS&&(u=Error(a(423),{cause:_}),Ke(oe(u,p))),l=l.current.alternate,l.flags|=65536,M&=-M,l.lanes|=M,_=oe(_,p),M=Cy(l.stateNode,_,M),Q(l,M),mi!==4&&(mi=2)),!1;var A=Error(a(520),{cause:_});if(A=oe(A,p),Sp===null?Sp=[A]:Sp.push(A),mi!==4&&(mi=2),u===null)return!0;_=oe(_,p),p=u;do{switch(p.tag){case 3:return p.flags|=65536,l=M&-M,p.lanes|=l,l=Cy(p.stateNode,_,l),Q(p,l),!1;case 1:if(u=p.type,A=p.stateNode,(p.flags&128)===0&&(typeof u.getDerivedStateFromError=="function"||A!==null&&typeof A.componentDidCatch=="function"&&(Ml===null||!Ml.has(A))))return p.flags|=65536,M&=-M,p.lanes|=M,M=YA(M),qA(M,l,p,_),Q(p,M),!1}p=p.return}while(p!==null);return!1}function aa(l,u,p,_){u.child=l===null?CR(u,null,p,_):Bc(u,l.child,p,_)}function jA(l,u,p,_,M){p=p.render;var A=u.ref;if("ref"in _){var F={};for(var $ in _)$!=="ref"&&(F[$]=_[$])}else F=_;return Nc(u),_=zs(l,u,p,F,A,M),$=da(),l!==null&&!Yi?(R(l,u,M),fo(l,u,M)):(pn&&$&&Xe(u),u.flags|=1,aa(l,u,_,M),u.child)}function ZA(l,u,p,_,M){if(l===null){var A=p.type;return typeof A=="function"&&!sS(A)&&A.defaultProps===void 0&&p.compare===null?(u.tag=15,u.type=A,KA(l,u,A,_,M)):(l=sg(p.type,null,_,u,u.mode,M),l.ref=u.ref,l.return=u,u.child=l)}if(A=l.child,!zy(l,M)){var F=A.memoizedProps;if(p=p.compare,p=p!==null?p:me,p(F,_)&&l.ref===u.ref)return fo(l,u,M)}return u.flags|=1,l=ml(A,_),l.ref=u.ref,l.return=u,u.child=l}function KA(l,u,p,_,M){if(l!==null){var A=l.memoizedProps;if(me(A,_)&&l.ref===u.ref)if(Yi=!1,u.pendingProps=_=A,zy(l,M))l.flags&131072&&(Yi=!0);else return u.lanes=l.lanes,fo(l,u,M)}return Ny(l,u,p,_,M)}function QA(l,u,p){var _=u.pendingProps,M=_.children,A=(u.stateNode._pendingVisibility&2)!==0,F=l!==null?l.memoizedState:null;if(ap(l,u),_.mode==="hidden"||A){if(u.flags&128){if(_=F!==null?F.baseLanes|p:p,l!==null){for(M=u.child=l.child,A=0;M!==null;)A=A|M.lanes|M.childLanes,M=M.sibling;u.childLanes=A&~_}else u.childLanes=0,u.child=null;return JA(l,u,_,p)}if(p&536870912)u.memoizedState={baseLanes:0,cachePool:null},l!==null&&tg(u,F!==null?F.cachePool:null),F!==null?uo(u,F):Is(),Ps(u);else return u.lanes=u.childLanes=536870912,JA(l,u,F!==null?F.baseLanes|p:p,p)}else F!==null?(tg(u,F.cachePool),uo(u,F),fa(),u.memoizedState=null):(l!==null&&tg(u,null),Is(),fa());return aa(l,u,M,p),u.child}function JA(l,u,p,_){var M=Gy();return M=M===null?null:{parent:vo?di._currentValue:di._currentValue2,pool:M},u.memoizedState={baseLanes:p,cachePool:M},l!==null&&tg(u,null),Is(),Ps(u),l!==null&&rp(l,u,_,!0),null}function ap(l,u){var p=u.ref;if(p===null)l!==null&&l.ref!==null&&(u.flags|=2097664);else{if(typeof p!="function"&&typeof p!="object")throw Error(a(284));(l===null||l.ref!==p)&&(u.flags|=2097664)}}function Ny(l,u,p,_,M){return Nc(u),p=zs(l,u,p,_,void 0,M),_=da(),l!==null&&!Yi?(R(l,u,M),fo(l,u,M)):(pn&&_&&Xe(u),u.flags|=1,aa(l,u,p,M),u.child)}function $A(l,u,p,_,M,A){return Nc(u),u.updateQueue=null,p=ho(u,_,p,M),Bs(l),_=da(),l!==null&&!Yi?(R(l,u,A),fo(l,u,A)):(pn&&_&&Xe(u),u.flags|=1,aa(l,u,p,A),u.child)}function ew(l,u,p,_,M){if(Nc(u),u.stateNode===null){var A=wh,F=p.contextType;typeof F=="object"&&F!==null&&(A=pa(F)),A=new p(_,A),u.memoizedState=A.state!==null&&A.state!==void 0?A.state:null,A.updater=IS,u.stateNode=A,A._reactInternals=u,A=u.stateNode,A.props=_,A.state=u.memoizedState,A.refs={},_t(u),F=p.contextType,A.context=typeof F=="object"&&F!==null?pa(F):wh,A.state=u.memoizedState,F=p.getDerivedStateFromProps,typeof F=="function"&&(Ry(u,p,F,_),A.state=u.memoizedState),typeof p.getDerivedStateFromProps=="function"||typeof A.getSnapshotBeforeUpdate=="function"||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(F=A.state,typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount(),F!==A.state&&IS.enqueueReplaceState(A,A.state,null),Oe(u,_,A,M),pe(),A.state=u.memoizedState),typeof A.componentDidMount=="function"&&(u.flags|=4194308),_=!0}else if(l===null){A=u.stateNode;var $=u.memoizedProps,he=Cc(p,$);A.props=he;var Ne=A.context,et=p.contextType;F=wh,typeof et=="object"&&et!==null&&(F=pa(et));var dt=p.getDerivedStateFromProps;et=typeof dt=="function"||typeof A.getSnapshotBeforeUpdate=="function",$=u.pendingProps!==$,et||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||($||Ne!==F)&&WA(u,A,_,F),yl=!1;var mt=u.memoizedState;A.state=mt,Oe(u,_,A,M),pe(),Ne=u.memoizedState,$||mt!==Ne||yl?(typeof dt=="function"&&(Ry(u,p,dt,_),Ne=u.memoizedState),(he=yl||kA(u,p,he,_,mt,Ne,F))?(et||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount()),typeof A.componentDidMount=="function"&&(u.flags|=4194308)):(typeof A.componentDidMount=="function"&&(u.flags|=4194308),u.memoizedProps=_,u.memoizedState=Ne),A.props=_,A.state=Ne,A.context=F,_=he):(typeof A.componentDidMount=="function"&&(u.flags|=4194308),_=!1)}else{A=u.stateNode,pt(l,u),F=u.memoizedProps,et=Cc(p,F),A.props=et,dt=u.pendingProps,mt=A.context,Ne=p.contextType,he=wh,typeof Ne=="object"&&Ne!==null&&(he=pa(Ne)),$=p.getDerivedStateFromProps,(Ne=typeof $=="function"||typeof A.getSnapshotBeforeUpdate=="function")||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(F!==dt||mt!==he)&&WA(u,A,_,he),yl=!1,mt=u.memoizedState,A.state=mt,Oe(u,_,A,M),pe();var qt=u.memoizedState;F!==dt||mt!==qt||yl||l!==null&&l.dependencies!==null&&$0(l.dependencies)?(typeof $=="function"&&(Ry(u,p,$,_),qt=u.memoizedState),(et=yl||kA(u,p,et,_,mt,qt,he)||l!==null&&l.dependencies!==null&&$0(l.dependencies))?(Ne||typeof A.UNSAFE_componentWillUpdate!="function"&&typeof A.componentWillUpdate!="function"||(typeof A.componentWillUpdate=="function"&&A.componentWillUpdate(_,qt,he),typeof A.UNSAFE_componentWillUpdate=="function"&&A.UNSAFE_componentWillUpdate(_,qt,he)),typeof A.componentDidUpdate=="function"&&(u.flags|=4),typeof A.getSnapshotBeforeUpdate=="function"&&(u.flags|=1024)):(typeof A.componentDidUpdate!="function"||F===l.memoizedProps&&mt===l.memoizedState||(u.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===l.memoizedProps&&mt===l.memoizedState||(u.flags|=1024),u.memoizedProps=_,u.memoizedState=qt),A.props=_,A.state=qt,A.context=he,_=et):(typeof A.componentDidUpdate!="function"||F===l.memoizedProps&&mt===l.memoizedState||(u.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===l.memoizedProps&&mt===l.memoizedState||(u.flags|=1024),_=!1)}return A=_,ap(l,u),_=(u.flags&128)!==0,A||_?(A=u.stateNode,p=_&&typeof p.getDerivedStateFromError!="function"?null:A.render(),u.flags|=1,l!==null&&_?(u.child=Bc(u,l.child,null,M),u.child=Bc(u,null,p,M)):aa(l,u,p,M),u.memoizedState=A.state,l=u.child):l=fo(l,u,M),l}function tw(l,u,p,_){return ot(),u.flags|=256,aa(l,u,p,_),u.child}function Dy(l){return{baseLanes:l,cachePool:ow()}}function Oy(l,u,p){return l=l!==null?l.childLanes&~p:0,u&&(l|=Gr),l}function nw(l,u,p){var _=u.pendingProps,M=!1,A=(u.flags&128)!==0,F;if((F=A)||(F=l!==null&&l.memoizedState===null?!1:(Hi.current&2)!==0),F&&(M=!0,u.flags&=-129),F=(u.flags&32)!==0,u.flags&=-33,l===null){if(pn){if(M?bi(u):fa(),pn){var $=va,he;(he=$)&&($=N7($,Hs),$!==null?(u.memoizedState={dehydrated:$,treeContext:zc!==null?{id:_o,overflow:xo}:null,retryLane:536870912},he=t(18,null,null,0),he.stateNode=$,he.return=u,u.child=he,ba=u,va=null,he=!0):he=!1),he||Ze(u)}if($=u.memoizedState,$!==null&&($=$.dehydrated,$!==null))return SS($)?u.lanes=16:u.lanes=536870912,null;Xi(u)}return $=_.children,_=_.fallback,M?(fa(),M=u.mode,$=Iy({mode:"hidden",children:$},M),_=Ic(_,M,p,null),$.return=u,_.return=u,$.sibling=_,u.child=$,M=u.child,M.memoizedState=Dy(p),M.childLanes=Oy(l,F,p),u.memoizedState=US,_):(bi(u),Ly(u,$))}if(he=l.memoizedState,he!==null&&($=he.dehydrated,$!==null)){if(A)u.flags&256?(bi(u),u.flags&=-257,u=Uy(l,u,p)):u.memoizedState!==null?(fa(),u.child=l.child,u.flags|=128,u=null):(fa(),M=_.fallback,$=u.mode,_=Iy({mode:"visible",children:_.children},$),M=Ic(M,$,p,null),M.flags|=2,_.return=u,M.return=u,_.sibling=M,u.child=_,Bc(u,l.child,null,p),_=u.child,_.memoizedState=Dy(p),_.childLanes=Oy(l,F,p),u.memoizedState=US,u=M);else if(bi(u),SS($))F=T7($).digest,_=Error(a(419)),_.stack="",_.digest=F,Ke({value:_,source:null,stack:null}),u=Uy(l,u,p);else if(Yi||rp(l,u,p,!1),F=(p&l.childLanes)!==0,Yi||F){if(F=Vn,F!==null){if(_=p&-p,_&42)_=1;else switch(_){case 2:_=1;break;case 8:_=4;break;case 32:_=16;break;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:case 4194304:case 8388608:case 16777216:case 33554432:_=64;break;case 268435456:_=134217728;break;default:_=0}if(_=_&(F.suspendedLanes|p)?0:_,_!==0&&_!==he.retryLane)throw he.retryLane=_,De(l,_),Ma(F,l,_),DR}yS($)||iS(),u=Uy(l,u,p)}else yS($)?(u.flags|=128,u.child=l.child,u=b9.bind(null,l),E7($,u),u=null):(l=he.treeContext,Ur&&(va=w7($),ba=u,pn=!0,fs=null,Hs=!1,l!==null&&(zr[Br++]=_o,zr[Br++]=xo,zr[Br++]=zc,_o=l.id,xo=l.overflow,zc=u)),u=Ly(u,_.children),u.flags|=4096);return u}return M?(fa(),M=_.fallback,$=u.mode,he=l.child,A=he.sibling,_=ml(he,{mode:"hidden",children:_.children}),_.subtreeFlags=he.subtreeFlags&31457280,A!==null?M=ml(A,M):(M=Ic(M,$,p,null),M.flags|=2),M.return=u,_.return=u,_.sibling=M,u.child=_,_=M,M=u.child,$=l.child.memoizedState,$===null?$=Dy(p):(he=$.cachePool,he!==null?(A=vo?di._currentValue:di._currentValue2,he=he.parent!==A?{parent:A,pool:A}:he):he=ow(),$={baseLanes:$.baseLanes|p,cachePool:he}),M.memoizedState=$,M.childLanes=Oy(l,F,p),u.memoizedState=US,_):(bi(u),p=l.child,l=p.sibling,p=ml(p,{mode:"visible",children:_.children}),p.return=u,p.sibling=null,l!==null&&(F=u.deletions,F===null?(u.deletions=[l],u.flags|=16):F.push(l)),u.child=p,u.memoizedState=null,p)}function Ly(l,u){return u=Iy({mode:"visible",children:u},l.mode),u.return=l,l.child=u}function Iy(l,u){return Yw(l,u,0,null)}function Uy(l,u,p){return Bc(u,l.child,null,p),l=Ly(u,u.pendingProps.children),l.flags|=2,u.memoizedState=null,l}function iw(l,u,p){l.lanes|=u;var _=l.alternate;_!==null&&(_.lanes|=u),By(l.return,u,p)}function Py(l,u,p,_,M){var A=l.memoizedState;A===null?l.memoizedState={isBackwards:u,rendering:null,renderingStartTime:0,last:_,tail:p,tailMode:M}:(A.isBackwards=u,A.rendering=null,A.renderingStartTime=0,A.last=_,A.tail=p,A.tailMode=M)}function aw(l,u,p){var _=u.pendingProps,M=_.revealOrder,A=_.tail;if(aa(l,u,_.children,p),_=Hi.current,_&2)_=_&1|2,u.flags|=128;else{if(l!==null&&l.flags&128)e:for(l=u.child;l!==null;){if(l.tag===13)l.memoizedState!==null&&iw(l,p,u);else if(l.tag===19)iw(l,p,u);else if(l.child!==null){l.child.return=l,l=l.child;continue}if(l===u)break e;for(;l.sibling===null;){if(l.return===null||l.return===u)break e;l=l.return}l.sibling.return=l.return,l=l.sibling}_&=1}switch(S(Hi,_),M){case"forwards":for(p=u.child,M=null;p!==null;)l=p.alternate,l!==null&&Fa(l)===null&&(M=p),p=p.sibling;p=M,p===null?(M=u.child,u.child=null):(M=p.sibling,p.sibling=null),Py(u,!1,M,p,A);break;case"backwards":for(p=null,M=u.child,u.child=null;M!==null;){if(l=M.alternate,l!==null&&Fa(l)===null){u.child=M;break}l=M.sibling,M.sibling=p,p=M,M=l}Py(u,!0,p,null,A);break;case"together":Py(u,!1,null,null,void 0);break;default:u.memoizedState=null}return u.child}function fo(l,u,p){if(l!==null&&(u.dependencies=l.dependencies),El|=u.lanes,!(p&u.childLanes))if(l!==null){if(rp(l,u,p,!1),(p&u.childLanes)===0)return null}else return null;if(l!==null&&u.child!==l.child)throw Error(a(153));if(u.child!==null){for(l=u.child,p=ml(l,l.pendingProps),u.child=p,p.return=u;l.sibling!==null;)l=l.sibling,p=p.sibling=ml(l,l.pendingProps),p.return=u;p.sibling=null}return u.child}function zy(l,u){return l.lanes&u?!0:(l=l.dependencies,!!(l!==null&&$0(l)))}function p9(l,u,p){switch(u.tag){case 3:tt(u,u.stateNode.containerInfo),hl(u,di,l.memoizedState.cache),ot();break;case 27:case 5:ge(u);break;case 4:tt(u,u.stateNode.containerInfo);break;case 10:hl(u,u.type,u.memoizedProps.value);break;case 13:var _=u.memoizedState;if(_!==null)return _.dehydrated!==null?(bi(u),u.flags|=128,null):p&u.child.childLanes?nw(l,u,p):(bi(u),l=fo(l,u,p),l!==null?l.sibling:null);bi(u);break;case 19:var M=(l.flags&128)!==0;if(_=(p&u.childLanes)!==0,_||(rp(l,u,p,!1),_=(p&u.childLanes)!==0),M){if(_)return aw(l,u,p);u.flags|=128}if(M=u.memoizedState,M!==null&&(M.rendering=null,M.tail=null,M.lastEffect=null),S(Hi,Hi.current),_)break;return null;case 22:case 23:return u.lanes=0,QA(l,u,p);case 24:hl(u,di,l.memoizedState.cache)}return fo(l,u,p)}function rw(l,u,p){if(l!==null)if(l.memoizedProps!==u.pendingProps)Yi=!0;else{if(!zy(l,p)&&!(u.flags&128))return Yi=!1,p9(l,u,p);Yi=!!(l.flags&131072)}else Yi=!1,pn&&u.flags&1048576&&Ce(u,pg,u.index);switch(u.lanes=0,u.tag){case 16:e:{l=u.pendingProps;var _=u.elementType,M=_._init;if(_=M(_._payload),u.type=_,typeof _=="function")sS(_)?(l=Cc(_,l),u.tag=1,u=ew(null,u,_,l,p)):(u.tag=0,u=Ny(null,u,_,l,p));else{if(_!=null){if(M=_.$$typeof,M===fS){u.tag=11,u=jA(null,u,_,l,p);break e}else if(M===mS){u.tag=14,u=ZA(null,u,_,l,p);break e}}throw u=s(_)||_,Error(a(306,u,""))}}return u;case 0:return Ny(l,u,u.type,u.pendingProps,p);case 1:return _=u.type,M=Cc(_,u.pendingProps),ew(l,u,_,M,p);case 3:e:{if(tt(u,u.stateNode.containerInfo),l===null)throw Error(a(387));var A=u.pendingProps;M=u.memoizedState,_=M.element,pt(l,u),Oe(u,A,null,p);var F=u.memoizedState;if(A=F.cache,hl(u,di,A),A!==M.cache&&Hy(u,[di],p,!0),pe(),A=F.element,Ur&&M.isDehydrated)if(M={element:A,isDehydrated:!1,cache:F.cache},u.updateQueue.baseState=M,u.memoizedState=M,u.flags&256){u=tw(l,u,A,p);break e}else if(A!==_){_=oe(Error(a(424)),u),Ke(_),u=tw(l,u,A,p);break e}else for(Ur&&(va=A7(u.stateNode.containerInfo),ba=u,pn=!0,fs=null,Hs=!0),p=CR(u,null,A,p),u.child=p;p;)p.flags=p.flags&-3|4096,p=p.sibling;else{if(ot(),A===_){u=fo(l,u,p);break e}aa(l,u,A,p)}u=u.child}return u;case 26:if(Pr)return ap(l,u),l===null?(p=xR(u.type,null,u.pendingProps,null))?u.memoizedState=p:pn||(u.stateNode=V7(u.type,u.pendingProps,xl.current,u)):u.memoizedState=xR(u.type,l.memoizedProps,u.pendingProps,l.memoizedState),null;case 27:if(ga)return ge(u),l===null&&ga&&pn&&(_=u.stateNode=bR(u.type,u.pendingProps,xl.current,ra.current,!1),ba=u,Hs=!0,va=gR(_)),_=u.pendingProps.children,l!==null||pn?aa(l,u,_,p):u.child=Bc(u,null,_,p),ap(l,u),u.child;case 5:return l===null&&pn&&(H7(u.type,u.pendingProps,ra.current),(M=_=va)&&(_=R7(_,u.type,u.pendingProps,Hs),_!==null?(u.stateNode=_,ba=u,va=gR(_),Hs=!1,M=!0):M=!1),M||Ze(u)),ge(u),M=u.type,A=u.pendingProps,F=l!==null?l.memoizedProps:null,_=A.children,cg(M,A)?_=null:F!==null&&cg(M,F)&&(u.flags|=32),u.memoizedState!==null&&(M=zs(l,u,sr,null,null,p),vo?Pc._currentValue=M:Pc._currentValue2=M),ap(l,u),aa(l,u,_,p),u.child;case 6:return l===null&&pn&&(F7(u.pendingProps,ra.current),(l=p=va)&&(p=C7(p,u.pendingProps,Hs),p!==null?(u.stateNode=p,ba=u,va=null,l=!0):l=!1),l||Ze(u)),null;case 13:return nw(l,u,p);case 4:return tt(u,u.stateNode.containerInfo),_=u.pendingProps,l===null?u.child=Bc(u,null,_,p):aa(l,u,_,p),u.child;case 11:return jA(l,u,u.type,u.pendingProps,p);case 7:return aa(l,u,u.pendingProps,p),u.child;case 8:return aa(l,u,u.pendingProps.children,p),u.child;case 12:return aa(l,u,u.pendingProps.children,p),u.child;case 10:return _=u.pendingProps,hl(u,u.type,_.value),aa(l,u,_.children,p),u.child;case 9:return M=u.type._context,_=u.pendingProps.children,Nc(u),M=pa(M),_=_(M),u.flags|=1,aa(l,u,_,p),u.child;case 14:return ZA(l,u,u.type,u.pendingProps,p);case 15:return KA(l,u,u.type,u.pendingProps,p);case 19:return aw(l,u,p);case 22:return QA(l,u,p);case 24:return Nc(u),_=pa(di),l===null?(M=Gy(),M===null&&(M=Vn,A=Fy(),M.pooledCache=A,A.refCount++,A!==null&&(M.pooledCacheLanes|=p),M=A),u.memoizedState={parent:_,cache:M},_t(u),hl(u,di,M)):(l.lanes&p&&(pt(l,u),Oe(u,null,null,p),pe()),M=l.memoizedState,A=u.memoizedState,M.parent!==_?(M={parent:_,cache:_},u.memoizedState=M,u.lanes===0&&(u.memoizedState=u.updateQueue.baseState=M),hl(u,di,_)):(_=A.cache,hl(u,di,_),_!==M.cache&&Hy(u,[di],p,!0))),aa(l,u,u.pendingProps.children,p),u.child;case 29:throw u.pendingProps}throw Error(a(156,u.tag))}function hl(l,u,p){vo?(S(Tg,u._currentValue),u._currentValue=p):(S(Tg,u._currentValue2),u._currentValue2=p)}function po(l){var u=Tg.current;vo?l._currentValue=u:l._currentValue2=u,v(Tg)}function By(l,u,p){for(;l!==null;){var _=l.alternate;if((l.childLanes&u)!==u?(l.childLanes|=u,_!==null&&(_.childLanes|=u)):_!==null&&(_.childLanes&u)!==u&&(_.childLanes|=u),l===p)break;l=l.return}}function Hy(l,u,p,_){var M=l.child;for(M!==null&&(M.return=l);M!==null;){var A=M.dependencies;if(A!==null){var F=M.child;A=A.firstContext;e:for(;A!==null;){var $=A;A=M;for(var he=0;heTp&&(u.flags|=128,_=!0,op(M,!1),u.lanes=4194304)}else{if(!_)if(l=Fa(A),l!==null){if(u.flags|=128,_=!0,l=l.updateQueue,u.updateQueue=l,ng(u,l),op(M,!0),M.tail===null&&M.tailMode==="hidden"&&!A.alternate&&!pn)return ui(u),null}else 2*hs()-M.renderingStartTime>Tp&&p!==536870912&&(u.flags|=128,_=!0,op(M,!1),u.lanes=4194304);M.isBackwards?(A.sibling=u.child,u.child=A):(l=M.last,l!==null?l.sibling=A:u.child=A,M.last=A)}return M.tail!==null?(u=M.tail,M.rendering=u,M.tail=u.sibling,M.renderingStartTime=hs(),u.sibling=null,l=Hi.current,S(Hi,_?l&1|2:l&1),u):(ui(u),null);case 22:case 23:return Xi(u),Us(),_=u.memoizedState!==null,l!==null?l.memoizedState!==null!==_&&(u.flags|=8192):_&&(u.flags|=8192),_?p&536870912&&!(u.flags&128)&&(ui(u),u.subtreeFlags&6&&(u.flags|=8192)):ui(u),p=u.updateQueue,p!==null&&ng(u,p.retryQueue),p=null,l!==null&&l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(p=l.memoizedState.cachePool.pool),_=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(_=u.memoizedState.cachePool.pool),_!==p&&(u.flags|=2048),l!==null&&v(kc),null;case 24:return p=null,l!==null&&(p=l.memoizedState.cache),u.memoizedState.cache!==p&&(u.flags|=2048),po(di),ui(u),null;case 25:return null}throw Error(a(156,u.tag))}function g9(l,u){switch(nt(u),u.tag){case 1:return l=u.flags,l&65536?(u.flags=l&-65537|128,u):null;case 3:return po(di),gt(),l=u.flags,l&65536&&!(l&128)?(u.flags=l&-65537|128,u):null;case 26:case 27:case 5:return Ae(u),null;case 13:if(Xi(u),l=u.memoizedState,l!==null&&l.dehydrated!==null){if(u.alternate===null)throw Error(a(340));ot()}return l=u.flags,l&65536?(u.flags=l&-65537|128,u):null;case 19:return v(Hi),null;case 4:return gt(),null;case 10:return po(u.type),null;case 22:case 23:return Xi(u),Us(),l!==null&&v(kc),l=u.flags,l&65536?(u.flags=l&-65537|128,u):null;case 24:return po(di),null;case 25:return null;default:return null}}function fw(l,u){switch(nt(u),u.tag){case 3:po(di),gt();break;case 26:case 27:case 5:Ae(u);break;case 4:gt();break;case 13:Xi(u);break;case 19:v(Hi);break;case 10:po(u.type);break;case 22:case 23:Xi(u),Us(),l!==null&&v(kc);break;case 24:po(di)}}function lp(l,u){try{var p=u.updateQueue,_=p!==null?p.lastEffect:null;if(_!==null){var M=_.next;p=M;do{if((p.tag&l)===l){_=void 0;var A=p.create,F=p.inst;_=A(),F.destroy=_}p=p.next}while(p!==M)}}catch($){bn(u,u.return,$)}}function fl(l,u,p){try{var _=u.updateQueue,M=_!==null?_.lastEffect:null;if(M!==null){var A=M.next;_=A;do{if((_.tag&l)===l){var F=_.inst,$=F.destroy;if($!==void 0){F.destroy=void 0,M=u;var he=p;try{$()}catch(Ne){bn(M,he,Ne)}}}_=_.next}while(_!==A)}}catch(Ne){bn(u,u.return,Ne)}}function dw(l){var u=l.updateQueue;if(u!==null){var p=l.stateNode;try{Ve(u,p)}catch(_){bn(l,l.return,_)}}}function pw(l,u,p){p.props=Cc(l.type,l.memoizedProps),p.state=l.memoizedState;try{p.componentWillUnmount()}catch(_){bn(l,u,_)}}function Dc(l,u){try{var p=l.ref;if(p!==null){var _=l.stateNode;switch(l.tag){case 26:case 27:case 5:var M=hp(_);break;default:M=_}typeof p=="function"?l.refCleanup=p(M):p.current=M}}catch(A){bn(l,u,A)}}function lr(l,u){var p=l.ref,_=l.refCleanup;if(p!==null)if(typeof _=="function")try{_()}catch(M){bn(l,u,M)}finally{l.refCleanup=null,l=l.alternate,l!=null&&(l.refCleanup=null)}else if(typeof p=="function")try{p(null)}catch(M){bn(l,u,M)}else p.current=null}function mw(l){var u=l.type,p=l.memoizedProps,_=l.stateNode;try{c7(_,u,p,l)}catch(M){bn(l,l.return,M)}}function gw(l,u,p){try{u7(l.stateNode,l.type,p,u,l)}catch(_){bn(l,l.return,_)}}function vw(l){return l.tag===5||l.tag===3||(Pr?l.tag===26:!1)||(ga?l.tag===27:!1)||l.tag===4}function Xy(l){e:for(;;){for(;l.sibling===null;){if(l.return===null||vw(l.return))return null;l=l.return}for(l.sibling.return=l.return,l=l.sibling;l.tag!==5&&l.tag!==6&&(!ga||l.tag!==27)&&l.tag!==18;){if(l.flags&2||l.child===null||l.tag===4)continue e;l.child.return=l,l=l.child}if(!(l.flags&2))return l.stateNode}}function Yy(l,u,p){var _=l.tag;if(_===5||_===6)l=l.stateNode,u?f7(p,l,u):o7(p,l);else if(!(_===4||ga&&_===27)&&(l=l.child,l!==null))for(Yy(l,u,p),l=l.sibling;l!==null;)Yy(l,u,p),l=l.sibling}function ig(l,u,p){var _=l.tag;if(_===5||_===6)l=l.stateNode,u?h7(p,l,u):s7(p,l);else if(!(_===4||ga&&_===27)&&(l=l.child,l!==null))for(ig(l,u,p),l=l.sibling;l!==null;)ig(l,u,p),l=l.sibling}function _w(l,u,p){l=l.containerInfo;try{fR(l,p)}catch(_){bn(u,u.return,_)}}function v9(l,u){for(H9(l.containerInfo),qi=u;qi!==null;)if(l=qi,u=l.child,(l.subtreeFlags&1028)!==0&&u!==null)u.return=l,qi=u;else for(;qi!==null;){l=qi;var p=l.alternate;switch(u=l.flags,l.tag){case 0:break;case 11:case 15:break;case 1:if(u&1024&&p!==null){u=void 0;var _=l,M=p.memoizedProps;p=p.memoizedState;var A=_.stateNode;try{var F=Cc(_.type,M,_.elementType===_.type);u=A.getSnapshotBeforeUpdate(F,p),A.__reactInternalSnapshotBeforeUpdate=u}catch($){bn(_,_.return,$)}}break;case 3:u&1024&&ma&&x7(l.stateNode.containerInfo);break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if(u&1024)throw Error(a(163))}if(u=l.sibling,u!==null){u.return=l.return,qi=u;break}qi=l.return}return F=IR,IR=!1,F}function xw(l,u,p){var _=p.flags;switch(p.tag){case 0:case 11:case 15:mo(l,p),_&4&&lp(5,p);break;case 1:if(mo(l,p),_&4)if(l=p.stateNode,u===null)try{l.componentDidMount()}catch($){bn(p,p.return,$)}else{var M=Cc(p.type,u.memoizedProps);u=u.memoizedState;try{l.componentDidUpdate(M,u,l.__reactInternalSnapshotBeforeUpdate)}catch($){bn(p,p.return,$)}}_&64&&dw(p),_&512&&Dc(p,p.return);break;case 3:if(mo(l,p),_&64&&(_=p.updateQueue,_!==null)){if(l=null,p.child!==null)switch(p.child.tag){case 27:case 5:l=hp(p.child.stateNode);break;case 1:l=p.child.stateNode}try{Ve(_,l)}catch($){bn(p,p.return,$)}}break;case 26:if(Pr){mo(l,p),_&512&&Dc(p,p.return);break}case 27:case 5:mo(l,p),u===null&&_&4&&mw(p),_&512&&Dc(p,p.return);break;case 12:mo(l,p);break;case 13:mo(l,p),_&4&&Sw(l,p);break;case 22:if(M=p.memoizedState!==null||So,!M){u=u!==null&&u.memoizedState!==null||pi;var A=So,F=pi;So=M,(pi=u)&&!F?dl(l,p,(p.subtreeFlags&8772)!==0):mo(l,p),So=A,pi=F}_&512&&(p.memoizedProps.mode==="manual"?Dc(p,p.return):lr(p,p.return));break;default:mo(l,p)}}function yw(l){var u=l.alternate;u!==null&&(l.alternate=null,yw(u)),l.child=null,l.deletions=null,l.sibling=null,l.tag===5&&(u=l.stateNode,u!==null&&q9(u)),l.stateNode=null,l.return=null,l.dependencies=null,l.memoizedProps=null,l.memoizedState=null,l.pendingProps=null,l.stateNode=null,l.updateQueue=null}function us(l,u,p){for(p=p.child;p!==null;)qy(l,u,p),p=p.sibling}function qy(l,u,p){if(dr&&typeof dr.onCommitFiberUnmount=="function")try{dr.onCommitFiberUnmount(pp,p)}catch{}switch(p.tag){case 26:if(Pr){pi||lr(p,u),us(l,u,p),p.memoizedState?SR(p.memoizedState):p.stateNode&&ER(p.stateNode);break}case 27:if(ga){pi||lr(p,u);var _=Ri,M=mr;Ri=p.stateNode,us(l,u,p),j7(p.stateNode),Ri=_,mr=M;break}case 5:pi||lr(p,u);case 6:if(ma){if(_=Ri,M=mr,Ri=null,us(l,u,p),Ri=_,mr=M,Ri!==null)if(mr)try{p7(Ri,p.stateNode)}catch(A){bn(p,u,A)}else try{d7(Ri,p.stateNode)}catch(A){bn(p,u,A)}}else us(l,u,p);break;case 18:ma&&Ri!==null&&(mr?B7(Ri,p.stateNode):z7(Ri,p.stateNode));break;case 4:ma?(_=Ri,M=mr,Ri=p.stateNode.containerInfo,mr=!0,us(l,u,p),Ri=_,mr=M):(_l&&_w(p.stateNode,p,uR()),us(l,u,p));break;case 0:case 11:case 14:case 15:pi||fl(2,p,u),pi||fl(4,p,u),us(l,u,p);break;case 1:pi||(lr(p,u),_=p.stateNode,typeof _.componentWillUnmount=="function"&&pw(p,u,_)),us(l,u,p);break;case 21:us(l,u,p);break;case 22:pi||lr(p,u),pi=(_=pi)||p.memoizedState!==null,us(l,u,p),pi=_;break;default:us(l,u,p)}}function Sw(l,u){if(Ur&&u.memoizedState===null&&(l=u.alternate,l!==null&&(l=l.memoizedState,l!==null&&(l=l.dehydrated,l!==null))))try{P7(l)}catch(p){bn(u,u.return,p)}}function _9(l){switch(l.tag){case 13:case 19:var u=l.stateNode;return u===null&&(u=l.stateNode=new LR),u;case 22:return l=l.stateNode,u=l._retryCache,u===null&&(u=l._retryCache=new LR),u;default:throw Error(a(435,l.tag))}}function jy(l,u){var p=_9(l);u.forEach(function(_){var M=A9.bind(null,l,_);p.has(_)||(p.add(_),_.then(M,M))})}function Ga(l,u){var p=u.deletions;if(p!==null)for(var _=0;_";case Mg:return":has("+($y(l)||"")+")";case bg:return'[role="'+l.value+'"]';case wg:return'"'+l.value+'"';case Ag:return'[data-testname="'+l.value+'"]';default:throw Error(a(365))}}function Cw(l,u){var p=[];l=[l,0];for(var _=0;_p?32:p;p=Ft.T;var M=Uc();try{if(Va(_),Ft.T=null,Xc===null)var A=!1;else{_=VS,VS=null;var F=Xc,$=Ep;if(Xc=null,Ep=0,In&6)throw Error(a(331));var he=In;if(In|=4,ww(F.current),Mw(F,F.current,$,_),In=he,Je(0,!1),dr&&typeof dr.onPostCommitFiberRoot=="function")try{dr.onPostCommitFiberRoot(pp,F)}catch{}A=!0}return A}finally{Va(M),Ft.T=p,Vw(l,u)}}return!1}function kw(l,u,p){u=oe(p,u),u=Cy(l.stateNode,u,2),l=He(l,u,2),l!==null&&(B(l,2),$e(l))}function bn(l,u,p){if(l.tag===3)kw(l,l,p);else for(;u!==null;){if(u.tag===3){kw(u,l,p);break}else if(u.tag===1){var _=u.stateNode;if(typeof u.type.getDerivedStateFromError=="function"||typeof _.componentDidCatch=="function"&&(Ml===null||!Ml.has(_))){l=oe(p,l),p=YA(2),_=He(u,p,2),_!==null&&(qA(p,_,u,l),B(_,2),$e(_));break}}u=u.return}}function rS(l,u,p){var _=l.pingCache;if(_===null){_=l.pingCache=new cz;var M=new Set;_.set(u,M)}else M=_.get(u),M===void 0&&(M=new Set,_.set(u,M));M.has(p)||(zS=!0,M.add(p),l=M9.bind(null,l,u,p),u.then(l,l))}function M9(l,u,p){var _=l.pingCache;_!==null&&_.delete(u),l.pingedLanes|=l.suspendedLanes&p,l.warmLanes&=~p,Vn===l&&(hn&p)===p&&(mi===4||mi===3&&(hn&62914560)===hn&&300>hs()-FS?!(In&2)&&Sh(l,0):BS|=p,Vh===hn&&(Vh=0)),$e(l)}function Ww(l,u){u===0&&(u=O()),l=De(l,u),l!==null&&(B(l,u),$e(l))}function b9(l){var u=l.memoizedState,p=0;u!==null&&(p=u.retryLane),Ww(l,p)}function A9(l,u){var p=0;switch(l.tag){case 13:var _=l.stateNode,M=l.memoizedState;M!==null&&(p=M.retryLane);break;case 19:_=l.stateNode;break;case 22:_=l.stateNode._retryCache;break;default:throw Error(a(314))}_!==null&&_.delete(u),Ww(l,p)}function w9(l,u){return fg(l,u)}function R9(l,u,p,_){this.tag=l,this.key=p,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=u,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=_,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function sS(l){return l=l.prototype,!(!l||!l.isReactComponent)}function ml(l,u){var p=l.alternate;return p===null?(p=t(l.tag,u,l.key,l.mode),p.elementType=l.elementType,p.type=l.type,p.stateNode=l.stateNode,p.alternate=l,l.alternate=p):(p.pendingProps=u,p.type=l.type,p.flags=0,p.subtreeFlags=0,p.deletions=null),p.flags=l.flags&31457280,p.childLanes=l.childLanes,p.lanes=l.lanes,p.child=l.child,p.memoizedProps=l.memoizedProps,p.memoizedState=l.memoizedState,p.updateQueue=l.updateQueue,u=l.dependencies,p.dependencies=u===null?null:{lanes:u.lanes,firstContext:u.firstContext},p.sibling=l.sibling,p.index=l.index,p.ref=l.ref,p.refCleanup=l.refCleanup,p}function Xw(l,u){l.flags&=31457282;var p=l.alternate;return p===null?(l.childLanes=0,l.lanes=u,l.child=null,l.subtreeFlags=0,l.memoizedProps=null,l.memoizedState=null,l.updateQueue=null,l.dependencies=null,l.stateNode=null):(l.childLanes=p.childLanes,l.lanes=p.lanes,l.child=p.child,l.subtreeFlags=0,l.deletions=null,l.memoizedProps=p.memoizedProps,l.memoizedState=p.memoizedState,l.updateQueue=p.updateQueue,l.type=p.type,u=p.dependencies,l.dependencies=u===null?null:{lanes:u.lanes,firstContext:u.firstContext}),l}function sg(l,u,p,_,M,A){var F=0;if(_=l,typeof l=="function")sS(l)&&(F=1);else if(typeof l=="string")F=Pr&&ga?_R(l,p,ra.current)?26:AR(l)?27:5:Pr?_R(l,p,ra.current)?26:5:ga&&AR(l)?27:5;else e:switch(l){case Mh:return Ic(p.children,M,A,u);case Jw:F=8,M|=24;break;case hS:return l=t(12,p,u,M|2),l.elementType=hS,l.lanes=A,l;case dS:return l=t(13,p,u,M),l.elementType=dS,l.lanes=A,l;case pS:return l=t(19,p,u,M),l.elementType=pS,l.lanes=A,l;case eR:return Yw(p,M,A,u);default:if(typeof l=="object"&&l!==null)switch(l.$$typeof){case O9:case gl:F=10;break e;case $w:F=9;break e;case fS:F=11;break e;case mS:F=14;break e;case vl:F=16,_=null;break e}F=29,p=Error(a(130,l===null?"null":typeof l,"")),_=null}return u=t(F,p,u,M),u.elementType=l,u.type=_,u.lanes=A,u}function Ic(l,u,p,_){return l=t(7,l,_,u),l.lanes=p,l}function Yw(l,u,p,_){l=t(22,l,_,u),l.elementType=eR,l.lanes=p;var M={_visibility:1,_pendingVisibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null,_current:null,detach:function(){var A=M._current;if(A===null)throw Error(a(456));if(!(M._pendingVisibility&2)){var F=De(A,2);F!==null&&(M._pendingVisibility|=2,Ma(F,A,2))}},attach:function(){var A=M._current;if(A===null)throw Error(a(456));if(M._pendingVisibility&2){var F=De(A,2);F!==null&&(M._pendingVisibility&=-3,Ma(F,A,2))}}};return l.stateNode=M,l}function oS(l,u,p){return l=t(6,l,null,u),l.lanes=p,l}function lS(l,u,p){return u=t(4,l.children!==null?l.children:[],l.key,u),u.lanes=p,u.stateNode={containerInfo:l.containerInfo,pendingChildren:null,implementation:l.implementation},u}function C9(l,u,p,_,M,A,F,$){this.tag=1,this.containerInfo=l,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=xS,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=w(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.finishedLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=w(0),this.hiddenUpdates=w(null),this.identifierPrefix=_,this.onUncaughtError=M,this.onCaughtError=A,this.onRecoverableError=F,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=$,this.incompleteTransitions=new Map}function qw(l,u,p,_,M,A,F,$,he,Ne,et,dt){return l=new C9(l,u,p,F,$,he,Ne,dt),u=1,A===!0&&(u|=24),A=t(3,null,null,u),l.current=A,A.stateNode=l,u=Fy(),u.refCount++,l.pooledCache=u,u.refCount++,A.memoizedState={element:_,isDehydrated:p,cache:u},_t(A),l}function jw(l){return l?(l=wh,l):wh}function Zw(l){var u=l._reactInternals;if(u===void 0)throw typeof l.render=="function"?Error(a(188)):(l=Object.keys(l).join(","),Error(a(268,l)));return l=g(u),l=l!==null?x(l):null,l===null?null:hp(l.stateNode)}function Kw(l,u,p,_,M,A){M=jw(M),_.context===null?_.context=M:_.pendingContext=M,_=Ie(u),_.payload={element:p},A=A===void 0?null:A,A!==null&&(_.callback=A),p=He(l,_,u),p!==null&&(Ma(p,l,u),ht(p,l,u))}function Qw(l,u){if(l=l.memoizedState,l!==null&&l.dehydrated!==null){var p=l.retryLane;l.retryLane=p!==0&&p=Ne&&A>=dt&&M<=et&&F<=mt){l.splice(u,1);break}else if(_!==Ne||p.width!==he.width||mtF){if(!(A!==dt||p.height!==he.height||et<_||Ne>M)){Ne>_&&(he.width+=Ne-_,he.x=_),etA&&(he.height+=dt-A,he.y=A),mtp&&(p=$)),$ ")+` - -No matching component was found for: - `)+l.join(" > ")}return null},tn.getPublicRootInstance=function(l){if(l=l.current,!l.child)return null;switch(l.child.tag){case 27:case 5:return hp(l.child.stateNode);default:return l.child.stateNode}},tn.injectIntoDevTools=function(){var l={bundleType:0,version:U9,rendererPackageName:P9,currentDispatcherRef:Ft,findFiberByHostInstance:sR,reconcilerVersion:"19.0.0"};if(iR!==null&&(l.rendererConfig=iR),typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")l=!1;else{var u=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(u.isDisabled||!u.supportsFiber)l=!0;else{try{pp=u.inject(l),dr=u}catch{}l=!!u.checkDCE}}return l},tn.isAlreadyRendering=function(){return!1},tn.observeVisibleRects=function(l,u,p,_){if(!fp)throw Error(a(363));l=eS(l,u);var M=r7(l,p,_).disconnect;return{disconnect:function(){M()}}},tn.shouldError=function(){return null},tn.shouldSuspend=function(){return!1},tn.startHostTransition=function(l,u,p,_){if(l.tag!==5)throw Error(a(476));var M=zA(l).queue;PA(l,M,u,bh,p===null?i:function(){var A=zA(l).next.queue;return ip(l,A,{},ur()),p(_)})},tn.updateContainer=function(l,u,p,_){var M=u.current,A=ur();return Kw(M,A,l,u,p,_),A},tn.updateContainerSync=function(l,u,p,_){return u.tag===0&&Lc(),Kw(u.current,2,l,u,p,_),2},tn},n.exports.default=n.exports,Object.defineProperty(n.exports,"__esModule",{value:!0})})(j6);var qj=j6.exports;q6.exports=qj;var jj=q6.exports;const Zj=l1(jj);function eA(n,e,t){if(!n)return;if(t(n)===!0)return n;let i=e?n.return:n.child;for(;i;){const a=eA(i,e,t);if(a)return a;i=e?null:i.sibling}}function Q6(n){try{return Object.defineProperties(n,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return n}}const tA=Q6(Me.createContext(null));let J6=class extends Me.Component{render(){return Me.createElement(tA.Provider,{value:this._reactInternals},this.props.children)}};function $6(){const n=Me.useContext(tA);if(n===null)throw new Error("its-fine: useFiber must be called within a !");const e=Me.useId();return Me.useMemo(()=>{for(const t of[n,n==null?void 0:n.alternate]){if(!t)continue;const i=eA(t,!1,a=>{let r=a.memoizedState;for(;r;){if(r.memoizedState===e)return!0;r=r.next}});if(i)return i}},[n,e])}const Kj=Symbol.for("react.context"),Qj=n=>n!==null&&typeof n=="object"&&"$$typeof"in n&&n.$$typeof===Kj;function Jj(){const n=$6(),[e]=Me.useState(()=>new Map);e.clear();let t=n;for(;t;){const i=t.type;Qj(i)&&i!==tA&&!e.has(i)&&e.set(i,Me.use(Q6(i))),t=t.return}return e}function $j(){const n=Jj();return Me.useMemo(()=>Array.from(n.keys()).reduce((e,t)=>i=>Me.createElement(e,null,Me.createElement(t.Provider,{...i,value:n.get(t)})),e=>Me.createElement(J6,{...e})),[n])}function e8(n){let e=n.root;for(;e.getState().previousRoot;)e=e.getState().previousRoot;return e}const t8=n=>n&&n.isOrthographicCamera,eZ=n=>n&&n.hasOwnProperty("current"),tZ=n=>n!=null&&(typeof n=="string"||typeof n=="number"||n.isColor),k0=((n,e)=>typeof window<"u"&&(((n=window.document)==null?void 0:n.createElement)||((e=window.navigator)==null?void 0:e.product)==="ReactNative"))()?Me.useLayoutEffect:Me.useEffect;function n8(n){const e=Me.useRef(n);return k0(()=>void(e.current=n),[n]),e}function nZ(){const n=$6(),e=$j();return Me.useMemo(()=>({children:t})=>{const a=!!eA(n,!0,r=>r.type===Me.StrictMode)?Me.StrictMode:Me.Fragment;return Rt.jsx(a,{children:Rt.jsx(e,{children:t})})},[n,e])}function iZ({set:n}){return k0(()=>(n(new Promise(()=>null)),()=>n(!1)),[n]),null}const aZ=(n=>(n=class extends Me.Component{constructor(...t){super(...t),this.state={error:!1}}componentDidCatch(t){this.props.set(t)}render(){return this.state.error?null:this.props.children}},n.getDerivedStateFromError=()=>({error:!0}),n))();function i8(n){var e;const t=typeof window<"u"?(e=window.devicePixelRatio)!=null?e:2:1;return Array.isArray(n)?Math.min(Math.max(n[0],t),n[1]):n}function df(n){var e;return(e=n.__r3f)==null?void 0:e.root.getState()}const ri={obj:n=>n===Object(n)&&!ri.arr(n)&&typeof n!="function",fun:n=>typeof n=="function",str:n=>typeof n=="string",num:n=>typeof n=="number",boo:n=>typeof n=="boolean",und:n=>n===void 0,nul:n=>n===null,arr:n=>Array.isArray(n),equ(n,e,{arrays:t="shallow",objects:i="reference",strict:a=!0}={}){if(typeof n!=typeof e||!!n!=!!e)return!1;if(ri.str(n)||ri.num(n)||ri.boo(n))return n===e;const r=ri.obj(n);if(r&&i==="reference")return n===e;const s=ri.arr(n);if(s&&t==="reference")return n===e;if((s||r)&&n===e)return!0;let o;for(o in n)if(!(o in e))return!1;if(r&&t==="shallow"&&i==="shallow"){for(o in a?e:n)if(!ri.equ(n[o],e[o],{strict:a,objects:"reference"}))return!1}else for(o in a?e:n)if(n[o]!==e[o])return!1;if(ri.und(o)){if(s&&n.length===0&&e.length===0||r&&Object.keys(n).length===0&&Object.keys(e).length===0)return!0;if(n!==e)return!1}return!0}};function rZ(n){const e={nodes:{},materials:{},meshes:{}};return n&&n.traverse(t=>{t.name&&(e.nodes[t.name]=t),t.material&&!e.materials[t.material.name]&&(e.materials[t.material.name]=t.material),t.isMesh&&!e.meshes[t.name]&&(e.meshes[t.name]=t)}),e}function sZ(n){n.type!=="Scene"&&(n.dispose==null||n.dispose());for(const e in n){const t=n[e];(t==null?void 0:t.type)!=="Scene"&&(t==null||t.dispose==null||t.dispose())}}const a8=["children","key","ref"];function oZ(n){const e={};for(const t in n)a8.includes(t)||(e[t]=n[t]);return e}function Gx(n,e,t,i){const a=n;let r=a==null?void 0:a.__r3f;return r||(r={root:e,type:t,parent:null,children:[],props:oZ(i),object:a,eventCount:0,handlers:{},isHidden:!1},a&&(a.__r3f=r)),r}function g0(n,e){if(!e.includes("-"))return{root:n,key:e,target:n[e]};if(e in n)return{root:n,key:e,target:n[e]};let t=n;const i=e.split("-");for(const a of i){if(typeof t!="object"||t===null){if(t!==void 0){const r=i.slice(i.indexOf(a)).join("-");return{root:t,key:r,target:void 0}}return{root:n,key:e,target:void 0}}e=a,n=t,t=t[e]}return{root:n,key:e,target:t}}const FN=/-\d+$/;function Vx(n,e){if(ri.str(e.props.attach)){if(FN.test(e.props.attach)){const a=e.props.attach.replace(FN,""),{root:r,key:s}=g0(n.object,a);Array.isArray(r[s])||(r[s]=[])}const{root:t,key:i}=g0(n.object,e.props.attach);e.previousAttach=t[i],t[i]=e.object}else ri.fun(e.props.attach)&&(e.previousAttach=e.props.attach(n.object,e.object))}function kx(n,e){if(ri.str(e.props.attach)){const{root:t,key:i}=g0(n.object,e.props.attach),a=e.previousAttach;a===void 0?delete t[i]:t[i]=a}else e.previousAttach==null||e.previousAttach(n.object,e.object);delete e.previousAttach}const xE=[...a8,"args","dispose","attach","object","onUpdate","dispose"],GN=new Map;function lZ(n){let e=GN.get(n.constructor);try{e||(e=new n.constructor,GN.set(n.constructor,e))}catch{}return e}function cZ(n,e){const t={};for(const i in e)if(!xE.includes(i)&&!ri.equ(e[i],n.props[i])){t[i]=e[i];for(const a in e)a.startsWith(`${i}-`)&&(t[a]=e[a])}for(const i in n.props){if(xE.includes(i)||e.hasOwnProperty(i))continue;const{root:a,key:r}=g0(n.object,i);if(a.constructor&&a.constructor.length===0){const s=lZ(a);ri.und(s)||(t[r]=s[r])}else t[r]=0}return t}const uZ=["map","emissiveMap","sheenColorMap","specularColorMap","envMap"],hZ=/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/;function Yl(n,e){var t;const i=n.__r3f,a=i&&e8(i).getState(),r=i==null?void 0:i.eventCount;for(const o in e){let c=e[o];if(xE.includes(o))continue;if(i&&hZ.test(o)){typeof c=="function"?i.handlers[o]=c:delete i.handlers[o],i.eventCount=Object.keys(i.handlers).length;continue}if(c===void 0)continue;let{root:h,key:f,target:d}=g0(n,o);if(d===void 0&&(typeof h!="object"||h===null))throw Error(`R3F: Cannot set "${o}". Ensure it is an object before setting "${f}".`);if(d instanceof Ad&&c instanceof Ad)d.mask=c.mask;else if(d instanceof je&&tZ(c))d.set(c);else if(d!==null&&typeof d=="object"&&typeof d.set=="function"&&typeof d.copy=="function"&&c!=null&&c.constructor&&d.constructor===c.constructor)d.copy(c);else if(d!==null&&typeof d=="object"&&typeof d.set=="function"&&Array.isArray(c))typeof d.fromArray=="function"?d.fromArray(c):d.set(...c);else if(d!==null&&typeof d=="object"&&typeof d.set=="function"&&typeof c=="number")typeof d.setScalar=="function"?d.setScalar(c):d.set(c);else{var s;h[f]=c,a&&!a.linear&&uZ.includes(f)&&(s=h[f])!=null&&s.isTexture&&h[f].format===$n&&h[f].type===zi&&(h[f].colorSpace=En)}}if(i!=null&&i.parent&&a!=null&&a.internal&&(t=i.object)!=null&&t.isObject3D&&r!==i.eventCount){const o=i.object,c=a.internal.interaction.indexOf(o);c>-1&&a.internal.interaction.splice(c,1),i.eventCount&&o.raycast!==null&&a.internal.interaction.push(o)}return i&&i.props.attach===void 0&&(i.object.isBufferGeometry?i.props.attach="geometry":i.object.isMaterial&&(i.props.attach="material")),i&&Zd(i),n}function Zd(n){var e;if(!n.parent)return;n.props.onUpdate==null||n.props.onUpdate(n.object);const t=(e=n.root)==null||e.getState==null?void 0:e.getState();t&&t.internal.frames===0&&t.invalidate()}function fZ(n,e){n.manual||(t8(n)?(n.left=e.width/-2,n.right=e.width/2,n.top=e.height/2,n.bottom=e.height/-2):n.aspect=e.width/e.height,n.updateProjectionMatrix())}const Ca=n=>n==null?void 0:n.isObject3D;function Pv(n){return(n.eventObject||n.object).uuid+"/"+n.index+n.instanceId}function r8(n,e,t,i){const a=t.get(e);a&&(t.delete(e),t.size===0&&(n.delete(i),a.target.releasePointerCapture(i)))}function dZ(n,e){const{internal:t}=n.getState();t.interaction=t.interaction.filter(i=>i!==e),t.initialHits=t.initialHits.filter(i=>i!==e),t.hovered.forEach((i,a)=>{(i.eventObject===e||i.object===e)&&t.hovered.delete(a)}),t.capturedMap.forEach((i,a)=>{r8(t.capturedMap,e,i,a)})}function pZ(n){function e(c){const{internal:h}=n.getState(),f=c.offsetX-h.initialClick[0],d=c.offsetY-h.initialClick[1];return Math.round(Math.sqrt(f*f+d*d))}function t(c){return c.filter(h=>["Move","Over","Enter","Out","Leave"].some(f=>{var d;return(d=h.__r3f)==null?void 0:d.handlers["onPointer"+f]}))}function i(c,h){const f=n.getState(),d=new Set,m=[],g=h?h(f.internal.interaction):f.internal.interaction;for(let v=0;v{const E=df(v.object),b=df(S.object);return!E||!b?v.distance-S.distance:b.events.priority-E.events.priority||v.distance-S.distance}).filter(v=>{const S=Pv(v);return d.has(S)?!1:(d.add(S),!0)});f.events.filter&&(T=f.events.filter(T,f));for(const v of T){let S=v.object;for(;S;){var y;(y=S.__r3f)!=null&&y.eventCount&&m.push({...v,eventObject:S}),S=S.parent}}if("pointerId"in c&&f.internal.capturedMap.has(c.pointerId))for(let v of f.internal.capturedMap.get(c.pointerId).values())d.has(Pv(v.intersection))||m.push(v.intersection);return m}function a(c,h,f,d){if(c.length){const m={stopped:!1};for(const g of c){let x=df(g.object);if(x||g.object.traverseAncestors(T=>{const y=df(T);if(y)return x=y,!1}),x){const{raycaster:T,pointer:y,camera:v,internal:S}=x,E=new L(y.x,y.y,0).unproject(v),b=O=>{var w,B;return(w=(B=S.capturedMap.get(O))==null?void 0:B.has(g.eventObject))!=null?w:!1},D=O=>{const w={intersection:g,target:h.target};S.capturedMap.has(O)?S.capturedMap.get(O).set(g.eventObject,w):S.capturedMap.set(O,new Map([[g.eventObject,w]])),h.target.setPointerCapture(O)},C=O=>{const w=S.capturedMap.get(O);w&&r8(S.capturedMap,g.eventObject,w,O)};let I={};for(let O in h){let w=h[O];typeof w!="function"&&(I[O]=w)}let P={...g,...I,pointer:y,intersections:c,stopped:m.stopped,delta:f,unprojectedPoint:E,ray:T.ray,camera:v,stopPropagation(){const O="pointerId"in h&&S.capturedMap.get(h.pointerId);if((!O||O.has(g.eventObject))&&(P.stopped=m.stopped=!0,S.hovered.size&&Array.from(S.hovered.values()).find(w=>w.eventObject===g.eventObject))){const w=c.slice(0,c.indexOf(g));r([...w,g])}},target:{hasPointerCapture:b,setPointerCapture:D,releasePointerCapture:C},currentTarget:{hasPointerCapture:b,setPointerCapture:D,releasePointerCapture:C},nativeEvent:h};if(d(P),m.stopped===!0)break}}}return c}function r(c){const{internal:h}=n.getState();for(const f of h.hovered.values())if(!c.length||!c.find(d=>d.object===f.object&&d.index===f.index&&d.instanceId===f.instanceId)){const m=f.eventObject.__r3f;if(h.hovered.delete(Pv(f)),m!=null&&m.eventCount){const g=m.handlers,x={...f,intersections:c};g.onPointerOut==null||g.onPointerOut(x),g.onPointerLeave==null||g.onPointerLeave(x)}}}function s(c,h){for(let f=0;fr([]);case"onLostPointerCapture":return h=>{const{internal:f}=n.getState();"pointerId"in h&&f.capturedMap.has(h.pointerId)&&requestAnimationFrame(()=>{f.capturedMap.has(h.pointerId)&&(f.capturedMap.delete(h.pointerId),r([]))})}}return function(f){const{onPointerMissed:d,internal:m}=n.getState();m.lastEvent.current=f;const g=c==="onPointerMove",x=c==="onClick"||c==="onContextMenu"||c==="onDoubleClick",y=i(f,g?t:void 0),v=x?e(f):0;c==="onPointerDown"&&(m.initialClick=[f.offsetX,f.offsetY],m.initialHits=y.map(E=>E.eventObject)),x&&!y.length&&v<=2&&(s(f,m.interaction),d&&d(f)),g&&r(y);function S(E){const b=E.eventObject,D=b.__r3f;if(!(D!=null&&D.eventCount))return;const C=D.handlers;if(g){if(C.onPointerOver||C.onPointerEnter||C.onPointerOut||C.onPointerLeave){const I=Pv(E),P=m.hovered.get(I);P?P.stopped&&E.stopPropagation():(m.hovered.set(I,E),C.onPointerOver==null||C.onPointerOver(E),C.onPointerEnter==null||C.onPointerEnter(E))}C.onPointerMove==null||C.onPointerMove(E)}else{const I=C[c];I?(!x||m.initialHits.includes(b))&&(s(f,m.interaction.filter(P=>!m.initialHits.includes(P))),I(E)):x&&m.initialHits.includes(b)&&s(f,m.interaction.filter(P=>!m.initialHits.includes(P)))}}a(y,f,v,S)}}return{handlePointer:o}}const VN=n=>!!(n!=null&&n.render),s8=Me.createContext(null),mZ=(n,e)=>{const t=Vj((o,c)=>{const h=new L,f=new L,d=new L;function m(v=c().camera,S=f,E=c().size){const{width:b,height:D,top:C,left:I}=E,P=b/D;S.isVector3?d.copy(S):d.set(...S);const O=v.getWorldPosition(h).distanceTo(d);if(t8(v))return{width:b/v.zoom,height:D/v.zoom,top:C,left:I,factor:1,distance:O,aspect:P};{const w=v.fov*Math.PI/180,B=2*Math.tan(w/2)*O,j=B*(b/D);return{width:j,height:B,top:C,left:I,factor:b/j,distance:O,aspect:P}}}let g;const x=v=>o(S=>({performance:{...S.performance,current:v}})),T=new de;return{set:o,get:c,gl:null,camera:null,raycaster:null,events:{priority:1,enabled:!0,connected:!1},scene:null,xr:null,invalidate:(v=1)=>n(c(),v),advance:(v,S)=>e(v,S,c()),legacy:!1,linear:!1,flat:!1,controls:null,clock:new Zb,pointer:T,mouse:T,frameloop:"always",onPointerMissed:void 0,performance:{current:1,min:.5,max:1,debounce:200,regress:()=>{const v=c();g&&clearTimeout(g),v.performance.current!==v.performance.min&&x(v.performance.min),g=setTimeout(()=>x(c().performance.max),v.performance.debounce)}},size:{width:0,height:0,top:0,left:0},viewport:{initialDpr:0,dpr:0,width:0,height:0,top:0,left:0,aspect:0,distance:0,factor:0,getCurrentViewport:m},setEvents:v=>o(S=>({...S,events:{...S.events,...v}})),setSize:(v,S,E=0,b=0)=>{const D=c().camera,C={width:v,height:S,top:E,left:b};o(I=>({size:C,viewport:{...I.viewport,...m(D,f,C)}}))},setDpr:v=>o(S=>{const E=i8(v);return{viewport:{...S.viewport,dpr:E,initialDpr:S.viewport.initialDpr||E}}}),setFrameloop:(v="always")=>{const S=c().clock;S.stop(),S.elapsedTime=0,v!=="never"&&(S.start(),S.elapsedTime=0),o(()=>({frameloop:v}))},previousRoot:void 0,internal:{interaction:[],hovered:new Map,subscribers:[],initialClick:[0,0],initialHits:[],capturedMap:new Map,lastEvent:Me.createRef(),active:!1,frames:0,priority:0,subscribe:(v,S,E)=>{const b=c().internal;return b.priority=b.priority+(S>0?1:0),b.subscribers.push({ref:v,priority:S,store:E}),b.subscribers=b.subscribers.sort((D,C)=>D.priority-C.priority),()=>{const D=c().internal;D!=null&&D.subscribers&&(D.priority=D.priority-(S>0?1:0),D.subscribers=D.subscribers.filter(C=>C.ref!==v))}}}}}),i=t.getState();let a=i.size,r=i.viewport.dpr,s=i.camera;return t.subscribe(()=>{const{camera:o,size:c,viewport:h,gl:f,set:d}=t.getState();if(c.width!==a.width||c.height!==a.height||h.dpr!==r){a=c,r=h.dpr,fZ(o,c),h.dpr>0&&f.setPixelRatio(h.dpr);const m=typeof HTMLCanvasElement<"u"&&f.domElement instanceof HTMLCanvasElement;f.setSize(c.width,c.height,m)}o!==s&&(s=o,d(m=>({viewport:{...m.viewport,...m.viewport.getCurrentViewport(o)}})))}),t.subscribe(o=>n(o)),t};function o8(){const n=Me.useContext(s8);if(!n)throw new Error("R3F: Hooks can only be used within the Canvas component!");return n}function Oi(n=t=>t,e){return o8()(n,e)}function cl(n,e=0){const t=o8(),i=t.getState().internal.subscribe,a=n8(n);return k0(()=>i(a,e,t),[e,i,t]),null}const kN=new WeakMap,gZ=n=>{var e;return typeof n=="function"&&(n==null||(e=n.prototype)==null?void 0:e.constructor)===n};function l8(n,e){return function(t,...i){let a;return gZ(t)?(a=kN.get(t),a||(a=new t,kN.set(t,a))):a=t,n&&n(a),Promise.all(i.map(r=>new Promise((s,o)=>a.load(r,c=>{Ca(c==null?void 0:c.scene)&&Object.assign(c,rZ(c.scene)),s(c)},e,c=>o(new Error(`Could not load ${r}: ${c==null?void 0:c.message}`))))))}}function Wx(n,e,t,i){const a=Array.isArray(e)?e:[e],r=Wj(l8(t,i),[n,...a],{equal:ri.equ});return Array.isArray(e)?r:r[0]}Wx.preload=function(n,e,t){const i=Array.isArray(e)?e:[e];return Xj(l8(t),[n,...i])};Wx.clear=function(n,e){const t=Array.isArray(e)?e:[e];return Yj([n,...t])};function vZ(n){const e=Zj(n);return e.injectIntoDevTools({bundleType:0,rendererPackageName:"@react-three/fiber",version:Me.version}),e}const c8=0,Od={},_Z=/^three(?=[A-Z])/,cy=n=>`${n[0].toUpperCase()}${n.slice(1)}`;let xZ=0;const yZ=n=>typeof n=="function";function u8(n){if(yZ(n)){const e=`${xZ++}`;return Od[e]=n,e}else Object.assign(Od,n)}function h8(n,e){const t=cy(n),i=Od[t];if(n!=="primitive"&&!i)throw new Error(`R3F: ${t} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`);if(n==="primitive"&&!e.object)throw new Error("R3F: Primitives without 'object' are invalid!");if(e.args!==void 0&&!Array.isArray(e.args))throw new Error("R3F: The args prop must be an array!")}function SZ(n,e,t){var i;return n=cy(n)in Od?n:n.replace(_Z,""),h8(n,e),n==="primitive"&&(i=e.object)!=null&&i.__r3f&&delete e.object.__r3f,Gx(e.object,t,n,e)}function TZ(n){if(!n.isHidden){var e;n.props.attach&&(e=n.parent)!=null&&e.object?kx(n.parent,n):Ca(n.object)&&(n.object.visible=!1),n.isHidden=!0,Zd(n)}}function f8(n){if(n.isHidden){var e;n.props.attach&&(e=n.parent)!=null&&e.object?Vx(n.parent,n):Ca(n.object)&&n.props.visible!==!1&&(n.object.visible=!0),n.isHidden=!1,Zd(n)}}function nA(n,e,t){const i=e.root.getState();if(!(!n.parent&&n.object!==i.scene)){if(!e.object){var a,r;const s=Od[cy(e.type)];e.object=(a=e.props.object)!=null?a:new s(...(r=e.props.args)!=null?r:[]),e.object.__r3f=e}if(Yl(e.object,e.props),e.props.attach)Vx(n,e);else if(Ca(e.object)&&Ca(n.object)){const s=n.object.children.indexOf(t==null?void 0:t.object);if(t&&s!==-1){const o=n.object.children.indexOf(e.object);if(o!==-1){n.object.children.splice(o,1);const c=o{try{n.dispose()}catch{}};typeof IS_REACT_ACT_ENVIRONMENT<"u"?e():_E.unstable_scheduleCallback(_E.unstable_IdlePriority,e)}}function yE(n,e,t){if(!e)return;e.parent=null;const i=n.children.indexOf(e);i!==-1&&n.children.splice(i,1),e.props.attach?kx(n,e):Ca(e.object)&&Ca(n.object)&&(n.object.remove(e.object),dZ(e8(e),e.object));const a=e.props.dispose!==null&&t!==!1;for(let r=e.children.length-1;r>=0;r--){const s=e.children[r];yE(e,s,a)}e.children.length=0,delete e.object.__r3f,a&&e.type!=="primitive"&&e.object.type!=="Scene"&&d8(e.object),t===void 0&&Zd(e)}function EZ(n,e){for(const t of[n,n.alternate])if(t!==null)if(typeof t.ref=="function"){t.refCleanup==null||t.refCleanup();const i=t.ref(e);typeof i=="function"&&(t.refCleanup=i)}else t.ref&&(t.ref.current=e)}const __=[];function MZ(){for(const[t]of __){const i=t.parent;if(i){t.props.attach?kx(i,t):Ca(t.object)&&Ca(i.object)&&i.object.remove(t.object);for(const a of t.children)a.props.attach?kx(t,a):Ca(a.object)&&Ca(t.object)&&t.object.remove(a.object)}t.isHidden&&f8(t),t.object.__r3f&&delete t.object.__r3f,t.type!=="primitive"&&d8(t.object)}for(const[t,i,a]of __){t.props=i;const r=t.parent;if(r){var n,e;const s=Od[cy(t.type)];t.object=(n=t.props.object)!=null?n:new s(...(e=t.props.args)!=null?e:[]),t.object.__r3f=t,EZ(a,t.object),Yl(t.object,t.props),t.props.attach?Vx(r,t):Ca(t.object)&&Ca(r.object)&&r.object.add(t.object);for(const o of t.children)o.props.attach?Vx(t,o):Ca(o.object)&&Ca(t.object)&&t.object.add(o.object);Zd(t)}}__.length=0}const _2=()=>{},XN={};let zv=c8;const bZ=0,AZ=4,SE=vZ({isPrimaryRenderer:!1,warnsIfNotActing:!1,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,createInstance:SZ,removeChild:yE,appendChild:v2,appendInitialChild:v2,insertBefore:WN,appendChildToContainer(n,e){const t=n.getState().scene.__r3f;!e||!t||v2(t,e)},removeChildFromContainer(n,e){const t=n.getState().scene.__r3f;!e||!t||yE(t,e)},insertInContainerBefore(n,e,t){const i=n.getState().scene.__r3f;!e||!t||!i||WN(i,e,t)},getRootHostContext:()=>XN,getChildHostContext:()=>XN,commitUpdate(n,e,t,i,a){var r,s,o;h8(e,i);let c=!1;if((n.type==="primitive"&&t.object!==i.object||((r=i.args)==null?void 0:r.length)!==((s=t.args)==null?void 0:s.length)||(o=i.args)!=null&&o.some((f,d)=>{var m;return f!==((m=t.args)==null?void 0:m[d])}))&&(c=!0),c)__.push([n,{...i},a]);else{const f=cZ(n,i);Object.keys(f).length&&(Object.assign(n.props,f),Yl(n.object,f))}(a.sibling===null||(a.flags&AZ)===bZ)&&MZ()},finalizeInitialChildren:()=>!1,commitMount(){},getPublicInstance:n=>n==null?void 0:n.object,prepareForCommit:()=>null,preparePortalMount:n=>Gx(n.getState().scene,n,"",{}),resetAfterCommit:()=>{},shouldSetTextContent:()=>!1,clearContainer:()=>!1,hideInstance:TZ,unhideInstance:f8,createTextInstance:_2,hideTextInstance:_2,unhideTextInstance:_2,scheduleTimeout:typeof setTimeout=="function"?setTimeout:void 0,cancelTimeout:typeof clearTimeout=="function"?clearTimeout:void 0,noTimeout:-1,getInstanceFromNode:()=>null,beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},detachDeletedInstance(){},prepareScopeUpdate(){},getInstanceFromScope:()=>null,shouldAttemptEagerTransition:()=>!1,trackSchedulerEvent:()=>{},resolveEventType:()=>null,resolveEventTimeStamp:()=>-1.1,requestPostPaintCallback(){},maySuspendCommit:()=>!1,preloadInstance:()=>!0,startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady:()=>null,NotPendingTransition:null,HostTransitionContext:Me.createContext(null),setCurrentUpdatePriority(n){zv=n},getCurrentUpdatePriority(){return zv},resolveUpdatePriority(){var n;if(zv!==c8)return zv;switch(typeof window<"u"&&((n=window.event)==null?void 0:n.type)){case"click":case"contextmenu":case"dblclick":case"pointercancel":case"pointerdown":case"pointerup":return p_.DiscreteEventPriority;case"pointermove":case"pointerout":case"pointerover":case"pointerenter":case"pointerleave":case"wheel":return p_.ContinuousEventPriority;default:return p_.DefaultEventPriority}},resetFormInstance(){}}),$u=new Map,pf={objects:"shallow",strict:!1};function wZ(n,e){if(!e&&typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement&&n.parentElement){const{width:t,height:i,top:a,left:r}=n.parentElement.getBoundingClientRect();return{width:t,height:i,top:a,left:r}}else if(!e&&typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas)return{width:n.width,height:n.height,top:0,left:0};return{width:0,height:0,top:0,left:0,...e}}function RZ(n){const e=$u.get(n),t=e==null?void 0:e.fiber,i=e==null?void 0:e.store;e&&console.warn("R3F.createRoot should only be called once!");const a=typeof reportError=="function"?reportError:console.error,r=i||mZ(ME,qN),s=t||SE.createContainer(r,p_.ConcurrentRoot,null,!1,null,"",a,a,a,null);e||$u.set(n,{fiber:s,store:r});let o,c,h=!1,f=null;return{async configure(d={}){let m;f=new Promise(Ce=>m=Ce);let{gl:g,size:x,scene:T,events:y,onCreated:v,shadows:S=!1,linear:E=!1,flat:b=!1,legacy:D=!1,orthographic:C=!1,frameloop:I="always",dpr:P=[1,2],performance:O,raycaster:w,camera:B,onPointerMissed:j}=d,ee=r.getState(),se=ee.gl;if(!ee.gl){const Ce={canvas:n,powerPreference:"high-performance",antialias:!0,alpha:!0},Xe=typeof g=="function"?await g(Ce):g;VN(Xe)?se=Xe:se=new $b({...Ce,...g}),ee.set({gl:se})}let re=ee.raycaster;re||ee.set({raycaster:re=new O6});const{params:W,...te}=w||{};if(ri.equ(te,re,pf)||Yl(re,{...te}),ri.equ(W,re.params,pf)||Yl(re,{params:{...re.params,...W}}),!ee.camera||ee.camera===c&&!ri.equ(c,B,pf)){c=B;const Ce=B==null?void 0:B.isCamera,Xe=Ce?B:C?new ao(0,0,0,0,.1,1e3):new hi(75,0,.1,1e3);Ce||(Xe.position.z=5,B&&(Yl(Xe,B),Xe.manual||("aspect"in B||"left"in B||"right"in B||"bottom"in B||"top"in B)&&(Xe.manual=!0,Xe.updateProjectionMatrix())),!ee.camera&&!(B!=null&&B.rotation)&&Xe.lookAt(0,0,0)),ee.set({camera:Xe}),re.camera=Xe}if(!ee.scene){let Ce;T!=null&&T.isScene?(Ce=T,Gx(Ce,r,"",{})):(Ce=new Rd,Gx(Ce,r,"",{}),T&&Yl(Ce,T)),ee.set({scene:Ce})}y&&!ee.events.handlers&&ee.set({events:y(r)});const K=wZ(n,x);if(ri.equ(K,ee.size,pf)||ee.setSize(K.width,K.height,K.top,K.left),P&&ee.viewport.dpr!==i8(P)&&ee.setDpr(P),ee.frameloop!==I&&ee.setFrameloop(I),ee.onPointerMissed||ee.set({onPointerMissed:j}),O&&!ri.equ(O,ee.performance,pf)&&ee.set(Ce=>({performance:{...Ce.performance,...O}})),!ee.xr){var oe;const Ce=(tt,gt)=>{const ge=r.getState();ge.frameloop!=="never"&&qN(tt,!0,ge,gt)},Xe=()=>{const tt=r.getState();tt.gl.xr.enabled=tt.gl.xr.isPresenting,tt.gl.xr.setAnimationLoop(tt.gl.xr.isPresenting?Ce:null),tt.gl.xr.isPresenting||ME(tt)},nt={connect(){const tt=r.getState().gl;tt.xr.addEventListener("sessionstart",Xe),tt.xr.addEventListener("sessionend",Xe)},disconnect(){const tt=r.getState().gl;tt.xr.removeEventListener("sessionstart",Xe),tt.xr.removeEventListener("sessionend",Xe)}};typeof((oe=se.xr)==null?void 0:oe.addEventListener)=="function"&&nt.connect(),ee.set({xr:nt})}if(se.shadowMap){const Ce=se.shadowMap.enabled,Xe=se.shadowMap.type;if(se.shadowMap.enabled=!!S,ri.boo(S))se.shadowMap.type=Dm;else if(ri.str(S)){var ie;const nt={basic:ZI,percentage:R1,soft:Dm,variance:Ss};se.shadowMap.type=(ie=nt[S])!=null?ie:Dm}else ri.obj(S)&&Object.assign(se.shadowMap,S);(Ce!==se.shadowMap.enabled||Xe!==se.shadowMap.type)&&(se.shadowMap.needsUpdate=!0)}return rn.enabled=!D,h||(se.outputColorSpace=E?Wn:En,se.toneMapping=b?is:hb),ee.legacy!==D&&ee.set(()=>({legacy:D})),ee.linear!==E&&ee.set(()=>({linear:E})),ee.flat!==b&&ee.set(()=>({flat:b})),g&&!ri.fun(g)&&!VN(g)&&!ri.equ(g,se,pf)&&Yl(se,g),o=v,h=!0,m(),this},render(d){return!h&&!f&&this.configure(),f.then(()=>{SE.updateContainer(Rt.jsx(CZ,{store:r,children:d,onCreated:o,rootElement:n}),s,null,()=>{})}),r},unmount(){p8(n)}}}function CZ({store:n,children:e,onCreated:t,rootElement:i}){return k0(()=>{const a=n.getState();a.set(r=>({internal:{...r.internal,active:!0}})),t&&t(a),n.getState().events.connected||a.events.connect==null||a.events.connect(i)},[]),Rt.jsx(s8.Provider,{value:n,children:e})}function p8(n,e){const t=$u.get(n),i=t==null?void 0:t.fiber;if(i){const a=t==null?void 0:t.store.getState();a&&(a.internal.active=!1),SE.updateContainer(null,i,null,()=>{a&&setTimeout(()=>{try{var r,s,o,c;a.events.disconnect==null||a.events.disconnect(),(r=a.gl)==null||(s=r.renderLists)==null||s.dispose==null||s.dispose(),(o=a.gl)==null||o.forceContextLoss==null||o.forceContextLoss(),(c=a.gl)!=null&&c.xr&&a.xr.disconnect(),sZ(a.scene),$u.delete(n)}catch{}},500)})}}const NZ=new Set,DZ=new Set,OZ=new Set;function x2(n,e){if(n.size)for(const{callback:t}of n.values())t(e)}function Hm(n,e){switch(n){case"before":return x2(NZ,e);case"after":return x2(DZ,e);case"tail":return x2(OZ,e)}}let y2,S2;function TE(n,e,t){let i=e.clock.getDelta();e.frameloop==="never"&&typeof n=="number"&&(i=n-e.clock.elapsedTime,e.clock.oldTime=e.clock.elapsedTime,e.clock.elapsedTime=n),y2=e.internal.subscribers;for(let a=0;a0)&&!((e=mf.gl.xr)!=null&&e.isPresenting)&&(T2+=TE(n,mf))}if(EE=!1,Hm("after",n),T2===0)return Hm("tail",n),Xx=!1,cancelAnimationFrame(YN)}function ME(n,e=1){var t;if(!n)return $u.forEach(i=>ME(i.store.getState(),e));(t=n.gl.xr)!=null&&t.isPresenting||!n.internal.active||n.frameloop==="never"||(e>1?n.internal.frames=Math.min(60,n.internal.frames+e):EE?n.internal.frames=2:n.internal.frames=1,Xx||(Xx=!0,requestAnimationFrame(m8)))}function qN(n,e=!0,t,i){if(e&&Hm("before",n),t)TE(n,t,i);else for(const a of $u.values())TE(n,a.store.getState());e&&Hm("after",n)}const E2={onClick:["click",!1],onContextMenu:["contextmenu",!1],onDoubleClick:["dblclick",!1],onWheel:["wheel",!0],onPointerDown:["pointerdown",!0],onPointerUp:["pointerup",!0],onPointerLeave:["pointerleave",!0],onPointerMove:["pointermove",!0],onPointerCancel:["pointercancel",!0],onLostPointerCapture:["lostpointercapture",!0]};function LZ(n){const{handlePointer:e}=pZ(n);return{priority:1,enabled:!0,compute(t,i,a){i.pointer.set(t.offsetX/i.size.width*2-1,-(t.offsetY/i.size.height)*2+1),i.raycaster.setFromCamera(i.pointer,i.camera)},connected:void 0,handlers:Object.keys(E2).reduce((t,i)=>({...t,[i]:e(i)}),{}),update:()=>{var t;const{events:i,internal:a}=n.getState();(t=a.lastEvent)!=null&&t.current&&i.handlers&&i.handlers.onPointerMove(a.lastEvent.current)},connect:t=>{const{set:i,events:a}=n.getState();if(a.disconnect==null||a.disconnect(),i(r=>({events:{...r.events,connected:t}})),a.handlers)for(const r in a.handlers){const s=a.handlers[r],[o,c]=E2[r];t.addEventListener(o,s,{passive:c})}},disconnect:()=>{const{set:t,events:i}=n.getState();if(i.connected){if(i.handlers)for(const a in i.handlers){const r=i.handlers[a],[s]=E2[a];i.connected.removeEventListener(s,r)}t(a=>({events:{...a.events,connected:void 0}}))}}}}function jN(n,e){let t;return(...i)=>{window.clearTimeout(t),t=window.setTimeout(()=>n(...i),e)}}function IZ({debounce:n,scroll:e,polyfill:t,offsetSize:i}={debounce:0,scroll:!1,offsetSize:!1}){const a=t||(typeof window>"u"?class{}:window.ResizeObserver);if(!a)throw new Error("This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills");const[r,s]=Me.useState({left:0,top:0,width:0,height:0,bottom:0,right:0,x:0,y:0}),o=Me.useRef({element:null,scrollContainers:null,resizeObserver:null,lastBounds:r,orientationHandler:null}),c=n?typeof n=="number"?n:n.scroll:null,h=n?typeof n=="number"?n:n.resize:null,f=Me.useRef(!1);Me.useEffect(()=>(f.current=!0,()=>void(f.current=!1)));const[d,m,g]=Me.useMemo(()=>{const v=()=>{if(!o.current.element)return;const{left:S,top:E,width:b,height:D,bottom:C,right:I,x:P,y:O}=o.current.element.getBoundingClientRect(),w={left:S,top:E,width:b,height:D,bottom:C,right:I,x:P,y:O};o.current.element instanceof HTMLElement&&i&&(w.height=o.current.element.offsetHeight,w.width=o.current.element.offsetWidth),Object.freeze(w),f.current&&!BZ(o.current.lastBounds,w)&&s(o.current.lastBounds=w)};return[v,h?jN(v,h):v,c?jN(v,c):v]},[s,i,c,h]);function x(){o.current.scrollContainers&&(o.current.scrollContainers.forEach(v=>v.removeEventListener("scroll",g,!0)),o.current.scrollContainers=null),o.current.resizeObserver&&(o.current.resizeObserver.disconnect(),o.current.resizeObserver=null),o.current.orientationHandler&&("orientation"in screen&&"removeEventListener"in screen.orientation?screen.orientation.removeEventListener("change",o.current.orientationHandler):"onorientationchange"in window&&window.removeEventListener("orientationchange",o.current.orientationHandler))}function T(){o.current.element&&(o.current.resizeObserver=new a(g),o.current.resizeObserver.observe(o.current.element),e&&o.current.scrollContainers&&o.current.scrollContainers.forEach(v=>v.addEventListener("scroll",g,{capture:!0,passive:!0})),o.current.orientationHandler=()=>{g()},"orientation"in screen&&"addEventListener"in screen.orientation?screen.orientation.addEventListener("change",o.current.orientationHandler):"onorientationchange"in window&&window.addEventListener("orientationchange",o.current.orientationHandler))}const y=v=>{!v||v===o.current.element||(x(),o.current.element=v,o.current.scrollContainers=g8(v),T())};return PZ(g,!!e),UZ(m),Me.useEffect(()=>{x(),T()},[e,g,m]),Me.useEffect(()=>x,[]),[y,r,d]}function UZ(n){Me.useEffect(()=>{const e=n;return window.addEventListener("resize",e),()=>void window.removeEventListener("resize",e)},[n])}function PZ(n,e){Me.useEffect(()=>{if(e){const t=n;return window.addEventListener("scroll",t,{capture:!0,passive:!0}),()=>void window.removeEventListener("scroll",t,!0)}},[n,e])}function g8(n){const e=[];if(!n||n===document.body)return e;const{overflow:t,overflowX:i,overflowY:a}=window.getComputedStyle(n);return[t,i,a].some(r=>r==="auto"||r==="scroll")&&e.push(n),[...e,...g8(n.parentElement)]}const zZ=["x","y","top","bottom","left","right","width","height"],BZ=(n,e)=>zZ.every(t=>n[t]===e[t]);function HZ({ref:n,children:e,fallback:t,resize:i,style:a,gl:r,events:s=LZ,eventSource:o,eventPrefix:c,shadows:h,linear:f,flat:d,legacy:m,orthographic:g,frameloop:x,dpr:T,performance:y,raycaster:v,camera:S,scene:E,onPointerMissed:b,onCreated:D,...C}){Me.useMemo(()=>u8(vj),[]);const I=nZ(),[P,O]=IZ({scroll:!0,debounce:{scroll:50,resize:0},...i}),w=Me.useRef(null),B=Me.useRef(null);Me.useImperativeHandle(n,()=>w.current);const j=n8(b),[ee,se]=Me.useState(!1),[re,W]=Me.useState(!1);if(ee)throw ee;if(re)throw re;const te=Me.useRef(null);k0(()=>{const oe=w.current;if(O.width>0&&O.height>0&&oe){te.current||(te.current=RZ(oe));async function ie(){await te.current.configure({gl:r,scene:E,events:s,shadows:h,linear:f,flat:d,legacy:m,orthographic:g,frameloop:x,dpr:T,performance:y,raycaster:v,camera:S,size:O,onPointerMissed:(...Ce)=>j.current==null?void 0:j.current(...Ce),onCreated:Ce=>{Ce.events.connect==null||Ce.events.connect(o?eZ(o)?o.current:o:B.current),c&&Ce.setEvents({compute:(Xe,nt)=>{const tt=Xe[c+"X"],gt=Xe[c+"Y"];nt.pointer.set(tt/nt.size.width*2-1,-(gt/nt.size.height)*2+1),nt.raycaster.setFromCamera(nt.pointer,nt.camera)}}),D==null||D(Ce)}}),te.current.render(Rt.jsx(I,{children:Rt.jsx(aZ,{set:W,children:Rt.jsx(Me.Suspense,{fallback:Rt.jsx(iZ,{set:se}),children:e??null})})}))}ie()}}),Me.useEffect(()=>{const oe=w.current;if(oe)return()=>p8(oe)},[]);const K=o?"none":"auto";return Rt.jsx("div",{ref:B,style:{position:"relative",width:"100%",height:"100%",overflow:"hidden",pointerEvents:K,...a},...C,children:Rt.jsx("div",{ref:P,style:{width:"100%",height:"100%"},children:Rt.jsx("canvas",{ref:w,style:{display:"block"},children:t})})})}function v8(n){return Rt.jsx(J6,{children:Rt.jsx(HZ,{...n})})}function ZN(n,e){if(e===MU)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===Px||e===_b){let t=n.getIndex();if(t===null){const s=[],o=n.getAttribute("position");if(o!==void 0){for(let c=0;c=2.0 are supported."));return}const h=new _K(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});h.fileLoader.setRequestHeader(this.requestHeader);for(let f=0;f=0&&o[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}h.setExtensions(s),h.setPlugins(o),h.parse(i,a)}parseAsync(e,t){const i=this;return new Promise(function(a,r){i.parse(e,t,a,r)})}}function FZ(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const on={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class GZ{constructor(e){this.parser=e,this.name=on.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,a=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,s)}}class tK{constructor(e){this.parser=e,this.name=on.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,i=this.parser,a=i.json,r=a.textures[e];if(!r.extensions||!r.extensions[t])return null;const s=r.extensions[t],o=a.images[s.source];let c=i.textureLoader;if(o.uri){const h=i.options.manager.getHandler(o.uri);h!==null&&(c=h)}return i.loadTextureImage(e,s.source,c)}}class nK{constructor(e){this.parser=e,this.name=on.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,i=this.parser,a=i.json,r=a.textures[e];if(!r.extensions||!r.extensions[t])return null;const s=r.extensions[t],o=a.images[s.source];let c=i.textureLoader;if(o.uri){const h=i.options.manager.getHandler(o.uri);h!==null&&(c=h)}return i.loadTextureImage(e,s.source,c)}}class iK{constructor(e){this.name=on.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const a=i.extensions[this.name],r=this.parser.getDependency("buffer",a.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(o){const c=a.byteOffset||0,h=a.byteLength||0,f=a.count,d=a.byteStride,m=new Uint8Array(o,c,h);return s.decodeGltfBufferAsync?s.decodeGltfBufferAsync(f,d,m,a.mode,a.filter).then(function(g){return g.buffer}):s.ready.then(function(){const g=new ArrayBuffer(f*d);return s.decodeGltfBuffer(new Uint8Array(g),f,d,m,a.mode,a.filter),g})})}else return null}}class aK{constructor(e){this.name=on.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const a=t.meshes[i.mesh];for(const h of a.primitives)if(h.mode!==Yr.TRIANGLES&&h.mode!==Yr.TRIANGLE_STRIP&&h.mode!==Yr.TRIANGLE_FAN&&h.mode!==void 0)return null;const s=i.extensions[this.name].attributes,o=[],c={};for(const h in s)o.push(this.parser.getDependency("accessor",s[h]).then(f=>(c[h]=f,c[h])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(h=>{const f=h.pop(),d=f.isGroup?f.children:[f],m=h[0].count,g=[];for(const x of d){const T=new ke,y=new L,v=new St,S=new L(1,1,1),E=new Ab(x.geometry,x.material,m);for(let b=0;b0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const vK=new ke;class _K{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new FZ,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,a=-1,r=!1,s=-1;if(typeof navigator<"u"){const o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;const c=o.match(/Version\/(\d+)/);a=i&&c?parseInt(c[1],10):-1,r=o.indexOf("Firefox")>-1,s=r?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&a<17||r&&s<98?this.textureLoader=new kb(this.options.manager):this.textureLoader=new A6(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new os(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,a=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(s){return s._markDefs&&s._markDefs()}),Promise.all(this._invokeAll(function(s){return s.beforeRoot&&s.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(s){const o={scene:s[0][a.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:a.asset,parser:i,userData:{}};return lu(r,o,a),js(o,a),Promise.all(i._invokeAll(function(c){return c.afterRoot&&c.afterRoot(o)})).then(function(){for(const c of o.scenes)c.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let a=0,r=t.length;a{const c=this.associations.get(s);c!=null&&this.associations.set(o,c);for(const[h,f]of s.children.entries())r(f,o.children[h])};return r(i,a),a.name+="_instance_"+e.uses[t]++,a}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&y.setY(O,C[I*c+1]),c>=3&&y.setZ(O,C[I*c+2]),c>=4&&y.setW(O,C[I*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}y.normalized=x}return y})}loadTexture(e){const t=this.json,i=this.options,r=t.textures[e].source,s=t.images[r];let o=this.textureLoader;if(s.uri){const c=i.manager.getHandler(s.uri);c!==null&&(o=c)}return this.loadTextureImage(e,r,o)}loadTextureImage(e,t,i){const a=this,r=this.json,s=r.textures[e],o=r.images[t],c=(o.uri||o.bufferView)+":"+s.sampler;if(this.textureCache[c])return this.textureCache[c];const h=this.loadImageSource(t,i).then(function(f){f.flipY=!1,f.name=s.name||o.name||"",f.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(f.name=o.uri);const m=(r.samplers||{})[s.sampler]||{};return f.magFilter=JN[m.magFilter]||Ht,f.minFilter=JN[m.minFilter]||Mr,f.wrapS=$N[m.wrapS]||Ea,f.wrapT=$N[m.wrapT]||Ea,f.generateMipmaps=!f.isCompressedTexture&&f.minFilter!==Fn&&f.minFilter!==Ht,a.associations.set(f,{textures:e}),f}).catch(function(){return null});return this.textureCache[c]=h,h}loadImageSource(e,t){const i=this,a=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const s=a.images[e],o=self.URL||self.webkitURL;let c=s.uri||"",h=!1;if(s.bufferView!==void 0)c=i.getDependency("bufferView",s.bufferView).then(function(d){h=!0;const m=new Blob([d],{type:s.mimeType});return c=o.createObjectURL(m),c});else if(s.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const f=Promise.resolve(c).then(function(d){return new Promise(function(m,g){let x=m;t.isImageBitmapLoader===!0&&(x=function(T){const y=new Nn(T);y.needsUpdate=!0,m(y)}),t.load(uc.resolveURL(d,r.path),x,void 0,g)})}).then(function(d){return h===!0&&o.revokeObjectURL(c),js(d,s),d.userData.mimeType=s.mimeType||gK(s.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),d});return this.sourceCache[e]=f,f}assignTexture(e,t,i,a){const r=this;return this.getDependency("texture",i.index).then(function(s){if(!s)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(s=s.clone(),s.channel=i.texCoord),r.extensions[on.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[on.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const c=r.associations.get(s);s=r.extensions[on.KHR_TEXTURE_TRANSFORM].extendTexture(s,o),r.associations.set(s,c)}}return a!==void 0&&(s.colorSpace=a),e[t]=s,s})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const a=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,s=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+i.uuid;let c=this.cache.get(o);c||(c=new W1,qn.prototype.copy.call(c,i),c.color.copy(i.color),c.map=i.map,c.sizeAttenuation=!1,this.cache.add(o,c)),i=c}else if(e.isLine){const o="LineBasicMaterial:"+i.uuid;let c=this.cache.get(o);c||(c=new Bi,qn.prototype.copy.call(c,i),c.color.copy(i.color),c.map=i.map,this.cache.add(o,c)),i=c}if(a||r||s){let o="ClonedMaterial:"+i.uuid+":";a&&(o+="derivative-tangents:"),r&&(o+="vertex-colors:"),s&&(o+="flat-shading:");let c=this.cache.get(o);c||(c=i.clone(),r&&(c.vertexColors=!0),s&&(c.flatShading=!0),a&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(o,c),this.associations.set(c,this.associations.get(i))),i=c}e.material=i}getMaterialType(){return V0}loadMaterial(e){const t=this,i=this.json,a=this.extensions,r=i.materials[e];let s;const o={},c=r.extensions||{},h=[];if(c[on.KHR_MATERIALS_UNLIT]){const d=a[on.KHR_MATERIALS_UNLIT];s=d.getMaterialType(),h.push(d.extendParams(o,r,t))}else{const d=r.pbrMetallicRoughness||{};if(o.color=new je(1,1,1),o.opacity=1,Array.isArray(d.baseColorFactor)){const m=d.baseColorFactor;o.color.setRGB(m[0],m[1],m[2],Wn),o.opacity=m[3]}d.baseColorTexture!==void 0&&h.push(t.assignTexture(o,"map",d.baseColorTexture,En)),o.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,o.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(h.push(t.assignTexture(o,"metalnessMap",d.metallicRoughnessTexture)),h.push(t.assignTexture(o,"roughnessMap",d.metallicRoughnessTexture))),s=this._invokeOne(function(m){return m.getMaterialType&&m.getMaterialType(e)}),h.push(Promise.all(this._invokeAll(function(m){return m.extendMaterialParams&&m.extendMaterialParams(e,o)})))}r.doubleSided===!0&&(o.side=ca);const f=r.alphaMode||b2.OPAQUE;if(f===b2.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,f===b2.MASK&&(o.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&s!==Ia&&(h.push(t.assignTexture(o,"normalMap",r.normalTexture)),o.normalScale=new de(1,1),r.normalTexture.scale!==void 0)){const d=r.normalTexture.scale;o.normalScale.set(d,d)}if(r.occlusionTexture!==void 0&&s!==Ia&&(h.push(t.assignTexture(o,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&s!==Ia){const d=r.emissiveFactor;o.emissive=new je().setRGB(d[0],d[1],d[2],Wn)}return r.emissiveTexture!==void 0&&s!==Ia&&h.push(t.assignTexture(o,"emissiveMap",r.emissiveTexture,En)),Promise.all(h).then(function(){const d=new s(o);return r.name&&(d.name=r.name),js(d,r),t.associations.set(d,{materials:e}),r.extensions&&lu(a,d,r),d})}createUniqueName(e){const t=fn.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,a=this.primitiveCache;function r(o){return i[on.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(c){return eD(c,o,t)})}const s=[];for(let o=0,c=e.length;o0&&pK(v,r),v.name=t.createUniqueName(r.name||"mesh_"+e),js(v,r),y.extensions&&lu(a,v,y),t.assignFinalMaterial(v),d.push(v)}for(let g=0,x=d.length;g1?f=new Ua:h.length===1?f=h[0]:f=new Wt,f!==h[0])for(let d=0,m=h.length;d1){const d=a.associations.get(f);a.associations.set(f,{...d})}return a.associations.get(f).nodes=e,f}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],a=this,r=new Ua;i.name&&(r.name=a.createUniqueName(i.name)),js(r,i),i.extensions&&lu(t,r,i);const s=i.nodes||[],o=[];for(let c=0,h=s.length;c{const d=new Map;for(const[m,g]of a.associations)(m instanceof qn||m instanceof Nn)&&d.set(m,g);return f.traverse(m=>{const g=a.associations.get(m);g!=null&&d.set(m,g)}),d};return a.associations=h(r),r})}_createAnimationTracks(e,t,i,a,r){const s=[],o=e.name?e.name:e.uuid,c=[];Il[r.path]===Il.weights?e.traverse(function(m){m.morphTargetInfluences&&c.push(m.name?m.name:m.uuid)}):c.push(o);let h;switch(Il[r.path]){case Il.weights:h=xc;break;case Il.rotation:h=yc;break;case Il.translation:case Il.scale:h=Qu;break;default:switch(i.itemSize){case 1:h=xc;break;case 2:case 3:default:h=Qu;break}break}const f=a.interpolation!==void 0?hK[a.interpolation]:Td,d=this._getArrayFromAccessor(i);for(let m=0,g=c.length;mnew Promise((i,a)=>{var r=c=>{try{o(t.next(c))}catch(h){a(h)}},s=c=>{try{o(t.throw(c))}catch(h){a(h)}},o=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,s);o((t=t.apply(n,e)).next())}),vn=(n,e,t)=>new Promise((i,a)=>{var r=c=>{try{o(t.next(c))}catch(h){a(h)}},s=c=>{try{o(t.throw(c))}catch(h){a(h)}},o=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,s);o((t=t.apply(n,e)).next())}),tD=class extends Wt{constructor(n){super(),this.weight=0,this.isBinary=!1,this.overrideBlink="none",this.overrideLookAt="none",this.overrideMouth="none",this._binds=[],this.name=`VRMExpression_${n}`,this.expressionName=n,this.type="VRMExpression",this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink==="block"?0.5?1:0:this.weight}addBind(n){this._binds.push(n)}deleteBind(n){const e=this._binds.indexOf(n);e>=0&&this._binds.splice(e,1)}applyWeight(n){var e;let t=this.outputWeight;t*=(e=n==null?void 0:n.multiplier)!=null?e:1,this.isBinary&&t<1&&(t=0),this._binds.forEach(i=>i.applyWeight(t))}clearAppliedWeight(){this._binds.forEach(n=>n.clearAppliedWeight())}};function y8(n,e,t){var i,a;const r=n.parser.json,s=(i=r.nodes)==null?void 0:i[e];if(s==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${e}] of glTF but the node doesn't exist`),null;const o=s.mesh;if(o==null)return null;const c=(a=r.meshes)==null?void 0:a[o];if(c==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${o}] of glTF but the mesh doesn't exist`),null;const h=c.primitives.length,f=[];return t.traverse(d=>{f.length{const r=y8(n,a,i);r!=null&&t.set(a,r)}),t})}var wE={Aa:"aa",Ih:"ih",Ou:"ou",Ee:"ee",Oh:"oh",Blink:"blink",Happy:"happy",Angry:"angry",Sad:"sad",Relaxed:"relaxed",LookUp:"lookUp",Surprised:"surprised",LookDown:"lookDown",LookLeft:"lookLeft",LookRight:"lookRight",BlinkLeft:"blinkLeft",BlinkRight:"blinkRight",Neutral:"neutral"};function S8(n){return Math.max(Math.min(n,1),0)}var aD=class T8{constructor(){this.blinkExpressionNames=["blink","blinkLeft","blinkRight"],this.lookAtExpressionNames=["lookLeft","lookRight","lookUp","lookDown"],this.mouthExpressionNames=["aa","ee","ih","oh","ou"],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){const e={},t=new Set(Object.values(wE));return Object.entries(this._expressionMap).forEach(([i,a])=>{t.has(i)&&(e[i]=a)}),e}get customExpressionMap(){const e={},t=new Set(Object.values(wE));return Object.entries(this._expressionMap).forEach(([i,a])=>{t.has(i)||(e[i]=a)}),e}copy(e){return this._expressions.concat().forEach(i=>{this.unregisterExpression(i)}),e._expressions.forEach(i=>{this.registerExpression(i)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new T8().copy(this)}getExpression(e){var t;return(t=this._expressionMap[e])!=null?t:null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){const t=this._expressions.indexOf(e);t===-1&&console.warn("VRMExpressionManager: The specified expressions is not registered"),this._expressions.splice(t,1),delete this._expressionMap[e.expressionName]}getValue(e){var t;const i=this.getExpression(e);return(t=i==null?void 0:i.weight)!=null?t:null}setValue(e,t){const i=this.getExpression(e);i&&(i.weight=S8(t))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){const t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){const e=this._calculateWeightMultipliers();this._expressions.forEach(t=>{t.clearAppliedWeight()}),this._expressions.forEach(t=>{let i=1;const a=t.expressionName;this.blinkExpressionNames.indexOf(a)!==-1&&(i*=e.blink),this.lookAtExpressionNames.indexOf(a)!==-1&&(i*=e.lookAt),this.mouthExpressionNames.indexOf(a)!==-1&&(i*=e.mouth),t.applyWeight({multiplier:i})})}_calculateWeightMultipliers(){let e=1,t=1,i=1;return this._expressions.forEach(a=>{e-=a.overrideBlinkAmount,t-=a.overrideLookAtAmount,i-=a.overrideMouthAmount}),e=Math.max(0,e),t=Math.max(0,t),i=Math.max(0,i),{blink:e,lookAt:t,mouth:i}}},qp={Color:"color",EmissionColor:"emissionColor",ShadeColor:"shadeColor",RimColor:"rimColor",OutlineColor:"outlineColor"},yK={_Color:qp.Color,_EmissionColor:qp.EmissionColor,_ShadeColor:qp.ShadeColor,_RimColor:qp.RimColor,_OutlineColor:qp.OutlineColor},SK=new je,E8=class M8{constructor({material:e,type:t,targetValue:i,targetAlpha:a}){this.material=e,this.type=t,this.targetValue=i,this.targetAlpha=a??1;const r=this._initColorBindState(),s=this._initAlphaBindState();this._state={color:r,alpha:s}}applyWeight(e){const{color:t,alpha:i}=this._state;if(t!=null){const{propertyName:a,deltaValue:r}=t,s=this.material[a];s!=null&&s.add(SK.copy(r).multiplyScalar(e))}if(i!=null){const{propertyName:a,deltaValue:r}=i;this.material[a]!=null&&(this.material[a]+=r*e)}}clearAppliedWeight(){const{color:e,alpha:t}=this._state;if(e!=null){const{propertyName:i,initialValue:a}=e,r=this.material[i];r!=null&&r.copy(a)}if(t!=null){const{propertyName:i,initialValue:a}=t;this.material[i]!=null&&(this.material[i]=a)}}_initColorBindState(){var e,t,i;const{material:a,type:r,targetValue:s}=this,o=this._getPropertyNameMap(),c=(t=(e=o==null?void 0:o[r])==null?void 0:e[0])!=null?t:null;if(c==null)return console.warn(`Tried to add a material color bind to the material ${(i=a.name)!=null?i:"(no name)"}, the type ${r} but the material or the type is not supported.`),null;const f=a[c].clone(),d=new je(s.r-f.r,s.g-f.g,s.b-f.b);return{propertyName:c,initialValue:f,deltaValue:d}}_initAlphaBindState(){var e,t,i;const{material:a,type:r,targetAlpha:s}=this,o=this._getPropertyNameMap(),c=(t=(e=o==null?void 0:o[r])==null?void 0:e[1])!=null?t:null;if(c==null&&s!==1)return console.warn(`Tried to add a material alpha bind to the material ${(i=a.name)!=null?i:"(no name)"}, the type ${r} but the material or the type does not support alpha.`),null;if(c==null)return null;const h=a[c],f=s-h;return{propertyName:c,initialValue:h,deltaValue:f}}_getPropertyNameMap(){var e,t;return(t=(e=Object.entries(M8._propertyNameMapMap).find(([i])=>this.material[i]===!0))==null?void 0:e[1])!=null?t:null}};E8._propertyNameMapMap={isMeshStandardMaterial:{color:["color","opacity"],emissionColor:["emissive",null]},isMeshBasicMaterial:{color:["color","opacity"]},isMToonMaterial:{color:["color","opacity"],emissionColor:["emissive",null],outlineColor:["outlineColorFactor",null],matcapColor:["matcapFactor",null],rimColor:["parametricRimColorFactor",null],shadeColor:["shadeColorFactor",null]}};var rD=E8,Yx=class{constructor({primitives:n,index:e,weight:t}){this.primitives=n,this.index=e,this.weight=t}applyWeight(n){this.primitives.forEach(e=>{var t;((t=e.morphTargetInfluences)==null?void 0:t[this.index])!=null&&(e.morphTargetInfluences[this.index]+=this.weight*n)})}clearAppliedWeight(){this.primitives.forEach(n=>{var e;((e=n.morphTargetInfluences)==null?void 0:e[this.index])!=null&&(n.morphTargetInfluences[this.index]=0)})}},sD=new de,b8=class A8{constructor({material:e,scale:t,offset:i}){var a,r;this.material=e,this.scale=t,this.offset=i;const s=(a=Object.entries(A8._propertyNamesMap).find(([o])=>e[o]===!0))==null?void 0:a[1];s==null?(console.warn(`Tried to add a texture transform bind to the material ${(r=e.name)!=null?r:"(no name)"} but the material is not supported.`),this._properties=[]):(this._properties=[],s.forEach(o=>{var c;const h=(c=e[o])==null?void 0:c.clone();if(!h)return null;e[o]=h;const f=h.offset.clone(),d=h.repeat.clone(),m=i.clone().sub(f),g=t.clone().sub(d);this._properties.push({name:o,initialOffset:f,deltaOffset:m,initialScale:d,deltaScale:g})}))}applyWeight(e){this._properties.forEach(t=>{const i=this.material[t.name];i!==void 0&&(i.offset.add(sD.copy(t.deltaOffset).multiplyScalar(e)),i.repeat.add(sD.copy(t.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{const t=this.material[e.name];t!==void 0&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))})}};b8._propertyNamesMap={isMeshStandardMaterial:["map","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap"],isMeshBasicMaterial:["map","specularMap","alphaMap"],isMToonMaterial:["map","normalMap","emissiveMap","shadeMultiplyTexture","rimMultiplyTexture","outlineWidthMultiplyTexture","uvAnimationMaskTexture"]};var oD=b8,TK=new Set(["1.0","1.0-beta"]),w8=class R8{get name(){return"VRMExpressionLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return vn(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return vn(this,null,function*(){const t=yield this._v1Import(e);if(t)return t;const i=yield this._v0Import(e);return i||null})}_v1Import(e){return vn(this,null,function*(){var t,i;const a=this.parser.json;if(!(((t=a.extensionsUsed)==null?void 0:t.indexOf("VRMC_vrm"))!==-1))return null;const s=(i=a.extensions)==null?void 0:i.VRMC_vrm;if(!s)return null;const o=s.specVersion;if(!TK.has(o))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${o}"`),null;const c=s.expressions;if(!c)return null;const h=new Set(Object.values(wE)),f=new Map;c.preset!=null&&Object.entries(c.preset).forEach(([m,g])=>{if(g!=null){if(!h.has(m)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${m}" detected. Ignoring the expression`);return}f.set(m,g)}}),c.custom!=null&&Object.entries(c.custom).forEach(([m,g])=>{if(h.has(m)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${m}". Ignoring the expression`);return}f.set(m,g)});const d=new aD;return yield Promise.all(Array.from(f.entries()).map(m=>vn(this,[m],function*([g,x]){var T,y,v,S,E,b,D;const C=new tD(g);if(e.scene.add(C),C.isBinary=(T=x.isBinary)!=null?T:!1,C.overrideBlink=(y=x.overrideBlink)!=null?y:"none",C.overrideLookAt=(v=x.overrideLookAt)!=null?v:"none",C.overrideMouth=(S=x.overrideMouth)!=null?S:"none",(E=x.morphTargetBinds)==null||E.forEach(I=>vn(this,null,function*(){var P;if(I.node===void 0||I.index===void 0)return;const O=yield nD(e,I.node),w=I.index;if(!O.every(B=>Array.isArray(B.morphTargetInfluences)&&w{const O=P.material;O&&(Array.isArray(O)?I.push(...O):I.push(O))}),(b=x.materialColorBinds)==null||b.forEach(P=>vn(this,null,function*(){I.filter(w=>{var B;const j=(B=this.parser.associations.get(w))==null?void 0:B.materials;return P.material===j}).forEach(w=>{C.addBind(new rD({material:w,type:P.type,targetValue:new je().fromArray(P.targetValue),targetAlpha:P.targetValue[3]}))})})),(D=x.textureTransformBinds)==null||D.forEach(P=>vn(this,null,function*(){I.filter(w=>{var B;const j=(B=this.parser.associations.get(w))==null?void 0:B.materials;return P.material===j}).forEach(w=>{var B,j;C.addBind(new oD({material:w,offset:new de().fromArray((B=P.offset)!=null?B:[0,0]),scale:new de().fromArray((j=P.scale)!=null?j:[1,1])}))})}))}d.registerExpression(C)}))),d})}_v0Import(e){return vn(this,null,function*(){var t;const i=this.parser.json,a=(t=i.extensions)==null?void 0:t.VRM;if(!a)return null;const r=a.blendShapeMaster;if(!r)return null;const s=new aD,o=r.blendShapeGroups;if(!o)return s;const c=new Set;return yield Promise.all(o.map(h=>vn(this,null,function*(){var f;const d=h.presetName,m=d!=null&&R8.v0v1PresetNameMap[d]||null,g=m??h.name;if(g==null){console.warn("VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression");return}if(c.has(g)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${d} has duplicated entries. Ignoring the expression`);return}c.add(g);const x=new tD(g);e.scene.add(x),x.isBinary=(f=h.isBinary)!=null?f:!1,h.binds&&h.binds.forEach(y=>vn(this,null,function*(){var v;if(y.mesh===void 0||y.index===void 0)return;const S=[];(v=i.nodes)==null||v.forEach((b,D)=>{b.mesh===y.mesh&&S.push(D)});const E=y.index;yield Promise.all(S.map(b=>vn(this,null,function*(){var D;const C=yield nD(e,b);if(!C.every(I=>Array.isArray(I.morphTargetInfluences)&&E{if(y.materialName===void 0||y.propertyName===void 0||y.targetValue===void 0)return;const v=[];e.scene.traverse(E=>{if(E.material){const b=E.material;Array.isArray(b)?v.push(...b.filter(D=>(D.name===y.materialName||D.name===y.materialName+" (Outline)")&&v.indexOf(D)===-1)):b.name===y.materialName&&v.indexOf(b)===-1&&v.push(b)}});const S=y.propertyName;v.forEach(E=>{if(S==="_MainTex_ST"){const D=new de(y.targetValue[0],y.targetValue[1]),C=new de(y.targetValue[2],y.targetValue[3]);C.y=1-C.y-D.y,x.addBind(new oD({material:E,scale:D,offset:C}));return}const b=yK[S];if(b){x.addBind(new rD({material:E,type:b,targetValue:new je().fromArray(y.targetValue),targetAlpha:y.targetValue[3]}));return}console.warn(S+" is not supported")})}),s.registerExpression(x)}))),s})}};w8.v0v1PresetNameMap={a:"aa",e:"ee",i:"ih",o:"oh",u:"ou",blink:"blink",joy:"happy",angry:"angry",sorrow:"sad",fun:"relaxed",lookup:"lookUp",lookdown:"lookDown",lookleft:"lookLeft",lookright:"lookRight",blink_l:"blinkLeft",blink_r:"blinkRight",neutral:"neutral"};var EK=w8,iA=class Cf{constructor(e,t){this._firstPersonOnlyLayer=Cf.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=Cf.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=e,this.meshAnnotations=t}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMFirstPerson: humanoid must be same in order to copy");return this.meshAnnotations=e.meshAnnotations.map(t=>({meshes:t.meshes.concat(),type:t.type})),this}clone(){return new Cf(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:e=Cf.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=Cf.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||(this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=t,this.meshAnnotations.forEach(i=>{i.meshes.forEach(a=>{i.type==="firstPersonOnly"?(a.layers.set(this._firstPersonOnlyLayer),a.traverse(r=>r.layers.set(this._firstPersonOnlyLayer))):i.type==="thirdPersonOnly"?(a.layers.set(this._thirdPersonOnlyLayer),a.traverse(r=>r.layers.set(this._thirdPersonOnlyLayer))):i.type==="auto"&&this._createHeadlessModel(a)})}),this._initializedLayers=!0)}_excludeTriangles(e,t,i,a){let r=0;if(t!=null&&t.length>0)for(let s=0;s0&&a.includes(d[0])||f[1]>0&&a.includes(d[1])||f[2]>0&&a.includes(d[2])||f[3]>0&&a.includes(d[3]))continue;const m=t[c],g=i[c];if(m[0]>0&&a.includes(g[0])||m[1]>0&&a.includes(g[1])||m[2]>0&&a.includes(g[2])||m[3]>0&&a.includes(g[3]))continue;const x=t[h],T=i[h];x[0]>0&&a.includes(T[0])||x[1]>0&&a.includes(T[1])||x[2]>0&&a.includes(T[2])||x[3]>0&&a.includes(T[3])||(e[r++]=o,e[r++]=c,e[r++]=h)}return r}_createErasedMesh(e,t){const i=new G1(e.geometry.clone(),e.material);i.name=`${e.name}(erase)`,i.frustumCulled=e.frustumCulled,i.layers.set(this._firstPersonOnlyLayer);const a=i.geometry,r=a.getAttribute("skinIndex"),s=r instanceof fE?[]:r.array,o=[];for(let T=0;T{this._isEraseTarget(r)&&i.push(s)}),!i.length){t.layers.enable(this._thirdPersonOnlyLayer),t.layers.enable(this._firstPersonOnlyLayer);return}t.layers.set(this._thirdPersonOnlyLayer);const a=this._createErasedMesh(t,i);e.add(a)}_createHeadlessModel(e){if(e.type==="Group")if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(t=>t.layers.set(this._thirdPersonOnlyLayer));else{const t=new Ua;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter(i=>i.type==="SkinnedMesh").forEach(i=>{const a=i;this._createHeadlessModelForSkinnedMesh(t,a)})}else if(e.type==="SkinnedMesh"){const t=e;this._createHeadlessModelForSkinnedMesh(e.parent,t)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(t=>t.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode("head")?!0:e.parent?this._isEraseTarget(e.parent):!1}};iA.DEFAULT_FIRSTPERSON_ONLY_LAYER=9;iA.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var lD=iA,MK=new Set(["1.0","1.0-beta"]),bK=class{get name(){return"VRMFirstPersonLoaderPlugin"}constructor(n){this.parser=n}afterRoot(n){return vn(this,null,function*(){const e=n.userData.vrmHumanoid;if(e!==null){if(e===void 0)throw new Error("VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");n.userData.vrmFirstPerson=yield this._import(n,e)}})}_import(n,e){return vn(this,null,function*(){if(e==null)return null;const t=yield this._v1Import(n,e);if(t)return t;const i=yield this._v0Import(n,e);return i||null})}_v1Import(n,e){return vn(this,null,function*(){var t,i;const a=this.parser.json;if(!(((t=a.extensionsUsed)==null?void 0:t.indexOf("VRMC_vrm"))!==-1))return null;const s=(i=a.extensions)==null?void 0:i.VRMC_vrm;if(!s)return null;const o=s.specVersion;if(!MK.has(o))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${o}"`),null;const c=s.firstPerson,h=[],f=yield iD(n);return Array.from(f.entries()).forEach(([d,m])=>{var g,x;const T=(g=c==null?void 0:c.meshAnnotations)==null?void 0:g.find(y=>y.node===d);h.push({meshes:m,type:(x=T==null?void 0:T.type)!=null?x:"auto"})}),new lD(e,h)})}_v0Import(n,e){return vn(this,null,function*(){var t;const i=this.parser.json,a=(t=i.extensions)==null?void 0:t.VRM;if(!a)return null;const r=a.firstPerson;if(!r)return null;const s=[],o=yield iD(n);return Array.from(o.entries()).forEach(([c,h])=>{const f=i.nodes[c],d=r.meshAnnotations?r.meshAnnotations.find(m=>m.mesh===f.mesh):void 0;s.push({meshes:h,type:this._convertV0FlagToV1Type(d==null?void 0:d.firstPersonFlag)})}),new lD(e,s)})}_convertV0FlagToV1Type(n){return n==="FirstPersonOnly"?"firstPersonOnly":n==="ThirdPersonOnly"?"thirdPersonOnly":n==="Both"?"both":"auto"}},cD=new L,uD=new L,AK=new St,hD=class extends Ua{constructor(n){super(),this.vrmHumanoid=n,this._boneAxesMap=new Map,Object.values(n.humanBones).forEach(e=>{const t=new I6(1);t.matrixAutoUpdate=!1,t.material.depthTest=!1,t.material.depthWrite=!1,this.add(t),this._boneAxesMap.set(e,t)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(n=>{n.geometry.dispose(),n.material.dispose()})}updateMatrixWorld(n){Array.from(this._boneAxesMap.entries()).forEach(([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(cD,AK,uD);const i=cD.set(.1,.1,.1).divide(uD);t.matrix.copy(e.node.matrixWorld).scale(i)}),super.updateMatrixWorld(n)}},w2=["hips","spine","chest","upperChest","neck","head","leftEye","rightEye","jaw","leftUpperLeg","leftLowerLeg","leftFoot","leftToes","rightUpperLeg","rightLowerLeg","rightFoot","rightToes","leftShoulder","leftUpperArm","leftLowerArm","leftHand","rightShoulder","rightUpperArm","rightLowerArm","rightHand","leftThumbMetacarpal","leftThumbProximal","leftThumbDistal","leftIndexProximal","leftIndexIntermediate","leftIndexDistal","leftMiddleProximal","leftMiddleIntermediate","leftMiddleDistal","leftRingProximal","leftRingIntermediate","leftRingDistal","leftLittleProximal","leftLittleIntermediate","leftLittleDistal","rightThumbMetacarpal","rightThumbProximal","rightThumbDistal","rightIndexProximal","rightIndexIntermediate","rightIndexDistal","rightMiddleProximal","rightMiddleIntermediate","rightMiddleDistal","rightRingProximal","rightRingIntermediate","rightRingDistal","rightLittleProximal","rightLittleIntermediate","rightLittleDistal"],wK={hips:null,spine:"hips",chest:"spine",upperChest:"chest",neck:"upperChest",head:"neck",leftEye:"head",rightEye:"head",jaw:"head",leftUpperLeg:"hips",leftLowerLeg:"leftUpperLeg",leftFoot:"leftLowerLeg",leftToes:"leftFoot",rightUpperLeg:"hips",rightLowerLeg:"rightUpperLeg",rightFoot:"rightLowerLeg",rightToes:"rightFoot",leftShoulder:"upperChest",leftUpperArm:"leftShoulder",leftLowerArm:"leftUpperArm",leftHand:"leftLowerArm",rightShoulder:"upperChest",rightUpperArm:"rightShoulder",rightLowerArm:"rightUpperArm",rightHand:"rightLowerArm",leftThumbMetacarpal:"leftHand",leftThumbProximal:"leftThumbMetacarpal",leftThumbDistal:"leftThumbProximal",leftIndexProximal:"leftHand",leftIndexIntermediate:"leftIndexProximal",leftIndexDistal:"leftIndexIntermediate",leftMiddleProximal:"leftHand",leftMiddleIntermediate:"leftMiddleProximal",leftMiddleDistal:"leftMiddleIntermediate",leftRingProximal:"leftHand",leftRingIntermediate:"leftRingProximal",leftRingDistal:"leftRingIntermediate",leftLittleProximal:"leftHand",leftLittleIntermediate:"leftLittleProximal",leftLittleDistal:"leftLittleIntermediate",rightThumbMetacarpal:"rightHand",rightThumbProximal:"rightThumbMetacarpal",rightThumbDistal:"rightThumbProximal",rightIndexProximal:"rightHand",rightIndexIntermediate:"rightIndexProximal",rightIndexDistal:"rightIndexIntermediate",rightMiddleProximal:"rightHand",rightMiddleIntermediate:"rightMiddleProximal",rightMiddleDistal:"rightMiddleIntermediate",rightRingProximal:"rightHand",rightRingIntermediate:"rightRingProximal",rightRingDistal:"rightRingIntermediate",rightLittleProximal:"rightHand",rightLittleIntermediate:"rightLittleProximal",rightLittleDistal:"rightLittleIntermediate"};function C8(n){return n.invert?n.invert():n.inverse(),n}var cu=new L,uu=new St,RE=class{constructor(n){this.humanBones=n,this.restPose=this.getAbsolutePose()}getAbsolutePose(){const n={};return Object.keys(this.humanBones).forEach(e=>{const t=e,i=this.getBoneNode(t);i&&(cu.copy(i.position),uu.copy(i.quaternion),n[t]={position:cu.toArray(),rotation:uu.toArray()})}),n}getPose(){const n={};return Object.keys(this.humanBones).forEach(e=>{const t=e,i=this.getBoneNode(t);if(!i)return;cu.set(0,0,0),uu.identity();const a=this.restPose[t];a!=null&&a.position&&cu.fromArray(a.position).negate(),a!=null&&a.rotation&&C8(uu.fromArray(a.rotation)),cu.add(i.position),uu.premultiply(i.quaternion),n[t]={position:cu.toArray(),rotation:uu.toArray()}}),n}setPose(n){Object.entries(n).forEach(([e,t])=>{const i=e,a=this.getBoneNode(i);if(!a)return;const r=this.restPose[i];r&&(t!=null&&t.position&&(a.position.fromArray(t.position),r.position&&a.position.add(cu.fromArray(r.position))),t!=null&&t.rotation&&(a.quaternion.fromArray(t.rotation),r.rotation&&a.quaternion.multiply(uu.fromArray(r.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([n,e])=>{const t=this.getBoneNode(n);t&&(e!=null&&e.position&&t.position.fromArray(e.position),e!=null&&e.rotation&&t.quaternion.fromArray(e.rotation))})}getBone(n){var e;return(e=this.humanBones[n])!=null?e:void 0}getBoneNode(n){var e,t;return(t=(e=this.humanBones[n])==null?void 0:e.node)!=null?t:null}},R2=new L,RK=new St,CK=new L,fD=class N8 extends RE{static _setupTransforms(e){const t=new Wt;t.name="VRMHumanoidRig";const i={},a={},r={};w2.forEach(o=>{var c;const h=e.getBoneNode(o);if(h){const f=new L,d=new St;h.updateWorldMatrix(!0,!1),h.matrixWorld.decompose(f,d,R2),i[o]=f,a[o]=h.quaternion.clone();const m=new St;(c=h.parent)==null||c.matrixWorld.decompose(R2,m,R2),r[o]=m}});const s={};return w2.forEach(o=>{var c;const h=e.getBoneNode(o);if(h){const f=i[o];let d=o,m;for(;m==null&&(d=wK[d],d!=null);)m=i[d];const g=new Wt;g.name="Normalized_"+h.name,(d?(c=s[d])==null?void 0:c.node:t).add(g),g.position.copy(f),m&&g.position.sub(m),s[o]={node:g}}}),{rigBones:s,root:t,parentWorldRotations:r,boneRotations:a}}constructor(e){const{rigBones:t,root:i,parentWorldRotations:a,boneRotations:r}=N8._setupTransforms(e);super(t),this.original=e,this.root=i,this._parentWorldRotations=a,this._boneRotations=r}update(){w2.forEach(e=>{const t=this.original.getBoneNode(e);if(t!=null){const i=this.getBoneNode(e),a=this._parentWorldRotations[e],r=RK.copy(a).invert(),s=this._boneRotations[e];if(t.quaternion.copy(i.quaternion).multiply(a).premultiply(r).multiply(s),e==="hips"){const o=i.getWorldPosition(CK);t.parent.updateWorldMatrix(!0,!1);const c=t.parent.matrixWorld,h=o.applyMatrix4(c.invert());t.position.copy(h)}}})}},dD=class D8{get restPose(){return console.warn("VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead."),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,t){var i;this.autoUpdateHumanBones=(i=t==null?void 0:t.autoUpdateHumanBones)!=null?i:!0,this._rawHumanBones=new RE(e),this._normalizedHumanBones=new fD(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new RE(e.humanBones),this._normalizedHumanBones=new fD(this._rawHumanBones),this}clone(){return new D8(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn("VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead."),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn("VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead."),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn("VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead."),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn("VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead."),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn("VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead."),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn("VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead."),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},NK={Hips:"hips",Spine:"spine",Head:"head",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand"},DK=new Set(["1.0","1.0-beta"]),pD={leftThumbProximal:"leftThumbMetacarpal",leftThumbIntermediate:"leftThumbProximal",rightThumbProximal:"rightThumbMetacarpal",rightThumbIntermediate:"rightThumbProximal"},OK=class{get name(){return"VRMHumanoidLoaderPlugin"}constructor(n,e){this.parser=n,this.helperRoot=e==null?void 0:e.helperRoot,this.autoUpdateHumanBones=e==null?void 0:e.autoUpdateHumanBones}afterRoot(n){return vn(this,null,function*(){n.userData.vrmHumanoid=yield this._import(n)})}_import(n){return vn(this,null,function*(){const e=yield this._v1Import(n);if(e)return e;const t=yield this._v0Import(n);return t||null})}_v1Import(n){return vn(this,null,function*(){var e,t;const i=this.parser.json;if(!(((e=i.extensionsUsed)==null?void 0:e.indexOf("VRMC_vrm"))!==-1))return null;const r=(t=i.extensions)==null?void 0:t.VRMC_vrm;if(!r)return null;const s=r.specVersion;if(!DK.has(s))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${s}"`),null;const o=r.humanoid;if(!o)return null;const c=o.humanBones.leftThumbIntermediate!=null||o.humanBones.rightThumbIntermediate!=null,h={};o.humanBones!=null&&(yield Promise.all(Object.entries(o.humanBones).map(d=>vn(this,[d],function*([m,g]){let x=m;const T=g.node;if(c){const v=pD[x];v!=null&&(x=v)}const y=yield this.parser.getDependency("node",T);if(y==null){console.warn(`A glTF node bound to the humanoid bone ${x} (index = ${T}) does not exist`);return}h[x]={node:y}}))));const f=new dD(this._ensureRequiredBonesExist(h),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(n.scene.add(f.normalizedHumanBonesRoot),this.helperRoot){const d=new hD(f);this.helperRoot.add(d),d.renderOrder=this.helperRoot.renderOrder}return f})}_v0Import(n){return vn(this,null,function*(){var e;const i=(e=this.parser.json.extensions)==null?void 0:e.VRM;if(!i)return null;const a=i.humanoid;if(!a)return null;const r={};a.humanBones!=null&&(yield Promise.all(a.humanBones.map(o=>vn(this,null,function*(){const c=o.bone,h=o.node;if(c==null||h==null)return;const f=yield this.parser.getDependency("node",h);if(f==null){console.warn(`A glTF node bound to the humanoid bone ${c} (index = ${h}) does not exist`);return}const d=pD[c],m=d??c;if(r[m]!=null){console.warn(`Multiple bone entries for ${m} detected (index = ${h}), ignoring duplicated entries.`);return}r[m]={node:f}}))));const s=new dD(this._ensureRequiredBonesExist(r),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(n.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){const o=new hD(s);this.helperRoot.add(o),o.renderOrder=this.helperRoot.renderOrder}return s})}_ensureRequiredBonesExist(n){const e=Object.values(NK).filter(t=>n[t]==null);if(e.length>0)throw new Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${e.join(", ")}`);return n}},mD=class extends Ct{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new Ot(new Float32Array(65*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new Ot(new Uint16Array(3*63),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,n=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,n=!0),n&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let n=0;n<64;n++){const e=n/63*this._currentTheta;this._attrPos.setXYZ(n+1,this._currentRadius*Math.sin(e),0,this._currentRadius*Math.cos(e))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<63;n++)this._attrIndex.setXYZ(n*3,0,n+1,n+2);this._attrIndex.needsUpdate=!0}},LK=class extends Ct{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new L,this._currentTail=new L,this._attrPos=new Ot(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new Ot(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,n=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),n=!0),n&&this._buildPosition()}_buildPosition(){for(let n=0;n<32;n++){const e=n/16*Math.PI;this._attrPos.setXYZ(n,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+n,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+n,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(64+n*2,32+n,32+e),this._attrIndex.setXY(128+n*2,64+n,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},Hv=new St,gD=new St,jp=new L,vD=new L,_D=Math.sqrt(2)/2,IK=new St(0,0,-_D,_D),UK=new L(0,1,0),PK=class extends Ua{constructor(n){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=n;{const e=new mD;e.radius=.5;const t=new Ia({color:65280,transparent:!0,opacity:.5,side:ca,depthTest:!1,depthWrite:!1});this._meshPitch=new oi(e,t),this.add(this._meshPitch)}{const e=new mD;e.radius=.5;const t=new Ia({color:16711680,transparent:!0,opacity:.5,side:ca,depthTest:!1,depthWrite:!1});this._meshYaw=new oi(e,t),this.add(this._meshYaw)}{const e=new LK;e.radius=.1;const t=new Bi({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new ir(e,t),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(n){const e=$t.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=e,this._meshYaw.geometry.update();const t=$t.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=t,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(jp),this.vrmLookAt.getLookAtWorldQuaternion(Hv),Hv.multiply(this.vrmLookAt.getFaceFrontQuaternion(gD)),this._meshYaw.position.copy(jp),this._meshYaw.quaternion.copy(Hv),this._meshPitch.position.copy(jp),this._meshPitch.quaternion.copy(Hv),this._meshPitch.quaternion.multiply(gD.setFromAxisAngle(UK,e)),this._meshPitch.quaternion.multiply(IK);const{target:i,autoUpdate:a}=this.vrmLookAt;i!=null&&a&&(i.getWorldPosition(vD).sub(jp),this._lineTarget.geometry.tail.copy(vD),this._lineTarget.geometry.update(),this._lineTarget.position.copy(jp)),super.updateMatrixWorld(n)}},zK=new L,BK=new L;function CE(n,e){return n.matrixWorld.decompose(zK,e,BK),e}function x_(n){return[Math.atan2(-n.z,n.x),Math.atan2(n.y,Math.sqrt(n.x*n.x+n.z*n.z))]}function xD(n){const e=Math.round(n/2/Math.PI);return n-2*Math.PI*e}var yD=new L(0,0,1),HK=new L,FK=new L,GK=new L,VK=new St,C2=new St,SD=new St,kK=new St,N2=new Ei,O8=class L8{constructor(e,t){this.offsetFromHeadBone=new L,this.autoUpdate=!0,this.faceFront=new L(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new St)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn("VRMLookAt: euler is deprecated. use getEuler() instead."),this.getEuler(new Ei)}getEuler(e){return e.set($t.DEG2RAD*this._pitch,$t.DEG2RAD*this._yaw,0,"YXZ")}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMLookAt: humanoid must be same in order to copy");return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new L8(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){const t=this.humanoid.getRawBoneNode("head");return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){const t=this.humanoid.getRawBoneNode("head");return CE(t,e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(yD)<.01)return e.copy(this._restHeadWorldQuaternion).invert();const[t,i]=x_(this.faceFront);return N2.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(N2).premultiply(kK.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(C2),this.getFaceFrontQuaternion(SD),e.copy(yD).applyQuaternion(C2).applyQuaternion(SD).applyEuler(this.getEuler(N2))}lookAt(e){const t=VK.copy(this._restHeadWorldQuaternion).multiply(C8(this.getLookAtWorldQuaternion(C2))),i=this.getLookAtWorldPosition(FK),a=GK.copy(e).sub(i).applyQuaternion(t).normalize(),[r,s]=x_(this.faceFront),[o,c]=x_(a),h=xD(o-r),f=xD(s-c);this._yaw=$t.RAD2DEG*h,this._pitch=$t.RAD2DEG*f,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(HK)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};O8.EULER_ORDER="YXZ";var WK=O8,XK=new L(0,0,1),Xs=new St,gf=new St,Wr=new Ei(0,0,0,"YXZ"),y_=class{constructor(n,e,t,i,a){this.humanoid=n,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=t,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=a,this.faceFront=new L(0,0,1),this._restQuatLeftEye=new St,this._restQuatRightEye=new St,this._restLeftEyeParentWorldQuat=new St,this._restRightEyeParentWorldQuat=new St;const r=this.humanoid.getRawBoneNode("leftEye"),s=this.humanoid.getRawBoneNode("rightEye");r&&(this._restQuatLeftEye.copy(r.quaternion),CE(r.parent,this._restLeftEyeParentWorldQuat)),s&&(this._restQuatRightEye.copy(s.quaternion),CE(s.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(n,e){const t=this.humanoid.getRawBoneNode("leftEye"),i=this.humanoid.getRawBoneNode("rightEye"),a=this.humanoid.getNormalizedBoneNode("leftEye"),r=this.humanoid.getNormalizedBoneNode("rightEye");t&&(e<0?Wr.x=-$t.DEG2RAD*this.rangeMapVerticalDown.map(-e):Wr.x=$t.DEG2RAD*this.rangeMapVerticalUp.map(e),n<0?Wr.y=-$t.DEG2RAD*this.rangeMapHorizontalInner.map(-n):Wr.y=$t.DEG2RAD*this.rangeMapHorizontalOuter.map(n),Xs.setFromEuler(Wr),this._getWorldFaceFrontQuat(gf),a.quaternion.copy(gf).multiply(Xs).multiply(gf.invert()),Xs.copy(this._restLeftEyeParentWorldQuat),t.quaternion.copy(a.quaternion).multiply(Xs).premultiply(Xs.invert()).multiply(this._restQuatLeftEye)),i&&(e<0?Wr.x=-$t.DEG2RAD*this.rangeMapVerticalDown.map(-e):Wr.x=$t.DEG2RAD*this.rangeMapVerticalUp.map(e),n<0?Wr.y=-$t.DEG2RAD*this.rangeMapHorizontalOuter.map(-n):Wr.y=$t.DEG2RAD*this.rangeMapHorizontalInner.map(n),Xs.setFromEuler(Wr),this._getWorldFaceFrontQuat(gf),r.quaternion.copy(gf).multiply(Xs).multiply(gf.invert()),Xs.copy(this._restRightEyeParentWorldQuat),i.quaternion.copy(r.quaternion).multiply(Xs).premultiply(Xs.invert()).multiply(this._restQuatRightEye))}lookAt(n){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const e=$t.RAD2DEG*n.y,t=$t.RAD2DEG*n.x;this.applyYawPitch(e,t)}_getWorldFaceFrontQuat(n){if(this.faceFront.distanceToSquared(XK)<.01)return n.identity();const[e,t]=x_(this.faceFront);return Wr.set(0,.5*Math.PI+e,t,"YZX"),n.setFromEuler(Wr)}};y_.type="bone";var NE=class{constructor(n,e,t,i,a){this.expressions=n,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=t,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=a}applyYawPitch(n,e){e<0?(this.expressions.setValue("lookDown",0),this.expressions.setValue("lookUp",this.rangeMapVerticalUp.map(-e))):(this.expressions.setValue("lookUp",0),this.expressions.setValue("lookDown",this.rangeMapVerticalDown.map(e))),n<0?(this.expressions.setValue("lookLeft",0),this.expressions.setValue("lookRight",this.rangeMapHorizontalOuter.map(-n))):(this.expressions.setValue("lookRight",0),this.expressions.setValue("lookLeft",this.rangeMapHorizontalOuter.map(n)))}lookAt(n){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const e=$t.RAD2DEG*n.y,t=$t.RAD2DEG*n.x;this.applyYawPitch(e,t)}};NE.type="expression";var TD=class{constructor(n,e){this.inputMaxValue=n,this.outputScale=e}map(n){return this.outputScale*S8(n/this.inputMaxValue)}},YK=new Set(["1.0","1.0-beta"]),Fv=.01,qK=class{get name(){return"VRMLookAtLoaderPlugin"}constructor(n,e){this.parser=n,this.helperRoot=e==null?void 0:e.helperRoot}afterRoot(n){return vn(this,null,function*(){const e=n.userData.vrmHumanoid;if(e===null)return;if(e===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");const t=n.userData.vrmExpressionManager;if(t!==null){if(t===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first");n.userData.vrmLookAt=yield this._import(n,e,t)}})}_import(n,e,t){return vn(this,null,function*(){if(e==null||t==null)return null;const i=yield this._v1Import(n,e,t);if(i)return i;const a=yield this._v0Import(n,e,t);return a||null})}_v1Import(n,e,t){return vn(this,null,function*(){var i,a,r;const s=this.parser.json;if(!(((i=s.extensionsUsed)==null?void 0:i.indexOf("VRMC_vrm"))!==-1))return null;const c=(a=s.extensions)==null?void 0:a.VRMC_vrm;if(!c)return null;const h=c.specVersion;if(!YK.has(h))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${h}"`),null;const f=c.lookAt;if(!f)return null;const d=f.type==="expression"?1:10,m=this._v1ImportRangeMap(f.rangeMapHorizontalInner,d),g=this._v1ImportRangeMap(f.rangeMapHorizontalOuter,d),x=this._v1ImportRangeMap(f.rangeMapVerticalDown,d),T=this._v1ImportRangeMap(f.rangeMapVerticalUp,d);let y;f.type==="expression"?y=new NE(t,m,g,x,T):y=new y_(e,m,g,x,T);const v=this._importLookAt(e,y);return v.offsetFromHeadBone.fromArray((r=f.offsetFromHeadBone)!=null?r:[0,.06,0]),v})}_v1ImportRangeMap(n,e){var t,i;let a=(t=n==null?void 0:n.inputMaxValue)!=null?t:90;const r=(i=n==null?void 0:n.outputScale)!=null?i:e;return a(console.error(s),console.warn("VRMMetaLoaderPlugin: Failed to load a thumbnail image"),null))})}},QK=class{constructor(n){this.scene=n.scene,this.meta=n.meta,this.humanoid=n.humanoid,this.expressionManager=n.expressionManager,this.firstPerson=n.firstPerson,this.lookAt=n.lookAt}update(n){this.humanoid.update(),this.lookAt&&this.lookAt.update(n),this.expressionManager&&this.expressionManager.update()}},JK=class extends QK{constructor(n){super(n),this.materials=n.materials,this.springBoneManager=n.springBoneManager,this.nodeConstraintManager=n.nodeConstraintManager}update(n){super.update(n),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(n),this.materials&&this.materials.forEach(e=>{e.update&&e.update(n)})}},$K=Object.defineProperty,ED=Object.getOwnPropertySymbols,eQ=Object.prototype.hasOwnProperty,tQ=Object.prototype.propertyIsEnumerable,MD=(n,e,t)=>e in n?$K(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,bD=(n,e)=>{for(var t in e||(e={}))eQ.call(e,t)&&MD(n,t,e[t]);if(ED)for(var t of ED(e))tQ.call(e,t)&&MD(n,t,e[t]);return n},wu=(n,e,t)=>new Promise((i,a)=>{var r=c=>{try{o(t.next(c))}catch(h){a(h)}},s=c=>{try{o(t.throw(c))}catch(h){a(h)}},o=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,s);o((t=t.apply(n,e)).next())}),nQ={"":3e3,srgb:3001};function iQ(n,e){parseInt(Cs,10)>=152?n.colorSpace=e:n.encoding=nQ[e]}var aQ=class{get pending(){return Promise.all(this._pendings)}constructor(n,e){this._parser=n,this._materialParams=e,this._pendings=[]}assignPrimitive(n,e){e!=null&&(this._materialParams[n]=e)}assignColor(n,e,t){if(e!=null){const i=new je().fromArray(e);t&&i.convertSRGBToLinear(),this._materialParams[n]=i}}assignTexture(n,e,t){return wu(this,null,function*(){const i=wu(this,null,function*(){e!=null&&(yield this._parser.assignTexture(this._materialParams,n,e),t&&iQ(this._materialParams[n],"srgb"))});return this._pendings.push(i),i})}assignTextureByIndex(n,e,t){return wu(this,null,function*(){return this.assignTexture(n,e!=null?{index:e}:void 0,t)})}},rQ=`// #define PHONG - -varying vec3 vViewPosition; - -#ifndef FLAT_SHADED - varying vec3 vNormal; -#endif - -#include - -// #include -#ifdef MTOON_USE_UV - varying vec2 vUv; - - // COMPAT: pre-r151 uses a common uvTransform - #if THREE_VRM_THREE_REVISION < 151 - uniform mat3 uvTransform; - #endif -#endif - -// #include -// COMAPT: pre-r151 uses uv2 for lightMap and aoMap -#if THREE_VRM_THREE_REVISION < 151 - #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) - attribute vec2 uv2; - varying vec2 vUv2; - uniform mat3 uv2Transform; - #endif -#endif - -// #include -// #include -#include -#include -#include -#include -#include -#include -#include - -#ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE - uniform sampler2D outlineWidthMultiplyTexture; - uniform mat3 outlineWidthMultiplyTextureUvTransform; -#endif - -uniform float outlineWidthFactor; - -void main() { - - // #include - #ifdef MTOON_USE_UV - // COMPAT: pre-r151 uses a common uvTransform - #if THREE_VRM_THREE_REVISION >= 151 - vUv = uv; - #else - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - #endif - #endif - - // #include - // COMAPT: pre-r151 uses uv2 for lightMap and aoMap - #if THREE_VRM_THREE_REVISION < 151 - #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) - vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy; - #endif - #endif - - #include - - #include - #include - #include - #include - - // we need this to compute the outline properly - objectNormal = normalize( objectNormal ); - - #include - - #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED - vNormal = normalize( transformedNormal ); - #endif - - #include - - #include - #include - // #include - #include - #include - #include - - vViewPosition = - mvPosition.xyz; - - #ifdef OUTLINE - float worldNormalLength = length( transformedNormal ); - vec3 outlineOffset = outlineWidthFactor * worldNormalLength * objectNormal; - - #ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE - vec2 outlineWidthMultiplyTextureUv = ( outlineWidthMultiplyTextureUvTransform * vec3( vUv, 1 ) ).xy; - float outlineTex = texture2D( outlineWidthMultiplyTexture, outlineWidthMultiplyTextureUv ).g; - outlineOffset *= outlineTex; - #endif - - #ifdef OUTLINE_WIDTH_SCREEN - outlineOffset *= vViewPosition.z / projectionMatrix[ 1 ].y; - #endif - - gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 ); - - gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic - #endif - - #include - // #include - #include - #include - -}`,sQ=`// #define PHONG - -uniform vec3 litFactor; - -uniform float opacity; - -uniform vec3 shadeColorFactor; -#ifdef USE_SHADEMULTIPLYTEXTURE - uniform sampler2D shadeMultiplyTexture; - uniform mat3 shadeMultiplyTextureUvTransform; -#endif - -uniform float shadingShiftFactor; -uniform float shadingToonyFactor; - -#ifdef USE_SHADINGSHIFTTEXTURE - uniform sampler2D shadingShiftTexture; - uniform mat3 shadingShiftTextureUvTransform; - uniform float shadingShiftTextureScale; -#endif - -uniform float giEqualizationFactor; - -uniform vec3 parametricRimColorFactor; -#ifdef USE_RIMMULTIPLYTEXTURE - uniform sampler2D rimMultiplyTexture; - uniform mat3 rimMultiplyTextureUvTransform; -#endif -uniform float rimLightingMixFactor; -uniform float parametricRimFresnelPowerFactor; -uniform float parametricRimLiftFactor; - -#ifdef USE_MATCAPTEXTURE - uniform vec3 matcapFactor; - uniform sampler2D matcapTexture; - uniform mat3 matcapTextureUvTransform; -#endif - -uniform vec3 emissive; -uniform float emissiveIntensity; - -uniform vec3 outlineColorFactor; -uniform float outlineLightingMixFactor; - -#ifdef USE_UVANIMATIONMASKTEXTURE - uniform sampler2D uvAnimationMaskTexture; - uniform mat3 uvAnimationMaskTextureUvTransform; -#endif - -uniform float uvAnimationScrollXOffset; -uniform float uvAnimationScrollYOffset; -uniform float uvAnimationRotationPhase; - -#include -#include -#include -#include - -// #include -#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) ) - varying vec2 vUv; -#endif - -// #include -// COMAPT: pre-r151 uses uv2 for lightMap and aoMap -#if THREE_VRM_THREE_REVISION < 151 - #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) - varying vec2 vUv2; - #endif -#endif - -#include - -#ifdef USE_MAP - uniform mat3 mapUvTransform; -#endif - -// #include - -#include - -#include -// #include -#include - -#ifdef USE_EMISSIVEMAP - uniform mat3 emissiveMapUvTransform; -#endif - -// #include -// #include -// #include -#include - -// #include -// COMPAT: pre-r151 doesn't have BRDF_Lambert in -#if THREE_VRM_THREE_REVISION < 151 - vec3 BRDF_Lambert( const in vec3 diffuseColor ) { - return RECIPROCAL_PI * diffuseColor; - } -#endif - -#include - -#include - -// #include -varying vec3 vViewPosition; - -struct MToonMaterial { - vec3 diffuseColor; - vec3 shadeColor; - float shadingShift; -}; - -float linearstep( float a, float b, float t ) { - return clamp( ( t - a ) / ( b - a ), 0.0, 1.0 ); -} - -/** - * Convert NdotL into toon shading factor using shadingShift and shadingToony - */ -float getShading( - const in float dotNL, - const in float shadow, - const in float shadingShift -) { - float shading = dotNL; - shading = shading + shadingShift; - shading = linearstep( -1.0 + shadingToonyFactor, 1.0 - shadingToonyFactor, shading ); - shading *= shadow; - return shading; -} - -/** - * Mix diffuseColor and shadeColor using shading factor and light color - */ -vec3 getDiffuse( - const in MToonMaterial material, - const in float shading, - in vec3 lightColor -) { - #ifdef DEBUG_LITSHADERATE - return vec3( BRDF_Lambert( shading * lightColor ) ); - #endif - - vec3 col = lightColor * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, shading ) ); - - // The "comment out if you want to PBR absolutely" line - #ifdef V0_COMPAT_SHADE - col = min( col, material.diffuseColor ); - #endif - - return col; -} - -// COMPAT: pre-r156 uses a struct GeometricContext -#if THREE_VRM_THREE_REVISION >= 157 - void RE_Direct_MToon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) { - float dotNL = clamp( dot( geometryNormal, directLight.direction ), -1.0, 1.0 ); - vec3 irradiance = directLight.color; - - // directSpecular will be used for rim lighting, not an actual specular - reflectedLight.directSpecular += irradiance; - - irradiance *= dotNL; - - float shading = getShading( dotNL, shadow, material.shadingShift ); - - // toon shaded diffuse - reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color ); - } - - void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, inout ReflectedLight reflectedLight ) { - // indirect diffuse will use diffuseColor, no shadeColor involved - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); - - // directSpecular will be used for rim lighting, not an actual specular - reflectedLight.directSpecular += irradiance; - } -#else - void RE_Direct_MToon( const in IncidentLight directLight, const in GeometricContext geometry, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) { - float dotNL = clamp( dot( geometry.normal, directLight.direction ), -1.0, 1.0 ); - vec3 irradiance = directLight.color; - - // directSpecular will be used for rim lighting, not an actual specular - reflectedLight.directSpecular += irradiance; - - irradiance *= dotNL; - - float shading = getShading( dotNL, shadow, material.shadingShift ); - - // toon shaded diffuse - reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color ); - } - - void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in GeometricContext geometry, const in MToonMaterial material, inout ReflectedLight reflectedLight ) { - // indirect diffuse will use diffuseColor, no shadeColor involved - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); - - // directSpecular will be used for rim lighting, not an actual specular - reflectedLight.directSpecular += irradiance; - } -#endif - -#define RE_Direct RE_Direct_MToon -#define RE_IndirectDiffuse RE_IndirectDiffuse_MToon -#define Material_LightProbeLOD( material ) (0) - -#include -// #include - -// #include -#ifdef USE_NORMALMAP - - uniform sampler2D normalMap; - uniform mat3 normalMapUvTransform; - uniform vec2 normalScale; - -#endif - -// COMPAT: pre-r151 -// USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151 -#if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP ) - - uniform mat3 normalMatrix; - -#endif - -// COMPAT: pre-r151 -// USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151 -#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( TANGENTSPACE_NORMALMAP ) ) - - // Per-Pixel Tangent Space Normal Mapping - // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html - - // three-vrm specific change: it requires \`uv\` as an input in order to support uv scrolls - - // Temporary compat against shader change @ Three.js r126, r151 - #if THREE_VRM_THREE_REVISION >= 151 - - 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 ); - - } - - #else - - vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) { - - vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) ); - vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) ); - vec2 st0 = dFdx( uv.st ); - vec2 st1 = dFdy( uv.st ); - - vec3 N = normalize( 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; - - // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0 - // TODO: Is this still required? Or shall I make a PR about it? - if ( length( T ) == 0.0 || length( B ) == 0.0 ) { - return surf_norm; - } - - float det = max( dot( T, T ), dot( B, B ) ); - float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det ); - - return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z ); - - } - - #endif - -#endif - -// #include -#include -#include - -// == post correction ========================================================== -void postCorrection() { - #include - #include - #include - #include - #include -} - -// == main procedure =========================================================== -void main() { - #include - - vec2 uv = vec2(0.5, 0.5); - - #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) ) - uv = vUv; - - float uvAnimMask = 1.0; - #ifdef USE_UVANIMATIONMASKTEXTURE - vec2 uvAnimationMaskTextureUv = ( uvAnimationMaskTextureUvTransform * vec3( uv, 1 ) ).xy; - uvAnimMask = texture2D( uvAnimationMaskTexture, uvAnimationMaskTextureUv ).b; - #endif - - float uvRotCos = cos( uvAnimationRotationPhase * uvAnimMask ); - float uvRotSin = sin( uvAnimationRotationPhase * uvAnimMask ); - uv = mat2( uvRotCos, -uvRotSin, uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5; - uv = uv + vec2( uvAnimationScrollXOffset, uvAnimationScrollYOffset ) * uvAnimMask; - #endif - - #ifdef DEBUG_UV - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) ) - gl_FragColor = vec4( uv, 0.0, 1.0 ); - #endif - return; - #endif - - vec4 diffuseColor = vec4( litFactor, opacity ); - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive * emissiveIntensity; - - #include - - // #include - #ifdef USE_MAP - vec2 mapUv = ( mapUvTransform * vec3( uv, 1 ) ).xy; - vec4 sampledDiffuseColor = texture2D( map, mapUv ); - #ifdef DECODE_VIDEO_TEXTURE - sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w ); - #endif - diffuseColor *= sampledDiffuseColor; - #endif - - // #include - #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) ) - diffuseColor.rgb *= vColor; - #endif - - // #include - - #include - - // #include - - // #include - 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 - - #ifdef USE_NORMALMAP - - vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy; - - #endif - - #ifdef USE_NORMALMAP_TANGENTSPACE - - #ifdef USE_TANGENT - - mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - - #else - - mat3 tbn = getTangentFrame( - vViewPosition, normal, normalMapUv ); - - #endif - - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - - tbn[0] *= faceDirection; - tbn[1] *= faceDirection; - - #endif - - #endif - - #ifdef USE_CLEARCOAT_NORMALMAP - - #ifdef USE_TANGENT - - mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - - #else - - mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); - - #endif - - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - - tbn2[0] *= faceDirection; - tbn2[1] *= faceDirection; - - #endif - - #endif - - // non perturbed normal for clearcoat among others - - vec3 nonPerturbedNormal = normal; - - #ifdef OUTLINE - normal *= -1.0; - #endif - - // #include - - // COMPAT: pre-r151 - // USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151 - #if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP ) - - normal = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals - - #ifdef FLIP_SIDED - - normal = - normal; - - #endif - - #ifdef DOUBLE_SIDED - - normal = normal * faceDirection; - - #endif - - normal = normalize( normalMatrix * normal ); - - // COMPAT: pre-r151 - // USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151 - #elif defined( USE_NORMALMAP_TANGENTSPACE ) || defined( TANGENTSPACE_NORMALMAP ) - - vec3 mapN = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; - mapN.xy *= normalScale; - - // COMPAT: pre-r151 - #if THREE_VRM_THREE_REVISION >= 151 || defined( USE_TANGENT ) - - normal = normalize( tbn * mapN ); - - #else - - normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection ); - - #endif - - #endif - - // #include - #ifdef USE_EMISSIVEMAP - vec2 emissiveMapUv = ( emissiveMapUvTransform * vec3( uv, 1 ) ).xy; - totalEmissiveRadiance *= texture2D( emissiveMap, emissiveMapUv ).rgb; - #endif - - #ifdef DEBUG_NORMAL - gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 ); - return; - #endif - - // -- MToon: lighting -------------------------------------------------------- - // accumulation - // #include - MToonMaterial material; - - material.diffuseColor = diffuseColor.rgb; - - material.shadeColor = shadeColorFactor; - #ifdef USE_SHADEMULTIPLYTEXTURE - vec2 shadeMultiplyTextureUv = ( shadeMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy; - material.shadeColor *= texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv ).rgb; - #endif - - #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) ) - material.shadeColor.rgb *= vColor; - #endif - - material.shadingShift = shadingShiftFactor; - #ifdef USE_SHADINGSHIFTTEXTURE - vec2 shadingShiftTextureUv = ( shadingShiftTextureUvTransform * vec3( uv, 1 ) ).xy; - material.shadingShift += texture2D( shadingShiftTexture, shadingShiftTextureUv ).r * shadingShiftTextureScale; - #endif - - // #include - - // MToon Specific changes: - // Since we want to take shadows into account of shading instead of irradiance, - // we had to modify the codes that multiplies the results of shadowmap into color of direct lights. - - // COMPAT: pre-r156 uses a struct GeometricContext - #if THREE_VRM_THREE_REVISION >= 157 - vec3 geometryPosition = - vViewPosition; - vec3 geometryNormal = normal; - vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); - - vec3 geometryClearcoatNormal; - - #ifdef USE_CLEARCOAT - - geometryClearcoatNormal = clearcoatNormal; - - #endif - #else - GeometricContext geometry; - - geometry.position = - vViewPosition; - geometry.normal = normal; - geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); - - #ifdef USE_CLEARCOAT - - geometry.clearcoatNormal = clearcoatNormal; - - #endif - #endif - - IncidentLight directLight; - - // since these variables will be used in unrolled loop, we have to define in prior - float shadow; - - #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 ]; - - // COMPAT: pre-r156 uses a struct GeometricContext - #if THREE_VRM_THREE_REVISION >= 157 - getPointLightInfo( pointLight, geometryPosition, directLight ); - #else - getPointLightInfo( pointLight, geometry, directLight ); - #endif - - shadow = 1.0; - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - // COMPAT: pre-r166 - // r166 introduced shadowIntensity - #if THREE_VRM_THREE_REVISION >= 166 - shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #else - shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif - #endif - - // COMPAT: pre-r156 uses a struct GeometricContext - #if THREE_VRM_THREE_REVISION >= 157 - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight ); - #else - RE_Direct( directLight, geometry, material, shadow, reflectedLight ); - #endif - - } - #pragma unroll_loop_end - - #endif - - #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - - SpotLight spotLight; - #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 ]; - - // COMPAT: pre-r156 uses a struct GeometricContext - #if THREE_VRM_THREE_REVISION >= 157 - getSpotLightInfo( spotLight, geometryPosition, directLight ); - #else - getSpotLightInfo( spotLight, geometry, directLight ); - #endif - - shadow = 1.0; - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - // COMPAT: pre-r166 - // r166 introduced shadowIntensity - #if THREE_VRM_THREE_REVISION >= 166 - shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; - #else - shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; - #endif - #endif - - // COMPAT: pre-r156 uses a struct GeometricContext - #if THREE_VRM_THREE_REVISION >= 157 - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight ); - #else - RE_Direct( directLight, geometry, material, shadow, reflectedLight ); - #endif - - } - #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 ]; - - // COMPAT: pre-r156 uses a struct GeometricContext - #if THREE_VRM_THREE_REVISION >= 157 - getDirectionalLightInfo( directionalLight, directLight ); - #else - getDirectionalLightInfo( directionalLight, geometry, directLight ); - #endif - - shadow = 1.0; - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - // COMPAT: pre-r166 - // r166 introduced shadowIntensity - #if THREE_VRM_THREE_REVISION >= 166 - shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #else - shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - #endif - - // COMPAT: pre-r156 uses a struct GeometricContext - #if THREE_VRM_THREE_REVISION >= 157 - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight ); - #else - RE_Direct( directLight, geometry, material, shadow, reflectedLight ); - #endif - - } - #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, geometry, material, reflectedLight ); - - // } - // #pragma unroll_loop_end - - // #endif - - #if defined( RE_IndirectDiffuse ) - - vec3 iblIrradiance = vec3( 0.0 ); - - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - - // COMPAT: pre-r156 uses a struct GeometricContext - // COMPAT: pre-r156 doesn't have a define USE_LIGHT_PROBES - #if THREE_VRM_THREE_REVISION >= 157 - #if defined( USE_LIGHT_PROBES ) - irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); - #endif - #else - irradiance += getLightProbeIrradiance( lightProbe, geometry.normal ); - #endif - - #if ( NUM_HEMI_LIGHTS > 0 ) - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - - // COMPAT: pre-r156 uses a struct GeometricContext - #if THREE_VRM_THREE_REVISION >= 157 - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - #else - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal ); - #endif - - } - #pragma unroll_loop_end - - #endif - - #endif - - // #if defined( RE_IndirectSpecular ) - - // vec3 radiance = vec3( 0.0 ); - // vec3 clearcoatRadiance = vec3( 0.0 ); - - // #endif - - #include - #include - - // modulation - #include - - vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; - - #ifdef DEBUG_LITSHADERATE - gl_FragColor = vec4( col, diffuseColor.a ); - postCorrection(); - return; - #endif - - // -- MToon: rim lighting ----------------------------------------- - vec3 viewDir = normalize( vViewPosition ); - - #ifndef PHYSICALLY_CORRECT_LIGHTS - reflectedLight.directSpecular /= PI; - #endif - vec3 rimMix = mix( vec3( 1.0 ), reflectedLight.directSpecular, 1.0 ); - - vec3 rim = parametricRimColorFactor * pow( saturate( 1.0 - dot( viewDir, normal ) + parametricRimLiftFactor ), parametricRimFresnelPowerFactor ); - - #ifdef USE_MATCAPTEXTURE - { - vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) ); - vec3 y = cross( viewDir, x ); // guaranteed to be normalized - vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) ); - sphereUv = ( matcapTextureUvTransform * vec3( sphereUv, 1 ) ).xy; - vec3 matcap = texture2D( matcapTexture, sphereUv ).rgb; - rim += matcapFactor * matcap; - } - #endif - - #ifdef USE_RIMMULTIPLYTEXTURE - vec2 rimMultiplyTextureUv = ( rimMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy; - rim *= texture2D( rimMultiplyTexture, rimMultiplyTextureUv ).rgb; - #endif - - col += rimMix * rim; - - // -- MToon: Emission -------------------------------------------------------- - col += totalEmissiveRadiance; - - // #include - - // -- Almost done! ----------------------------------------------------------- - #if defined( OUTLINE ) - col = outlineColorFactor.rgb * mix( vec3( 1.0 ), col, outlineLightingMixFactor ); - #endif - - #ifdef OPAQUE - diffuseColor.a = 1.0; - #endif - - gl_FragColor = vec4( col, diffuseColor.a ); - postCorrection(); -} -`,oQ={None:"none"},AD={None:"none",ScreenCoordinates:"screenCoordinates"},lQ={3e3:"",3001:"srgb"};function D2(n){return parseInt(Cs,10)>=152?n.colorSpace:lQ[n.encoding]}var cQ=class extends Vi{constructor(n={}){var e;super({vertexShader:rQ,fragmentShader:sQ}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=ll,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=oQ.None,this._outlineWidthMode=AD.None,this._isOutline=!1,n.transparentWithZWrite&&(n.depthWrite=!0),delete n.transparentWithZWrite,n.fog=!0,n.lights=!0,n.clipping=!0,this.uniforms=Mb.merge([at.common,at.normalmap,at.emissivemap,at.fog,at.lights,{litFactor:{value:new je(1,1,1)},mapUvTransform:{value:new Et},colorAlpha:{value:1},normalMapUvTransform:{value:new Et},shadeColorFactor:{value:new je(0,0,0)},shadeMultiplyTexture:{value:null},shadeMultiplyTextureUvTransform:{value:new Et},shadingShiftFactor:{value:0},shadingShiftTexture:{value:null},shadingShiftTextureUvTransform:{value:new Et},shadingShiftTextureScale:{value:1},shadingToonyFactor:{value:.9},giEqualizationFactor:{value:.9},matcapFactor:{value:new je(1,1,1)},matcapTexture:{value:null},matcapTextureUvTransform:{value:new Et},parametricRimColorFactor:{value:new je(0,0,0)},rimMultiplyTexture:{value:null},rimMultiplyTextureUvTransform:{value:new Et},rimLightingMixFactor:{value:1},parametricRimFresnelPowerFactor:{value:5},parametricRimLiftFactor:{value:0},emissive:{value:new je(0,0,0)},emissiveIntensity:{value:1},emissiveMapUvTransform:{value:new Et},outlineWidthMultiplyTexture:{value:null},outlineWidthMultiplyTextureUvTransform:{value:new Et},outlineWidthFactor:{value:0},outlineColorFactor:{value:new je(0,0,0)},outlineLightingMixFactor:{value:1},uvAnimationMaskTexture:{value:null},uvAnimationMaskTextureUvTransform:{value:new Et},uvAnimationScrollXOffset:{value:0},uvAnimationScrollYOffset:{value:0},uvAnimationRotationPhase:{value:0}},(e=n.uniforms)!=null?e:{}]),this.setValues(n),this._uploadUniformsWorkaround(),this.customProgramCacheKey=()=>[...Object.entries(this._generateDefines()).map(([t,i])=>`${t}:${i}`),this.matcapTexture?`matcapTextureColorSpace:${D2(this.matcapTexture)}`:"",this.shadeMultiplyTexture?`shadeMultiplyTextureColorSpace:${D2(this.shadeMultiplyTexture)}`:"",this.rimMultiplyTexture?`rimMultiplyTextureColorSpace:${D2(this.rimMultiplyTexture)}`:""].join(","),this.onBeforeCompile=t=>{const i=parseInt(Cs,10),a=Object.entries(bD(bD({},this._generateDefines()),this.defines)).filter(([r,s])=>!!s).map(([r,s])=>`#define ${r} ${s}`).join(` -`)+` -`;t.vertexShader=a+t.vertexShader,t.fragmentShader=a+t.fragmentShader,i<154&&(t.fragmentShader=t.fragmentShader.replace("#include ","#include "))}}get color(){return this.uniforms.litFactor.value}set color(n){this.uniforms.litFactor.value=n}get map(){return this.uniforms.map.value}set map(n){this.uniforms.map.value=n}get normalMap(){return this.uniforms.normalMap.value}set normalMap(n){this.uniforms.normalMap.value=n}get normalScale(){return this.uniforms.normalScale.value}set normalScale(n){this.uniforms.normalScale.value=n}get emissive(){return this.uniforms.emissive.value}set emissive(n){this.uniforms.emissive.value=n}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(n){this.uniforms.emissiveIntensity.value=n}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(n){this.uniforms.emissiveMap.value=n}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(n){this.uniforms.shadeColorFactor.value=n}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(n){this.uniforms.shadeMultiplyTexture.value=n}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(n){this.uniforms.shadingShiftFactor.value=n}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(n){this.uniforms.shadingShiftTexture.value=n}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(n){this.uniforms.shadingShiftTextureScale.value=n}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(n){this.uniforms.shadingToonyFactor.value=n}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(n){this.uniforms.giEqualizationFactor.value=n}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(n){this.uniforms.matcapFactor.value=n}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(n){this.uniforms.matcapTexture.value=n}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(n){this.uniforms.parametricRimColorFactor.value=n}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(n){this.uniforms.rimMultiplyTexture.value=n}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(n){this.uniforms.rimLightingMixFactor.value=n}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(n){this.uniforms.parametricRimFresnelPowerFactor.value=n}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(n){this.uniforms.parametricRimLiftFactor.value=n}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(n){this.uniforms.outlineWidthMultiplyTexture.value=n}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(n){this.uniforms.outlineWidthFactor.value=n}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(n){this.uniforms.outlineColorFactor.value=n}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(n){this.uniforms.outlineLightingMixFactor.value=n}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(n){this.uniforms.uvAnimationMaskTexture.value=n}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(n){this.uniforms.uvAnimationScrollXOffset.value=n}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(n){this.uniforms.uvAnimationScrollYOffset.value=n}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(n){this.uniforms.uvAnimationRotationPhase.value=n}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(n){this._ignoreVertexColor=n,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(n){this._v0CompatShade=n,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(n){this._debugMode=n,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(n){this._outlineWidthMode=n,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(n){this._isOutline=n,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(n){this._uploadUniformsWorkaround(),this._updateUVAnimation(n)}copy(n){return super.copy(n),this.map=n.map,this.normalMap=n.normalMap,this.emissiveMap=n.emissiveMap,this.shadeMultiplyTexture=n.shadeMultiplyTexture,this.shadingShiftTexture=n.shadingShiftTexture,this.matcapTexture=n.matcapTexture,this.rimMultiplyTexture=n.rimMultiplyTexture,this.outlineWidthMultiplyTexture=n.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=n.uvAnimationMaskTexture,this.normalMapType=n.normalMapType,this.uvAnimationScrollXSpeedFactor=n.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=n.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=n.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=n.ignoreVertexColor,this.v0CompatShade=n.v0CompatShade,this.debugMode=n.debugMode,this.outlineWidthMode=n.outlineWidthMode,this.isOutline=n.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(n){this.uniforms.uvAnimationScrollXOffset.value+=n*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=n*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=n*this.uvAnimationRotationSpeedFactor,this.uniforms.alphaTest.value=this.alphaTest,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform),this.uniformsNeedUpdate=!0}_generateDefines(){const n=parseInt(Cs,10),e=this.outlineWidthMultiplyTexture!==null,t=this.map!==null||this.normalMap!==null||this.emissiveMap!==null||this.shadeMultiplyTexture!==null||this.shadingShiftTexture!==null||this.rimMultiplyTexture!==null||this.uvAnimationMaskTexture!==null;return{THREE_VRM_THREE_REVISION:n,OUTLINE:this._isOutline,MTOON_USE_UV:e||t,MTOON_UVS_VERTEX_ONLY:e&&!t,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:this.shadeMultiplyTexture!==null,USE_SHADINGSHIFTTEXTURE:this.shadingShiftTexture!==null,USE_MATCAPTEXTURE:this.matcapTexture!==null,USE_RIMMULTIPLYTEXTURE:this.rimMultiplyTexture!==null,USE_OUTLINEWIDTHMULTIPLYTEXTURE:this._isOutline&&this.outlineWidthMultiplyTexture!==null,USE_UVANIMATIONMASKTEXTURE:this.uvAnimationMaskTexture!==null,IGNORE_VERTEX_COLOR:this._ignoreVertexColor===!0,DEBUG_NORMAL:this._debugMode==="normal",DEBUG_LITSHADERATE:this._debugMode==="litShadeRate",DEBUG_UV:this._debugMode==="uv",OUTLINE_WIDTH_SCREEN:this._isOutline&&this._outlineWidthMode===AD.ScreenCoordinates}}_updateTextureMatrix(n,e){n.value&&(n.value.matrixAutoUpdate&&n.value.updateMatrix(),e.value.copy(n.value.matrix))}},uQ=new Set(["1.0","1.0-beta"]),I8=class S_{get name(){return S_.EXTENSION_NAME}constructor(e,t={}){var i,a,r,s;this.parser=e,this.materialType=(i=t.materialType)!=null?i:cQ,this.renderOrderOffset=(a=t.renderOrderOffset)!=null?a:0,this.v0CompatShade=(r=t.v0CompatShade)!=null?r:!1,this.debugMode=(s=t.debugMode)!=null?s:"none",this._mToonMaterialSet=new Set}beforeRoot(){return wu(this,null,function*(){this._removeUnlitExtensionIfMToonExists()})}afterRoot(e){return wu(this,null,function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)})}getMaterialType(e){return this._getMToonExtension(e)?this.materialType:null}extendMaterialParams(e,t){const i=this._getMToonExtension(e);return i?this._extendMaterialParams(i,t):null}loadMesh(e){return wu(this,null,function*(){var t;const i=this.parser,r=(t=i.json.meshes)==null?void 0:t[e];if(r==null)throw new Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);const s=r.primitives,o=yield i.loadMesh(e);if(s.length===1){const c=o,h=s[0].material;h!=null&&this._setupPrimitive(c,h)}else{const c=o;for(let h=0;h{var s;this._getMToonExtension(r)&&((s=a.extensions)!=null&&s.KHR_materials_unlit)&&delete a.extensions.KHR_materials_unlit})}_getMToonExtension(e){var t,i;const s=(t=this.parser.json.materials)==null?void 0:t[e];if(s==null){console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);return}const o=(i=s.extensions)==null?void 0:i[S_.EXTENSION_NAME];if(o==null)return;const c=o.specVersion;if(!uQ.has(c)){console.warn(`MToonMaterialLoaderPlugin: Unknown ${S_.EXTENSION_NAME} specVersion "${c}"`);return}return o}_extendMaterialParams(e,t){return wu(this,null,function*(){var i;delete t.metalness,delete t.roughness;const a=new aQ(this.parser,t);a.assignPrimitive("transparentWithZWrite",e.transparentWithZWrite),a.assignColor("shadeColorFactor",e.shadeColorFactor),a.assignTexture("shadeMultiplyTexture",e.shadeMultiplyTexture,!0),a.assignPrimitive("shadingShiftFactor",e.shadingShiftFactor),a.assignTexture("shadingShiftTexture",e.shadingShiftTexture,!0),a.assignPrimitive("shadingShiftTextureScale",(i=e.shadingShiftTexture)==null?void 0:i.scale),a.assignPrimitive("shadingToonyFactor",e.shadingToonyFactor),a.assignPrimitive("giEqualizationFactor",e.giEqualizationFactor),a.assignColor("matcapFactor",e.matcapFactor),a.assignTexture("matcapTexture",e.matcapTexture,!0),a.assignColor("parametricRimColorFactor",e.parametricRimColorFactor),a.assignTexture("rimMultiplyTexture",e.rimMultiplyTexture,!0),a.assignPrimitive("rimLightingMixFactor",e.rimLightingMixFactor),a.assignPrimitive("parametricRimFresnelPowerFactor",e.parametricRimFresnelPowerFactor),a.assignPrimitive("parametricRimLiftFactor",e.parametricRimLiftFactor),a.assignPrimitive("outlineWidthMode",e.outlineWidthMode),a.assignPrimitive("outlineWidthFactor",e.outlineWidthFactor),a.assignTexture("outlineWidthMultiplyTexture",e.outlineWidthMultiplyTexture,!1),a.assignColor("outlineColorFactor",e.outlineColorFactor),a.assignPrimitive("outlineLightingMixFactor",e.outlineLightingMixFactor),a.assignTexture("uvAnimationMaskTexture",e.uvAnimationMaskTexture,!1),a.assignPrimitive("uvAnimationScrollXSpeedFactor",e.uvAnimationScrollXSpeedFactor),a.assignPrimitive("uvAnimationScrollYSpeedFactor",e.uvAnimationScrollYSpeedFactor),a.assignPrimitive("uvAnimationRotationSpeedFactor",e.uvAnimationRotationSpeedFactor),a.assignPrimitive("v0CompatShade",this.v0CompatShade),a.assignPrimitive("debugMode",this.debugMode),yield a.pending})}_setupPrimitive(e,t){const i=this._getMToonExtension(t);if(i){const a=this._parseRenderOrder(i);e.renderOrder=a+this.renderOrderOffset,this._generateOutline(e),this._addToMaterialSet(e);return}}_shouldGenerateOutline(e){return typeof e.outlineWidthMode=="string"&&e.outlineWidthMode!=="none"&&typeof e.outlineWidthFactor=="number"&&e.outlineWidthFactor>0}_generateOutline(e){const t=e.material;if(!(t instanceof qn)||!this._shouldGenerateOutline(t))return;e.material=[t];const i=t.clone();i.name+=" (Outline)",i.isOutline=!0,i.side=Ui,e.material.push(i);const a=e.geometry,r=a.index?a.index.count:a.attributes.position.count/3;a.addGroup(0,r,0),a.addGroup(0,r,1)}_addToMaterialSet(e){const t=e.material,i=new Set;Array.isArray(t)?t.forEach(a=>i.add(a)):i.add(t);for(const a of i)this._mToonMaterialSet.add(a)}_parseRenderOrder(e){var t;return(e.transparentWithZWrite?0:19)+((t=e.renderQueueOffsetNumber)!=null?t:0)}};I8.EXTENSION_NAME="VRMC_materials_mtoon";var hQ=I8,fQ=(n,e,t)=>new Promise((i,a)=>{var r=c=>{try{o(t.next(c))}catch(h){a(h)}},s=c=>{try{o(t.throw(c))}catch(h){a(h)}},o=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,s);o((t=t.apply(n,e)).next())}),U8=class DE{get name(){return DE.EXTENSION_NAME}constructor(e){this.parser=e}extendMaterialParams(e,t){return fQ(this,null,function*(){const i=this._getHDREmissiveMultiplierExtension(e);if(i==null)return;console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead.");const a=i.emissiveMultiplier;t.emissiveIntensity=a})}_getHDREmissiveMultiplierExtension(e){var t,i;const s=(t=this.parser.json.materials)==null?void 0:t[e];if(s==null){console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);return}const o=(i=s.extensions)==null?void 0:i[DE.EXTENSION_NAME];if(o!=null)return o}};U8.EXTENSION_NAME="VRMC_materials_hdr_emissiveMultiplier";var dQ=U8,pQ=Object.defineProperty,mQ=Object.defineProperties,gQ=Object.getOwnPropertyDescriptors,wD=Object.getOwnPropertySymbols,vQ=Object.prototype.hasOwnProperty,_Q=Object.prototype.propertyIsEnumerable,RD=(n,e,t)=>e in n?pQ(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ys=(n,e)=>{for(var t in e||(e={}))vQ.call(e,t)&&RD(n,t,e[t]);if(wD)for(var t of wD(e))_Q.call(e,t)&&RD(n,t,e[t]);return n},CD=(n,e)=>mQ(n,gQ(e)),xQ=(n,e,t)=>new Promise((i,a)=>{var r=c=>{try{o(t.next(c))}catch(h){a(h)}},s=c=>{try{o(t.throw(c))}catch(h){a(h)}},o=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,s);o((t=t.apply(n,e)).next())});function vf(n){return Math.pow(n,2.2)}var yQ=class{get name(){return"VRMMaterialsV0CompatPlugin"}constructor(n){var e;this.parser=n,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;const t=this.parser.json;t.extensionsUsed=(e=t.extensionsUsed)!=null?e:[],t.extensionsUsed.indexOf("KHR_texture_transform")===-1&&t.extensionsUsed.push("KHR_texture_transform")}beforeRoot(){return xQ(this,null,function*(){var n;const e=this.parser.json,t=(n=e.extensions)==null?void 0:n.VRM,i=t==null?void 0:t.materialProperties;i&&(this._populateRenderQueueMap(i),i.forEach((a,r)=>{var s,o;const c=(s=e.materials)==null?void 0:s[r];if(c==null){console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${r}] of glTF but the material doesn't exist`);return}if(a.shader==="VRM/MToon"){const h=this._parseV0MToonProperties(a,c);e.materials[r]=h}else if((o=a.shader)!=null&&o.startsWith("VRM/Unlit")){const h=this._parseV0UnlitProperties(a,c);e.materials[r]=h}else a.shader==="VRM_USE_GLTFSHADER"||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${a.shader}`)}))})}_parseV0MToonProperties(n,e){var t,i,a,r,s,o,c,h,f,d,m,g,x,T,y,v,S,E,b,D,C,I,P,O,w,B,j,ee,se,re,W,te,K,oe,ie,Ce,Xe,nt,tt,gt,ge,Ae,Ze,ue,it,Mt,ot,Ke,Te,G,be,De,Fe,Be,$e;const Je=(i=(t=n.keywordMap)==null?void 0:t._ALPHABLEND_ON)!=null?i:!1,k=((a=n.floatProperties)==null?void 0:a._ZWrite)===1&&Je,U=this._v0ParseRenderQueue(n),ce=(s=(r=n.keywordMap)==null?void 0:r._ALPHATEST_ON)!=null?s:!1,Ee=Je?"BLEND":ce?"MASK":"OPAQUE",Le=ce?(c=(o=n.floatProperties)==null?void 0:o._Cutoff)!=null?c:.5:void 0,vt=((f=(h=n.floatProperties)==null?void 0:h._CullMode)!=null?f:2)===0,qe=this._portTextureTransform(n),_t=((m=(d=n.vectorProperties)==null?void 0:d._Color)!=null?m:[1,1,1,1]).map((N,V)=>V===3?N:vf(N)),pt=(g=n.textureProperties)==null?void 0:g._MainTex,Ie=pt!=null?{index:pt,extensions:Ys({},qe)}:void 0,He=(T=(x=n.floatProperties)==null?void 0:x._BumpScale)!=null?T:1,ht=(y=n.textureProperties)==null?void 0:y._BumpMap,Q=ht!=null?{index:ht,scale:He,extensions:Ys({},qe)}:void 0,pe=((S=(v=n.vectorProperties)==null?void 0:v._EmissionColor)!=null?S:[0,0,0,1]).map(vf),Oe=(E=n.textureProperties)==null?void 0:E._EmissionMap,q=Oe!=null?{index:Oe,extensions:Ys({},qe)}:void 0,Ve=((D=(b=n.vectorProperties)==null?void 0:b._ShadeColor)!=null?D:[.97,.81,.86,1]).map(vf),me=(C=n.textureProperties)==null?void 0:C._ShadeTexture,We=me!=null?{index:me,extensions:Ys({},qe)}:void 0;let Ge=(P=(I=n.floatProperties)==null?void 0:I._ShadeShift)!=null?P:0,we=(w=(O=n.floatProperties)==null?void 0:O._ShadeToony)!=null?w:.9;we=$t.lerp(we,1,.5+.5*Ge),Ge=-Ge-(1-we);const rt=(j=(B=n.floatProperties)==null?void 0:B._IndirectLightIntensity)!=null?j:.1,yt=rt?1-rt:void 0,Gt=(ee=n.textureProperties)==null?void 0:ee._SphereAdd,Vt=Gt!=null?[1,1,1]:void 0,li=Gt!=null?{index:Gt}:void 0,ci=(re=(se=n.floatProperties)==null?void 0:se._RimLightingMix)!=null?re:0,uo=(W=n.textureProperties)==null?void 0:W._RimTexture,Is=uo!=null?{index:uo,extensions:Ys({},qe)}:void 0,Us=((K=(te=n.vectorProperties)==null?void 0:te._RimColor)!=null?K:[0,0,0,1]).map(vf),bi=(ie=(oe=n.floatProperties)==null?void 0:oe._RimFresnelPower)!=null?ie:1,Ps=(Xe=(Ce=n.floatProperties)==null?void 0:Ce._RimLift)!=null?Xe:0,fa=["none","worldCoordinates","screenCoordinates"][(tt=(nt=n.floatProperties)==null?void 0:nt._OutlineWidthMode)!=null?tt:0];let Xi=(ge=(gt=n.floatProperties)==null?void 0:gt._OutlineWidth)!=null?ge:0;Xi=.01*Xi;const Fa=(Ae=n.textureProperties)==null?void 0:Ae._OutlineWidthTexture,Dn=Fa!=null?{index:Fa,extensions:Ys({},qe)}:void 0,Lr=((ue=(Ze=n.vectorProperties)==null?void 0:Ze._OutlineColor)!=null?ue:[0,0,0]).map(vf),Bs=((Mt=(it=n.floatProperties)==null?void 0:it._OutlineColorMode)!=null?Mt:0)===1?(Ke=(ot=n.floatProperties)==null?void 0:ot._OutlineLightingMix)!=null?Ke:1:0,ho=(Te=n.textureProperties)==null?void 0:Te._UvAnimMaskTexture,sr=ho!=null?{index:ho,extensions:Ys({},qe)}:void 0,da=(be=(G=n.floatProperties)==null?void 0:G._UvAnimScrollX)!=null?be:0;let R=(Fe=(De=n.floatProperties)==null?void 0:De._UvAnimScrollY)!=null?Fe:0;R!=null&&(R=-R);const z=($e=(Be=n.floatProperties)==null?void 0:Be._UvAnimRotation)!=null?$e:0,Y={specVersion:"1.0",transparentWithZWrite:k,renderQueueOffsetNumber:U,shadeColorFactor:Ve,shadeMultiplyTexture:We,shadingShiftFactor:Ge,shadingToonyFactor:we,giEqualizationFactor:yt,matcapFactor:Vt,matcapTexture:li,rimLightingMixFactor:ci,rimMultiplyTexture:Is,parametricRimColorFactor:Us,parametricRimFresnelPowerFactor:bi,parametricRimLiftFactor:Ps,outlineWidthMode:fa,outlineWidthFactor:Xi,outlineWidthMultiplyTexture:Dn,outlineColorFactor:Lr,outlineLightingMixFactor:Bs,uvAnimationMaskTexture:sr,uvAnimationScrollXSpeedFactor:da,uvAnimationScrollYSpeedFactor:R,uvAnimationRotationSpeedFactor:z};return CD(Ys({},e),{pbrMetallicRoughness:{baseColorFactor:_t,baseColorTexture:Ie},normalTexture:Q,emissiveTexture:q,emissiveFactor:pe,alphaMode:Ee,alphaCutoff:Le,doubleSided:vt,extensions:{VRMC_materials_mtoon:Y}})}_parseV0UnlitProperties(n,e){var t,i,a,r,s;const o=n.shader==="VRM/UnlitTransparentZWrite",c=n.shader==="VRM/UnlitTransparent"||o,h=this._v0ParseRenderQueue(n),f=n.shader==="VRM/UnlitCutout",d=c?"BLEND":f?"MASK":"OPAQUE",m=f?(i=(t=n.floatProperties)==null?void 0:t._Cutoff)!=null?i:.5:void 0,g=this._portTextureTransform(n),x=((r=(a=n.vectorProperties)==null?void 0:a._Color)!=null?r:[1,1,1,1]).map(vf),T=(s=n.textureProperties)==null?void 0:s._MainTex,y=T!=null?{index:T,extensions:Ys({},g)}:void 0,v={specVersion:"1.0",transparentWithZWrite:o,renderQueueOffsetNumber:h,shadeColorFactor:x,shadeMultiplyTexture:y};return CD(Ys({},e),{pbrMetallicRoughness:{baseColorFactor:x,baseColorTexture:y},alphaMode:d,alphaCutoff:m,extensions:{VRMC_materials_mtoon:v}})}_portTextureTransform(n){var e,t,i,a,r;const s=(e=n.vectorProperties)==null?void 0:e._MainTex;if(s==null)return{};const o=[(t=s==null?void 0:s[0])!=null?t:0,(i=s==null?void 0:s[1])!=null?i:0],c=[(a=s==null?void 0:s[2])!=null?a:1,(r=s==null?void 0:s[3])!=null?r:1];return o[1]=1-c[1]-o[1],{KHR_texture_transform:{offset:o,scale:c}}}_v0ParseRenderQueue(n){var e,t;const i=n.shader==="VRM/UnlitTransparentZWrite",a=((e=n.keywordMap)==null?void 0:e._ALPHABLEND_ON)!=null||n.shader==="VRM/UnlitTransparent"||i,r=((t=n.floatProperties)==null?void 0:t._ZWrite)===1||i;let s=0;if(a){const o=n.renderQueue;o!=null&&(r?s=this._renderQueueMapTransparentZWrite.get(o):s=this._renderQueueMapTransparent.get(o))}return s}_populateRenderQueueMap(n){const e=new Set,t=new Set;n.forEach(i=>{var a,r;const s=i.shader==="VRM/UnlitTransparentZWrite",o=((a=i.keywordMap)==null?void 0:a._ALPHABLEND_ON)!=null||i.shader==="VRM/UnlitTransparent"||s,c=((r=i.floatProperties)==null?void 0:r._ZWrite)===1||s;if(o){const h=i.renderQueue;h!=null&&(c?t.add(h):e.add(h))}}),e.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${e.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),t.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${t.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(e).sort().forEach((i,a)=>{const r=Math.min(Math.max(a-e.size+1,-9),0);this._renderQueueMapTransparent.set(i,r)}),Array.from(t).sort().forEach((i,a)=>{const r=Math.min(Math.max(a,0),9);this._renderQueueMapTransparentZWrite.set(i,r)})}},ND=(n,e,t)=>new Promise((i,a)=>{var r=c=>{try{o(t.next(c))}catch(h){a(h)}},s=c=>{try{o(t.throw(c))}catch(h){a(h)}},o=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,s);o((t=t.apply(n,e)).next())}),Ul=new L,O2=class extends Ua{constructor(n){super(),this._attrPosition=new Ot(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(IU);const e=new Ct;e.setAttribute("position",this._attrPosition);const t=new Bi({color:16711935,depthTest:!1,depthWrite:!1});this._line=new so(e,t),this.add(this._line),this.constraint=n}updateMatrixWorld(n){Ul.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,Ul.x,Ul.y,Ul.z),this.constraint.source&&Ul.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,Ul.x,Ul.y,Ul.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(n)}};function DD(n,e){return e.set(n.elements[12],n.elements[13],n.elements[14])}var SQ=new L,TQ=new L;function EQ(n,e){return n.decompose(SQ,e,TQ),e}function qx(n){return n.invert?n.invert():n.inverse(),n}var aA=class{constructor(n,e){this.destination=n,this.source=e,this.weight=1}},MQ=new L,bQ=new L,AQ=new L,wQ=new St,RQ=new St,CQ=new St,NQ=class extends aA{get aimAxis(){return this._aimAxis}set aimAxis(n){this._aimAxis=n,this._v3AimAxis.set(n==="PositiveX"?1:n==="NegativeX"?-1:0,n==="PositiveY"?1:n==="NegativeY"?-1:0,n==="PositiveZ"?1:n==="NegativeZ"?-1:0)}get dependencies(){const n=new Set([this.source]);return this.destination.parent&&n.add(this.destination.parent),n}constructor(n,e){super(n,e),this._aimAxis="PositiveX",this._v3AimAxis=new L(1,0,0),this._dstRestQuat=new St}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);const n=wQ.identity(),e=RQ.identity();this.destination.parent&&(EQ(this.destination.parent.matrixWorld,n),qx(e.copy(n)));const t=MQ.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(n),i=DD(this.source.matrixWorld,bQ).sub(DD(this.destination.matrixWorld,AQ)).normalize(),a=CQ.setFromUnitVectors(t,i).premultiply(e).multiply(n).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(a,this.weight)}};function DQ(n,e){const t=[n];let i=n.parent;for(;i!==null;)t.unshift(i),i=i.parent;t.forEach(a=>{e(a)})}var OQ=class{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(n){this._constraints.add(n);let e=this._objectConstraintsMap.get(n.destination);e==null&&(e=new Set,this._objectConstraintsMap.set(n.destination,e)),e.add(n)}deleteConstraint(n){this._constraints.delete(n),this._objectConstraintsMap.get(n.destination).delete(n)}setInitState(){const n=new Set,e=new Set;for(const t of this._constraints)this._processConstraint(t,n,e,i=>i.setInitState())}update(){const n=new Set,e=new Set;for(const t of this._constraints)this._processConstraint(t,n,e,i=>i.update())}_processConstraint(n,e,t,i){if(t.has(n))return;if(e.has(n))throw new Error("VRMNodeConstraintManager: Circular dependency detected while updating constraints");e.add(n);const a=n.dependencies;for(const r of a)DQ(r,s=>{const o=this._objectConstraintsMap.get(s);if(o)for(const c of o)this._processConstraint(c,e,t,i)});i(n),t.add(n)}},LQ=new St,IQ=new St,UQ=class extends aA{get dependencies(){return new Set([this.source])}constructor(n,e){super(n,e),this._dstRestQuat=new St,this._invSrcRestQuat=new St}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),qx(this._invSrcRestQuat.copy(this.source.quaternion))}update(){const n=LQ.copy(this._invSrcRestQuat).multiply(this.source.quaternion),e=IQ.copy(this._dstRestQuat).multiply(n);this.destination.quaternion.copy(this._dstRestQuat).slerp(e,this.weight)}},PQ=new L,zQ=new St,BQ=new St,HQ=class extends aA{get rollAxis(){return this._rollAxis}set rollAxis(n){this._rollAxis=n,this._v3RollAxis.set(n==="X"?1:0,n==="Y"?1:0,n==="Z"?1:0)}get dependencies(){return new Set([this.source])}constructor(n,e){super(n,e),this._rollAxis="X",this._v3RollAxis=new L(1,0,0),this._dstRestQuat=new St,this._invDstRestQuat=new St,this._invSrcRestQuatMulDstRestQuat=new St}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),qx(this._invDstRestQuat.copy(this._dstRestQuat)),qx(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){const n=zQ.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),e=PQ.copy(this._v3RollAxis).applyQuaternion(n),i=BQ.setFromUnitVectors(e,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(n);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}},FQ=new Set(["1.0","1.0-beta"]),P8=class fm{get name(){return fm.EXTENSION_NAME}constructor(e,t){this.parser=e,this.helperRoot=t==null?void 0:t.helperRoot}afterRoot(e){return ND(this,null,function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)})}_import(e){return ND(this,null,function*(){var t;const i=this.parser.json;if(!(((t=i.extensionsUsed)==null?void 0:t.indexOf(fm.EXTENSION_NAME))!==-1))return null;const r=new OQ,s=yield this.parser.getDependencies("node");return s.forEach((o,c)=>{var h;const f=i.nodes[c],d=(h=f==null?void 0:f.extensions)==null?void 0:h[fm.EXTENSION_NAME];if(d==null)return;const m=d.specVersion;if(!FQ.has(m)){console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${fm.EXTENSION_NAME} specVersion "${m}"`);return}const g=d.constraint;if(g.roll!=null){const x=this._importRollConstraint(o,s,g.roll);r.addConstraint(x)}else if(g.aim!=null){const x=this._importAimConstraint(o,s,g.aim);r.addConstraint(x)}else if(g.rotation!=null){const x=this._importRotationConstraint(o,s,g.rotation);r.addConstraint(x)}}),e.scene.updateMatrixWorld(),r.setInitState(),r})}_importRollConstraint(e,t,i){const{source:a,rollAxis:r,weight:s}=i,o=t[a],c=new HQ(e,o);if(r!=null&&(c.rollAxis=r),s!=null&&(c.weight=s),this.helperRoot){const h=new O2(c);this.helperRoot.add(h)}return c}_importAimConstraint(e,t,i){const{source:a,aimAxis:r,weight:s}=i,o=t[a],c=new NQ(e,o);if(r!=null&&(c.aimAxis=r),s!=null&&(c.weight=s),this.helperRoot){const h=new O2(c);this.helperRoot.add(h)}return c}_importRotationConstraint(e,t,i){const{source:a,weight:r}=i,s=t[a],o=new UQ(e,s);if(r!=null&&(o.weight=r),this.helperRoot){const c=new O2(o);this.helperRoot.add(c)}return o}};P8.EXTENSION_NAME="VRMC_node_constraint";var GQ=P8,Gv=(n,e,t)=>new Promise((i,a)=>{var r=c=>{try{o(t.next(c))}catch(h){a(h)}},s=c=>{try{o(t.throw(c))}catch(h){a(h)}},o=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,s);o((t=t.apply(n,e)).next())}),rA=class{},L2=new L,hu=new L,z8=class extends rA{get type(){return"capsule"}constructor(n){var e,t,i,a;super(),this.offset=(e=n==null?void 0:n.offset)!=null?e:new L(0,0,0),this.tail=(t=n==null?void 0:n.tail)!=null?t:new L(0,0,0),this.radius=(i=n==null?void 0:n.radius)!=null?i:0,this.inside=(a=n==null?void 0:n.inside)!=null?a:!1}calculateCollision(n,e,t,i){L2.setFromMatrixPosition(n),hu.subVectors(this.tail,this.offset).applyMatrix4(n),hu.sub(L2);const a=hu.lengthSq();i.copy(e).sub(L2);const r=hu.dot(i);r<=0||(a<=r||hu.multiplyScalar(r/a),i.sub(hu));const s=i.length(),o=this.inside?this.radius-t-s:s-t-this.radius;return o<0&&(i.multiplyScalar(1/s),this.inside&&i.negate()),o}},I2=new L,OD=new Et,B8=class extends rA{get type(){return"plane"}constructor(n){var e,t;super(),this.offset=(e=n==null?void 0:n.offset)!=null?e:new L(0,0,0),this.normal=(t=n==null?void 0:n.normal)!=null?t:new L(0,0,1)}calculateCollision(n,e,t,i){i.setFromMatrixPosition(n),i.negate().add(e),OD.getNormalMatrix(n),I2.copy(this.normal).applyNormalMatrix(OD).normalize();const a=i.dot(I2)-t;return i.copy(I2),a}},VQ=new L,H8=class extends rA{get type(){return"sphere"}constructor(n){var e,t,i;super(),this.offset=(e=n==null?void 0:n.offset)!=null?e:new L(0,0,0),this.radius=(t=n==null?void 0:n.radius)!=null?t:0,this.inside=(i=n==null?void 0:n.inside)!=null?i:!1}calculateCollision(n,e,t,i){i.subVectors(e,VQ.setFromMatrixPosition(n));const a=i.length(),r=this.inside?this.radius-t-a:a-t-this.radius;return r<0&&(i.multiplyScalar(1/a),this.inside&&i.negate()),r}},qs=new L,kQ=class extends Ct{constructor(n){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new L,this._currentTail=new L,this._shape=n,this._attrPos=new Ot(new Float32Array(396),3),this.setAttribute("position",this._attrPos),this._attrIndex=new Ot(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;const e=this._shape.radius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,n=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),n=!0);const t=qs.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(t)>1e-10&&(this._currentTail.copy(t),n=!0),n&&this._buildPosition()}_buildPosition(){qs.copy(this._currentTail).sub(this._currentOffset);const n=qs.length()/this._currentRadius;for(let i=0;i<=16;i++){const a=i/16*Math.PI;this._attrPos.setXYZ(i,-Math.sin(a),-Math.cos(a),0),this._attrPos.setXYZ(17+i,n+Math.sin(a),Math.cos(a),0),this._attrPos.setXYZ(34+i,-Math.sin(a),0,-Math.cos(a)),this._attrPos.setXYZ(51+i,n+Math.sin(a),0,Math.cos(a))}for(let i=0;i<32;i++){const a=i/16*Math.PI;this._attrPos.setXYZ(68+i,0,Math.sin(a),Math.cos(a)),this._attrPos.setXYZ(100+i,n,Math.sin(a),Math.cos(a))}const e=Math.atan2(qs.y,Math.sqrt(qs.x*qs.x+qs.z*qs.z)),t=-Math.atan2(qs.z,qs.x);this.rotateZ(e),this.rotateY(t),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<34;n++){const e=(n+1)%34;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(68+n*2,34+n,34+e)}for(let n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(136+n*2,68+n,68+e),this._attrIndex.setXY(200+n*2,100+n,100+e)}this._attrIndex.needsUpdate=!0}},WQ=class extends Ct{constructor(n){super(),this.worldScale=1,this._currentOffset=new L,this._currentNormal=new L,this._shape=n,this._attrPos=new Ot(new Float32Array(6*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new Ot(new Uint16Array(10),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),n=!0),this._currentNormal.equals(this._shape.normal)||(this._currentNormal.copy(this._shape.normal),n=!0),n&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,-.5,-.5,0),this._attrPos.setXYZ(1,.5,-.5,0),this._attrPos.setXYZ(2,.5,.5,0),this._attrPos.setXYZ(3,-.5,.5,0),this._attrPos.setXYZ(4,0,0,0),this._attrPos.setXYZ(5,0,0,.25),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this.lookAt(this._currentNormal),this._attrPos.needsUpdate=!0}_buildIndex(){this._attrIndex.setXY(0,0,1),this._attrIndex.setXY(2,1,2),this._attrIndex.setXY(4,2,3),this._attrIndex.setXY(6,3,0),this._attrIndex.setXY(8,4,5),this._attrIndex.needsUpdate=!0}},XQ=class extends Ct{constructor(n){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new L,this._shape=n,this._attrPos=new Ot(new Float32Array(32*3*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new Ot(new Uint16Array(64*3),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;const e=this._shape.radius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,n=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),n=!0),n&&this._buildPosition()}_buildPosition(){for(let n=0;n<32;n++){const e=n/16*Math.PI;this._attrPos.setXYZ(n,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+n,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+n,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(64+n*2,32+n,32+e),this._attrIndex.setXY(128+n*2,64+n,64+e)}this._attrIndex.needsUpdate=!0}},YQ=new L,U2=class extends Ua{constructor(n){if(super(),this.matrixAutoUpdate=!1,this.collider=n,this.collider.shape instanceof H8)this._geometry=new XQ(this.collider.shape);else if(this.collider.shape instanceof z8)this._geometry=new kQ(this.collider.shape);else if(this.collider.shape instanceof B8)this._geometry=new WQ(this.collider.shape);else throw new Error("VRMSpringBoneColliderHelper: Unknown collider shape type detected");const e=new Bi({color:16711935,depthTest:!1,depthWrite:!1});this._line=new ir(this._geometry,e),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(n){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);const e=this.matrix.elements;this._geometry.worldScale=YQ.set(e[0],e[1],e[2]).length(),this._geometry.update(),super.updateMatrixWorld(n)}},qQ=class extends Ct{constructor(n){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new L,this._springBone=n,this._attrPos=new Ot(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new Ot(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;const e=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,n=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),n=!0),n&&this._buildPosition()}_buildPosition(){for(let n=0;n<32;n++){const e=n/16*Math.PI;this._attrPos.setXYZ(n,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+n,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+n,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(64+n*2,32+n,32+e),this._attrIndex.setXY(128+n*2,64+n,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},jQ=new L,ZQ=class extends Ua{constructor(n){super(),this.matrixAutoUpdate=!1,this.springBone=n,this._geometry=new qQ(this.springBone);const e=new Bi({color:16776960,depthTest:!1,depthWrite:!1});this._line=new ir(this._geometry,e),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(n){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);const e=this.matrix.elements;this._geometry.worldScale=jQ.set(e[0],e[1],e[2]).length(),this._geometry.update(),super.updateMatrixWorld(n)}},P2=class extends Wt{constructor(n){super(),this.colliderMatrix=new ke,this.shape=n}updateWorldMatrix(n,e){super.updateWorldMatrix(n,e),KQ(this.colliderMatrix,this.matrixWorld,this.shape.offset)}};function KQ(n,e,t){const i=e.elements;n.copy(e),t&&(n.elements[12]=i[0]*t.x+i[4]*t.y+i[8]*t.z+i[12],n.elements[13]=i[1]*t.x+i[5]*t.y+i[9]*t.z+i[13],n.elements[14]=i[2]*t.x+i[6]*t.y+i[10]*t.z+i[14])}var QQ=new ke;function JQ(n){return n.invert?n.invert():n.getInverse(QQ.copy(n)),n}var $Q=class{constructor(n){this._inverseCache=new ke,this._shouldUpdateInverse=!0,this.matrix=n;const e={set:(t,i,a)=>(this._shouldUpdateInverse=!0,t[i]=a,!0)};this._originalElements=n.elements,n.elements=new Proxy(n.elements,e)}get inverse(){return this._shouldUpdateInverse&&(JQ(this._inverseCache.copy(this.matrix)),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}},z2=new ke,_f=new L,Zp=new L,Kp=new L,Qp=new L,eJ=new ke,tJ=class{constructor(n,e,t={},i=[]){this._currentTail=new L,this._prevTail=new L,this._boneAxis=new L,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new ke,this._initialLocalRotation=new St,this._initialLocalChildPosition=new L;var a,r,s,o,c,h;this.bone=n,this.bone.matrixAutoUpdate=!1,this.child=e,this.settings={hitRadius:(a=t.hitRadius)!=null?a:0,stiffness:(r=t.stiffness)!=null?r:1,gravityPower:(s=t.gravityPower)!=null?s:0,gravityDir:(c=(o=t.gravityDir)==null?void 0:o.clone())!=null?c:new L(0,-1,0),dragForce:(h=t.dragForce)!=null?h:.4},this.colliderGroups=i}get dependencies(){const n=new Set,e=this.bone.parent;e&&n.add(e);for(let t=0;t{e(a)})}function OE(n,e){n.children.forEach(t=>{e(t)||OE(t,e)})}function iJ(n){var e;const t=new Map;for(const i of n){let a=i;do{const r=((e=t.get(a))!=null?e:0)+1;if(r===n.size)return a;t.set(a,r),a=a.parent}while(a!==null)}return null}var LD=class{constructor(){this._joints=new Set,this._sortedJoints=[],this._hasWarnedCircularDependency=!1,this._ancestors=[],this._objectSpringBonesMap=new Map,this._isSortedJointsDirty=!1,this._relevantChildrenUpdated=this._relevantChildrenUpdated.bind(this)}get joints(){return this._joints}get springBones(){return console.warn("VRMSpringBoneManager: springBones is deprecated. use joints instead."),this._joints}get colliderGroups(){const n=new Set;return this._joints.forEach(e=>{e.colliderGroups.forEach(t=>{n.add(t)})}),Array.from(n)}get colliders(){const n=new Set;return this.colliderGroups.forEach(e=>{e.colliders.forEach(t=>{n.add(t)})}),Array.from(n)}addJoint(n){this._joints.add(n);let e=this._objectSpringBonesMap.get(n.bone);e==null&&(e=new Set,this._objectSpringBonesMap.set(n.bone,e)),e.add(n),this._isSortedJointsDirty=!0}addSpringBone(n){console.warn("VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead."),this.addJoint(n)}deleteJoint(n){this._joints.delete(n),this._objectSpringBonesMap.get(n.bone).delete(n),this._isSortedJointsDirty=!0}deleteSpringBone(n){console.warn("VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead."),this.deleteJoint(n)}setInitState(){this._sortJoints();for(let n=0;n{var s,o;return((o=(s=this._objectSpringBonesMap.get(r))==null?void 0:s.size)!=null?o:0)>0?!0:(this._ancestors.push(r),!1)})),this._isSortedJointsDirty=!1}_insertJointSort(n,e,t,i,a){if(t.has(n))return;if(e.has(n)){this._hasWarnedCircularDependency||(console.warn("VRMSpringBoneManager: Circular dependency detected"),this._hasWarnedCircularDependency=!0);return}e.add(n);const r=n.dependencies;for(const s of r){let o=!1,c=null;nJ(s,h=>{const f=this._objectSpringBonesMap.get(h);if(f)for(const d of f)o=!0,this._insertJointSort(d,e,t,i,a);else o||(c=h)}),c&&a.add(c)}i.push(n),t.add(n)}_relevantChildrenUpdated(n){var e,t;return((t=(e=this._objectSpringBonesMap.get(n))==null?void 0:e.size)!=null?t:0)>0?!0:(n.updateWorldMatrix(!1,!1),!1)}},ID="VRMC_springBone_extended_collider",aJ=new Set(["1.0","1.0-beta"]),rJ=new Set(["1.0"]),F8=class Nf{get name(){return Nf.EXTENSION_NAME}constructor(e,t){var i;this.parser=e,this.jointHelperRoot=t==null?void 0:t.jointHelperRoot,this.colliderHelperRoot=t==null?void 0:t.colliderHelperRoot,this.useExtendedColliders=(i=t==null?void 0:t.useExtendedColliders)!=null?i:!0}afterRoot(e){return Gv(this,null,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return Gv(this,null,function*(){const t=yield this._v1Import(e);if(t!=null)return t;const i=yield this._v0Import(e);return i??null})}_v1Import(e){return Gv(this,null,function*(){var t,i,a,r,s;const o=e.parser.json;if(!(((t=o.extensionsUsed)==null?void 0:t.indexOf(Nf.EXTENSION_NAME))!==-1))return null;const h=new LD,f=yield e.parser.getDependencies("node"),d=(i=o.extensions)==null?void 0:i[Nf.EXTENSION_NAME];if(!d)return null;const m=d.specVersion;if(!aJ.has(m))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${Nf.EXTENSION_NAME} specVersion "${m}"`),null;const g=(a=d.colliders)==null?void 0:a.map((T,y)=>{var v,S,E,b,D,C,I,P,O,w,B,j,ee,se,re;const W=f[T.node];if(W==null)return console.warn(`VRMSpringBoneLoaderPlugin: The collider #${y} attempted to use the node #${T.node} but not found`),null;const te=T.shape,K=(v=T.extensions)==null?void 0:v[ID];if(this.useExtendedColliders&&K!=null){const oe=K.specVersion;if(!rJ.has(oe))console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${ID} specVersion "${oe}". Fallbacking to the ${Nf.EXTENSION_NAME} definition`);else{const ie=K.shape;if(ie.sphere)return this._importSphereCollider(W,{offset:new L().fromArray((S=ie.sphere.offset)!=null?S:[0,0,0]),radius:(E=ie.sphere.radius)!=null?E:0,inside:(b=ie.sphere.inside)!=null?b:!1});if(ie.capsule)return this._importCapsuleCollider(W,{offset:new L().fromArray((D=ie.capsule.offset)!=null?D:[0,0,0]),radius:(C=ie.capsule.radius)!=null?C:0,tail:new L().fromArray((I=ie.capsule.tail)!=null?I:[0,0,0]),inside:(P=ie.capsule.inside)!=null?P:!1});if(ie.plane)return this._importPlaneCollider(W,{offset:new L().fromArray((O=ie.plane.offset)!=null?O:[0,0,0]),normal:new L().fromArray((w=ie.plane.normal)!=null?w:[0,0,1])})}}if(te.sphere)return this._importSphereCollider(W,{offset:new L().fromArray((B=te.sphere.offset)!=null?B:[0,0,0]),radius:(j=te.sphere.radius)!=null?j:0,inside:!1});if(te.capsule)return this._importCapsuleCollider(W,{offset:new L().fromArray((ee=te.capsule.offset)!=null?ee:[0,0,0]),radius:(se=te.capsule.radius)!=null?se:0,tail:new L().fromArray((re=te.capsule.tail)!=null?re:[0,0,0]),inside:!1});throw new Error(`VRMSpringBoneLoaderPlugin: The collider #${y} has no valid shape`)}),x=(r=d.colliderGroups)==null?void 0:r.map((T,y)=>{var v;return{colliders:((v=T.colliders)!=null?v:[]).flatMap(E=>{const b=g==null?void 0:g[E];return b??(console.warn(`VRMSpringBoneLoaderPlugin: The colliderGroup #${y} attempted to use a collider #${E} but not found`),[])}),name:T.name}});return(s=d.springs)==null||s.forEach((T,y)=>{var v;const S=T.joints,E=(v=T.colliderGroups)==null?void 0:v.map(C=>{const I=x==null?void 0:x[C];if(I==null)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${y} attempted to use a colliderGroup ${C} but not found`);return I}),b=T.center!=null?f[T.center]:void 0;let D;S.forEach(C=>{if(D){const I=D.node,P=f[I],O=C.node,w=f[O],B={hitRadius:D.hitRadius,dragForce:D.dragForce,gravityPower:D.gravityPower,stiffness:D.stiffness,gravityDir:D.gravityDir!=null?new L().fromArray(D.gravityDir):void 0},j=this._importJoint(P,w,B,E);b&&(j.center=b),h.addJoint(j)}D=C})}),h.setInitState(),h})}_v0Import(e){return Gv(this,null,function*(){var t,i,a;const r=e.parser.json;if(!(((t=r.extensionsUsed)==null?void 0:t.indexOf("VRM"))!==-1))return null;const o=(i=r.extensions)==null?void 0:i.VRM,c=o==null?void 0:o.secondaryAnimation;if(!c)return null;const h=c==null?void 0:c.boneGroups;if(!h)return null;const f=new LD,d=yield e.parser.getDependencies("node"),m=(a=c.colliderGroups)==null?void 0:a.map(g=>{var x;const T=d[g.node];return{colliders:((x=g.colliders)!=null?x:[]).map((v,S)=>{var E,b,D;const C=new L(0,0,0);return v.offset&&C.set((E=v.offset.x)!=null?E:0,(b=v.offset.y)!=null?b:0,v.offset.z?-v.offset.z:0),this._importSphereCollider(T,{offset:C,radius:(D=v.radius)!=null?D:0,inside:!1})})}});return h==null||h.forEach((g,x)=>{const T=g.bones;T&&T.forEach(y=>{var v,S,E,b;const D=d[y],C=new L;g.gravityDir?C.set((v=g.gravityDir.x)!=null?v:0,(S=g.gravityDir.y)!=null?S:0,(E=g.gravityDir.z)!=null?E:0):C.set(0,-1,0);const I=g.center!=null?d[g.center]:void 0,P={hitRadius:g.hitRadius,dragForce:g.dragForce,gravityPower:g.gravityPower,stiffness:g.stiffiness,gravityDir:C},O=(b=g.colliderGroups)==null?void 0:b.map(w=>{const B=m==null?void 0:m[w];if(B==null)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${x} attempted to use a colliderGroup ${w} but not found`);return B});D.traverse(w=>{var B;const j=(B=w.children[0])!=null?B:null,ee=this._importJoint(w,j,P,O);I&&(ee.center=I),f.addJoint(ee)})})}),e.scene.updateMatrixWorld(),f.setInitState(),f})}_importJoint(e,t,i,a){const r=new tJ(e,t,i,a);if(this.jointHelperRoot){const s=new ZQ(r);this.jointHelperRoot.add(s),s.renderOrder=this.jointHelperRoot.renderOrder}return r}_importSphereCollider(e,t){const i=new H8(t),a=new P2(i);if(e.add(a),this.colliderHelperRoot){const r=new U2(a);this.colliderHelperRoot.add(r),r.renderOrder=this.colliderHelperRoot.renderOrder}return a}_importCapsuleCollider(e,t){const i=new z8(t),a=new P2(i);if(e.add(a),this.colliderHelperRoot){const r=new U2(a);this.colliderHelperRoot.add(r),r.renderOrder=this.colliderHelperRoot.renderOrder}return a}_importPlaneCollider(e,t){const i=new B8(t),a=new P2(i);if(e.add(a),this.colliderHelperRoot){const r=new U2(a);this.colliderHelperRoot.add(r),r.renderOrder=this.colliderHelperRoot.renderOrder}return a}};F8.EXTENSION_NAME="VRMC_springBone";var sJ=F8,oJ=class{get name(){return"VRMLoaderPlugin"}constructor(n,e){var t,i,a,r,s,o,c,h,f,d;this.parser=n;const m=e==null?void 0:e.helperRoot,g=e==null?void 0:e.autoUpdateHumanBones;this.expressionPlugin=(t=e==null?void 0:e.expressionPlugin)!=null?t:new EK(n),this.firstPersonPlugin=(i=e==null?void 0:e.firstPersonPlugin)!=null?i:new bK(n),this.humanoidPlugin=(a=e==null?void 0:e.humanoidPlugin)!=null?a:new OK(n,{helperRoot:m,autoUpdateHumanBones:g}),this.lookAtPlugin=(r=e==null?void 0:e.lookAtPlugin)!=null?r:new qK(n,{helperRoot:m}),this.metaPlugin=(s=e==null?void 0:e.metaPlugin)!=null?s:new KK(n),this.mtoonMaterialPlugin=(o=e==null?void 0:e.mtoonMaterialPlugin)!=null?o:new hQ(n),this.materialsHDREmissiveMultiplierPlugin=(c=e==null?void 0:e.materialsHDREmissiveMultiplierPlugin)!=null?c:new dQ(n),this.materialsV0CompatPlugin=(h=e==null?void 0:e.materialsV0CompatPlugin)!=null?h:new yQ(n),this.springBonePlugin=(f=e==null?void 0:e.springBonePlugin)!=null?f:new sJ(n,{colliderHelperRoot:m,jointHelperRoot:m}),this.nodeConstraintPlugin=(d=e==null?void 0:e.nodeConstraintPlugin)!=null?d:new GQ(n,{helperRoot:m})}beforeRoot(){return Bv(this,null,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(n){return Bv(this,null,function*(){return yield this.mtoonMaterialPlugin.loadMesh(n)})}getMaterialType(n){const e=this.mtoonMaterialPlugin.getMaterialType(n);return e??null}extendMaterialParams(n,e){return Bv(this,null,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(n,e),yield this.mtoonMaterialPlugin.extendMaterialParams(n,e)})}afterRoot(n){return Bv(this,null,function*(){yield this.metaPlugin.afterRoot(n),yield this.humanoidPlugin.afterRoot(n),yield this.expressionPlugin.afterRoot(n),yield this.lookAtPlugin.afterRoot(n),yield this.firstPersonPlugin.afterRoot(n),yield this.springBonePlugin.afterRoot(n),yield this.nodeConstraintPlugin.afterRoot(n),yield this.mtoonMaterialPlugin.afterRoot(n);const e=n.userData.vrmMeta,t=n.userData.vrmHumanoid;if(e&&t){const i=new JK({scene:n.scene,expressionManager:n.userData.vrmExpressionManager,firstPerson:n.userData.vrmFirstPerson,humanoid:t,lookAt:n.userData.vrmLookAt,meta:e,materials:n.userData.vrmMToonMaterials,springBoneManager:n.userData.vrmSpringBoneManager,nodeConstraintManager:n.userData.vrmNodeConstraintManager});n.userData.vrm=i}})}};function lJ(n){const e=new Set;return n.traverse(t=>{if(!t.isMesh)return;const i=t;e.add(i)}),e}function UD(n,e,t){if(e.size===1){const s=e.values().next().value;if(s.weight===1)return n[s.index]}const i=new Float32Array(n[0].count*3);let a=0;if(t)a=1;else for(const s of e)a+=s.weight;for(const s of e){const o=n[s.index],c=s.weight/a;for(let h=0;hf.getOrCreate(O)).join(","),I=`${b};${v};${C}`;let P=o.get(I);P==null&&(P=E.clone(),mJ(P,D,x),o.set(I,P)),S.geometry.setAttribute("skinIndex",P)}for(const S of g)S.bind(y,new ke)}}function hJ(n){const e=new Set;return n.traverse(t=>{if(!t.isSkinnedMesh)return;const i=t;e.add(i)}),e}function fJ(n,e){const t=new Set;for(let i=0;it)return!1;return!0}var B2=class{constructor(){this._objectIndexMap=new Map,this._index=0}get(n){return this._objectIndexMap.get(n)}getOrCreate(n){let e=this._objectIndexMap.get(n);return e==null&&(e=this._index,this._objectIndexMap.set(n,e),this._index++),e}};function vJ(n){var e,t,i,a;const r=new Ct;r.name=n.name,r.setIndex(n.index);for(const[s,o]of Object.entries(n.attributes))r.setAttribute(s,o);for(const[s,o]of Object.entries(n.morphAttributes)){const c=s;r.morphAttributes[c]=o.concat()}r.morphTargetsRelative=n.morphTargetsRelative,r.groups=[];for(const s of n.groups)r.addGroup(s.start,s.count,s.materialIndex);return r.boundingSphere=(t=(e=n.boundingSphere)==null?void 0:e.clone())!=null?t:null,r.boundingBox=(a=(i=n.boundingBox)==null?void 0:i.clone())!=null?a:null,r.drawRange.start=n.drawRange.start,r.drawRange.count=n.drawRange.count,r.userData=n.userData,r}function PD(n){if(Object.values(n).forEach(e=>{e!=null&&e.isTexture&&e.dispose()}),n.isShaderMaterial){const e=n.uniforms;e&&Object.values(e).forEach(t=>{const i=t.value;i!=null&&i.isTexture&&i.dispose()})}n.dispose()}function _J(n){const e=n.geometry;e&&e.dispose();const t=n.skeleton;t&&t.dispose();const i=n.material;i&&(Array.isArray(i)?i.forEach(a=>PD(a)):i&&PD(i))}function xJ(n){n.traverse(_J)}function yJ(n,e){var t,i;console.warn("VRMUtils.removeUnnecessaryJoints: removeUnnecessaryJoints is deprecated. Use combineSkeletons instead. combineSkeletons contributes more to the performance improvement. This function will be removed in the next major version.");const a=(t=e==null?void 0:e.experimentalSameBoneCounts)!=null?t:!1,r=[];n.traverse(c=>{c.type==="SkinnedMesh"&&r.push(c)});const s=new Map;let o=0;for(const c of r){const f=c.geometry.getAttribute("skinIndex");if(s.has(f))continue;const d=new Map,m=new Map;for(let g=0;g{var i,a,r,s;if(!t.isMesh)return;const o=t,c=o.geometry,h=c.index;if(h==null)return;const f=e.get(c);if(f!=null){o.geometry=f;return}const d=Object.values(c.attributes)[0].count,m=new Array(d);let g=0;const x=h.array;for(let b=0;b{S.addGroup(b.start,b.count,b.materialIndex)}),S.boundingBox=(a=(i=c.boundingBox)==null?void 0:i.clone())!=null?a:null,S.boundingSphere=(s=(r=c.boundingSphere)==null?void 0:r.clone())!=null?s:null,S.setDrawRange(c.drawRange.start,c.drawRange.count),S.userData=c.userData,e.set(c,S);{const b=h.array,D=new b.constructor(b.length);for(let C=0;C{const D=c.attributes[b];if(D.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const C=D.array,{itemSize:I,normalized:P}=D,O=new C.constructor(y.length*I);y.forEach((w,B)=>{for(let j=0;j{for(let re=0;reee===0),S.morphAttributes[C][I]=new Ot(j,w,B)}}E&&(S.morphAttributes={}),o.geometry=S}),Array.from(e.keys()).forEach(t=>{t.dispose()})}function TJ(n){var e;((e=n.meta)==null?void 0:e.metaVersion)==="0"&&(n.scene.rotation.y=Math.PI)}var ph=class{constructor(){}};ph.combineMorphs=cJ;ph.combineSkeletons=uJ;ph.deepDispose=xJ;ph.removeUnnecessaryJoints=yJ;ph.removeUnnecessaryVertices=SJ;ph.rotateVRM0=TJ;/*! - * @pixiv/three-vrm-core v3.4.4 - * The implementation of core features of VRM, for @pixiv/three-vrm - * - * Copyright (c) 2019-2025 pixiv Inc. - * @pixiv/three-vrm-core is distributed under MIT License - * https://github.com/pixiv/three-vrm/blob/release/LICENSE - *//*! - * @pixiv/three-vrm-materials-mtoon v3.4.4 - * MToon (toon material) module for @pixiv/three-vrm - * - * Copyright (c) 2019-2025 pixiv Inc. - * @pixiv/three-vrm-materials-mtoon is distributed under MIT License - * https://github.com/pixiv/three-vrm/blob/release/LICENSE - *//*! - * @pixiv/three-vrm-materials-hdr-emissive-multiplier v3.4.4 - * Support VRMC_hdr_emissiveMultiplier for @pixiv/three-vrm - * - * Copyright (c) 2019-2025 pixiv Inc. - * @pixiv/three-vrm-materials-hdr-emissive-multiplier is distributed under MIT License - * https://github.com/pixiv/three-vrm/blob/release/LICENSE - *//*! - * @pixiv/three-vrm-materials-v0compat v3.4.4 - * VRM0.0 materials compatibility layer plugin for @pixiv/three-vrm - * - * Copyright (c) 2019-2025 pixiv Inc. - * @pixiv/three-vrm-materials-v0compat is distributed under MIT License - * https://github.com/pixiv/three-vrm/blob/release/LICENSE - *//*! - * @pixiv/three-vrm-node-constraint v3.4.4 - * Node constraint module for @pixiv/three-vrm - * - * Copyright (c) 2019-2025 pixiv Inc. - * @pixiv/three-vrm-node-constraint is distributed under MIT License - * https://github.com/pixiv/three-vrm/blob/release/LICENSE - *//*! - * @pixiv/three-vrm-springbone v3.4.4 - * Spring bone module for @pixiv/three-vrm - * - * Copyright (c) 2019-2025 pixiv Inc. - * @pixiv/three-vrm-springbone is distributed under MIT License - * https://github.com/pixiv/three-vrm/blob/release/LICENSE - *//*! - * @pixiv/three-vrm-animation v3.4.4 - * The implementation of VRM Animation - * - * Copyright (c) 2019-2025 pixiv Inc. - * @pixiv/three-vrm-animation is distributed under MIT License - * https://github.com/pixiv/three-vrm/blob/release/LICENSE - */var zD=(n,e,t)=>new Promise((i,a)=>{var r=c=>{try{o(t.next(c))}catch(h){a(h)}},s=c=>{try{o(t.throw(c))}catch(h){a(h)}},o=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,s);o((t=t.apply(n,e)).next())}),EJ={Aa:"aa",Ih:"ih",Ou:"ou",Ee:"ee",Oh:"oh",Blink:"blink",Happy:"happy",Angry:"angry",Sad:"sad",Relaxed:"relaxed",LookUp:"lookUp",Surprised:"surprised",LookDown:"lookDown",LookLeft:"lookLeft",LookRight:"lookRight",BlinkLeft:"blinkLeft",BlinkRight:"blinkRight",Neutral:"neutral"};new je;new de;new L;new L;var BD={hips:null,spine:"hips",chest:"spine",upperChest:"chest",neck:"upperChest",head:"neck",leftEye:"head",rightEye:"head",jaw:"head",leftUpperLeg:"hips",leftLowerLeg:"leftUpperLeg",leftFoot:"leftLowerLeg",leftToes:"leftFoot",rightUpperLeg:"hips",rightLowerLeg:"rightUpperLeg",rightFoot:"rightLowerLeg",rightToes:"rightFoot",leftShoulder:"upperChest",leftUpperArm:"leftShoulder",leftLowerArm:"leftUpperArm",leftHand:"leftLowerArm",rightShoulder:"upperChest",rightUpperArm:"rightShoulder",rightLowerArm:"rightUpperArm",rightHand:"rightLowerArm",leftThumbMetacarpal:"leftHand",leftThumbProximal:"leftThumbMetacarpal",leftThumbDistal:"leftThumbProximal",leftIndexProximal:"leftHand",leftIndexIntermediate:"leftIndexProximal",leftIndexDistal:"leftIndexIntermediate",leftMiddleProximal:"leftHand",leftMiddleIntermediate:"leftMiddleProximal",leftMiddleDistal:"leftMiddleIntermediate",leftRingProximal:"leftHand",leftRingIntermediate:"leftRingProximal",leftRingDistal:"leftRingIntermediate",leftLittleProximal:"leftHand",leftLittleIntermediate:"leftLittleProximal",leftLittleDistal:"leftLittleIntermediate",rightThumbMetacarpal:"rightHand",rightThumbProximal:"rightThumbMetacarpal",rightThumbDistal:"rightThumbProximal",rightIndexProximal:"rightHand",rightIndexIntermediate:"rightIndexProximal",rightIndexDistal:"rightIndexIntermediate",rightMiddleProximal:"rightHand",rightMiddleIntermediate:"rightMiddleProximal",rightMiddleDistal:"rightMiddleIntermediate",rightRingProximal:"rightHand",rightRingIntermediate:"rightRingProximal",rightRingDistal:"rightRingIntermediate",rightLittleProximal:"rightHand",rightLittleIntermediate:"rightLittleProximal",rightLittleDistal:"rightLittleIntermediate"};function MJ(n){return n.invert?n.invert():n.inverse(),n}new L;new L;new L;new L;new L;new L(0,1,0);var bJ=new L,AJ=new L;function wJ(n,e){return n.matrixWorld.decompose(bJ,e,AJ),e}function H2(n){return[Math.atan2(-n.z,n.x),Math.atan2(n.y,Math.sqrt(n.x*n.x+n.z*n.z))]}function HD(n){const e=Math.round(n/2/Math.PI);return n-2*Math.PI*e}var FD=new L(0,0,1),RJ=new L,CJ=new L,NJ=new L,DJ=new St,F2=new St,GD=new St,OJ=new St,G2=new Ei,V8=class k8{constructor(e,t){this.offsetFromHeadBone=new L,this.autoUpdate=!0,this.faceFront=new L(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new St)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn("VRMLookAt: euler is deprecated. use getEuler() instead."),this.getEuler(new Ei)}getEuler(e){return e.set($t.DEG2RAD*this._pitch,$t.DEG2RAD*this._yaw,0,"YXZ")}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMLookAt: humanoid must be same in order to copy");return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new k8(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){const t=this.humanoid.getRawBoneNode("head");return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){const t=this.humanoid.getRawBoneNode("head");return wJ(t,e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(FD)<.01)return e.copy(this._restHeadWorldQuaternion).invert();const[t,i]=H2(this.faceFront);return G2.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(G2).premultiply(OJ.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(F2),this.getFaceFrontQuaternion(GD),e.copy(FD).applyQuaternion(F2).applyQuaternion(GD).applyEuler(this.getEuler(G2))}lookAt(e){const t=DJ.copy(this._restHeadWorldQuaternion).multiply(MJ(this.getLookAtWorldQuaternion(F2))),i=this.getLookAtWorldPosition(CJ),a=NJ.copy(e).sub(i).applyQuaternion(t).normalize(),[r,s]=H2(this.faceFront),[o,c]=H2(a),h=HD(o-r),f=HD(s-c);this._yaw=$t.RAD2DEG*h,this._pitch=$t.RAD2DEG*f,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(RJ)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};V8.EULER_ORDER="YXZ";var LJ=V8;new L(0,0,1);new Ei(0,0,0,"YXZ");var VD=180/Math.PI,V2=new Ei,kD=class extends Wt{constructor(n){super(),this.vrmLookAt=n,this.type="VRMLookAtQuaternionProxy";const e=this.rotation._onChangeCallback;this.rotation._onChange(()=>{e(),this._applyToLookAt()});const t=this.quaternion._onChangeCallback;this.quaternion._onChange(()=>{t(),this._applyToLookAt()})}_applyToLookAt(){V2.setFromQuaternion(this.quaternion,LJ.EULER_ORDER),this.vrmLookAt.yaw=VD*V2.y,this.vrmLookAt.pitch=VD*V2.x}};function IJ(n,e,t){var i,a;const r=new Map,s=new Map;for(const[o,c]of n.humanoidTracks.rotation.entries()){const h=(i=e.getNormalizedBoneNode(o))==null?void 0:i.name;if(h!=null){const f=new yc(`${h}.quaternion`,c.times,c.values.map((d,m)=>t==="0"&&m%2===0?-d:d));s.set(o,f)}}for(const[o,c]of n.humanoidTracks.translation.entries()){const h=(a=e.getNormalizedBoneNode(o))==null?void 0:a.name;if(h!=null){const f=n.restHipsPosition.y,m=e.normalizedRestPose.hips.position[1]/f,g=c.clone();g.values=g.values.map((x,T)=>(t==="0"&&T%3!==1?-x:x)*m),g.name=`${h}.position`,r.set(o,g)}}return{translation:r,rotation:s}}function UJ(n,e){const t=new Map,i=new Map;for(const[a,r]of n.expressionTracks.preset.entries()){const s=e.getExpressionTrackName(a);if(s!=null){const o=r.clone();o.name=s,t.set(a,o)}}for(const[a,r]of n.expressionTracks.custom.entries()){const s=e.getExpressionTrackName(a);if(s!=null){const o=r.clone();o.name=s,i.set(a,o)}}return{preset:t,custom:i}}function PJ(n,e){if(n.lookAtTrack==null)return null;const t=n.lookAtTrack.clone();return t.name=e,t}function zJ(n,e){const t=[],i=IJ(n,e.humanoid,e.meta.metaVersion);if(t.push(...i.translation.values()),t.push(...i.rotation.values()),e.expressionManager!=null){const a=UJ(n,e.expressionManager);t.push(...a.preset.values()),t.push(...a.custom.values())}if(e.lookAt!=null){let a=e.scene.children.find(s=>s instanceof kD);a==null?(console.warn("createVRMAnimationClip: VRMLookAtQuaternionProxy is not found. Creating a new one automatically. To suppress this warning, create a VRMLookAtQuaternionProxy manually"),a=new kD(e.lookAt),a.name="VRMLookAtQuaternionProxy",e.scene.add(a)):a.name===""&&(console.warn("createVRMAnimationClip: VRMLookAtQuaternionProxy is found but its name is not set. Setting the name automatically. To suppress this warning, set the name manually"),a.name="VRMLookAtQuaternionProxy");const r=PJ(n,`${a.name}.quaternion`);r!=null&&t.push(r)}return new Ju("Clip",n.duration,t)}var BJ=class{constructor(){this.duration=0,this.restHipsPosition=new L,this.humanoidTracks={translation:new Map,rotation:new Map},this.expressionTracks={preset:new Map,custom:new Map},this.lookAtTrack=null}};function WD(n,e){const t=n.length,i=[];let a=[],r=0;for(let s=0;s{const v=a.animations[y],S=this._parseAnimation(T,v,c,h);return S.restHipsPosition=m,S});n.userData.vrmAnimations=x})}_createNodeMap(n){var e,t,i,a,r;const s=new Map,o=new Map,c=(e=n.humanoid)==null?void 0:e.humanBones;c&&Object.entries(c).forEach(([m,g])=>{const x=g==null?void 0:g.node;x!=null&&s.set(x,m)});const h=(t=n.expressions)==null?void 0:t.preset;h&&Object.entries(h).forEach(([m,g])=>{const x=g==null?void 0:g.node;x!=null&&o.set(x,m)});const f=(i=n.expressions)==null?void 0:i.custom;f&&Object.entries(f).forEach(([m,g])=>{const{node:x}=g;o.set(x,m)});const d=(r=(a=n.lookAt)==null?void 0:a.node)!=null?r:null;return{humanoidIndexToName:s,expressionsIndexToName:o,lookAtIndex:d}}_createBoneWorldMatrixMap(n,e){return zD(this,null,function*(){var t,i;n.scene.updateWorldMatrix(!1,!0);const a=yield n.parser.getDependencies("node"),r=new Map;if(e.humanoid==null)return r;for(const[s,o]of Object.entries(e.humanoid.humanBones)){const c=o==null?void 0:o.node;if(c!=null){const h=a[c];r.set(s,h.matrixWorld),s==="hips"&&r.set("hipsParent",(i=(t=h.parent)==null?void 0:t.matrixWorld)!=null?i:HJ)}}return r})}_parseAnimation(n,e,t,i){const a=n.tracks,r=e.channels,s=new BJ;return s.duration=n.duration,r.forEach((o,c)=>{const{node:h,path:f}=o.target,d=a[c];if(h==null)return;const m=t.humanoidIndexToName.get(h);if(m!=null){let x=BD[m];for(;x!=null&&i.get(x)==null;)x=BD[x];if(x==null&&(x="hipsParent"),f==="translation")if(m!=="hips")console.warn(`The loading animation contains a translation track for ${m}, which is not permitted in the VRMC_vrm_animation spec. ignoring the track`);else{const T=i.get("hipsParent"),y=WD(d.values,3).flatMap(S=>Jp.fromArray(S).applyMatrix4(T).toArray()),v=d.clone();v.values=new Float32Array(y),s.humanoidTracks.translation.set(m,v)}else if(f==="rotation"){const T=i.get(m),y=i.get(x);T.decompose(Jp,k2,Jp),k2.invert(),y.decompose(Jp,XD,Jp);const v=WD(d.values,4).flatMap(E=>FJ.fromArray(E).premultiply(XD).multiply(k2).toArray()),S=d.clone();S.values=new Float32Array(v),s.humanoidTracks.rotation.set(m,S)}else throw new Error(`Invalid path "${f}"`);return}const g=t.expressionsIndexToName.get(h);if(g!=null){if(f==="translation"){const x=d.times,T=new Float32Array(d.values.length/3);for(let v=0;ve in n?WJ(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,YJ=(n,e,t)=>(XJ(n,e+"",t),t);class qJ{constructor(){YJ(this,"_listeners")}addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;const a=this._listeners[e];if(a!==void 0){const r=a.indexOf(t);r!==-1&&a.splice(r,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const i=this._listeners[e.type];if(i!==void 0){e.target=this;const a=i.slice(0);for(let r=0,s=a.length;re in n?jJ(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Dt=(n,e,t)=>(ZJ(n,typeof e!="symbol"?e+"":e,t),t);const Vv=new lh,YD=new Go,KJ=Math.cos(70*(Math.PI/180)),qD=(n,e)=>(n%e+e)%e;let QJ=class extends qJ{constructor(e,t){super(),Dt(this,"object"),Dt(this,"domElement"),Dt(this,"enabled",!0),Dt(this,"target",new L),Dt(this,"minDistance",0),Dt(this,"maxDistance",1/0),Dt(this,"minZoom",0),Dt(this,"maxZoom",1/0),Dt(this,"minPolarAngle",0),Dt(this,"maxPolarAngle",Math.PI),Dt(this,"minAzimuthAngle",-1/0),Dt(this,"maxAzimuthAngle",1/0),Dt(this,"enableDamping",!1),Dt(this,"dampingFactor",.05),Dt(this,"enableZoom",!0),Dt(this,"zoomSpeed",1),Dt(this,"enableRotate",!0),Dt(this,"rotateSpeed",1),Dt(this,"enablePan",!0),Dt(this,"panSpeed",1),Dt(this,"screenSpacePanning",!0),Dt(this,"keyPanSpeed",7),Dt(this,"zoomToCursor",!1),Dt(this,"autoRotate",!1),Dt(this,"autoRotateSpeed",2),Dt(this,"reverseOrbit",!1),Dt(this,"reverseHorizontalOrbit",!1),Dt(this,"reverseVerticalOrbit",!1),Dt(this,"keys",{LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"}),Dt(this,"mouseButtons",{LEFT:vu.ROTATE,MIDDLE:vu.DOLLY,RIGHT:vu.PAN}),Dt(this,"touches",{ONE:_u.ROTATE,TWO:_u.DOLLY_PAN}),Dt(this,"target0"),Dt(this,"position0"),Dt(this,"zoom0"),Dt(this,"_domElementKeyEvents",null),Dt(this,"getPolarAngle"),Dt(this,"getAzimuthalAngle"),Dt(this,"setPolarAngle"),Dt(this,"setAzimuthalAngle"),Dt(this,"getDistance"),Dt(this,"getZoomScale"),Dt(this,"listenToKeyEvents"),Dt(this,"stopListenToKeyEvents"),Dt(this,"saveState"),Dt(this,"reset"),Dt(this,"update"),Dt(this,"connect"),Dt(this,"dispose"),Dt(this,"dollyIn"),Dt(this,"dollyOut"),Dt(this,"getScale"),Dt(this,"setScale"),this.object=e,this.domElement=t,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this.getPolarAngle=()=>f.phi,this.getAzimuthalAngle=()=>f.theta,this.setPolarAngle=Q=>{let pe=qD(Q,2*Math.PI),Oe=f.phi;Oe<0&&(Oe+=2*Math.PI),pe<0&&(pe+=2*Math.PI);let q=Math.abs(pe-Oe);2*Math.PI-q{let pe=qD(Q,2*Math.PI),Oe=f.theta;Oe<0&&(Oe+=2*Math.PI),pe<0&&(pe+=2*Math.PI);let q=Math.abs(pe-Oe);2*Math.PI-qi.object.position.distanceTo(i.target),this.listenToKeyEvents=Q=>{Q.addEventListener("keydown",ye),this._domElementKeyEvents=Q},this.stopListenToKeyEvents=()=>{this._domElementKeyEvents.removeEventListener("keydown",ye),this._domElementKeyEvents=null},this.saveState=()=>{i.target0.copy(i.target),i.position0.copy(i.object.position),i.zoom0=i.object.zoom},this.reset=()=>{i.target.copy(i.target0),i.object.position.copy(i.position0),i.object.zoom=i.zoom0,i.object.updateProjectionMatrix(),i.dispatchEvent(a),i.update(),c=o.NONE},this.update=(()=>{const Q=new L,pe=new L(0,1,0),Oe=new St().setFromUnitVectors(e.up,pe),q=Oe.clone().invert(),Ve=new L,me=new St,We=2*Math.PI;return function(){const we=i.object.position;Oe.setFromUnitVectors(e.up,pe),q.copy(Oe).invert(),Q.copy(we).sub(i.target),Q.applyQuaternion(Oe),f.setFromVector3(Q),i.autoRotate&&c===o.NONE&&se(j()),i.enableDamping?(f.theta+=d.theta*i.dampingFactor,f.phi+=d.phi*i.dampingFactor):(f.theta+=d.theta,f.phi+=d.phi);let rt=i.minAzimuthAngle,yt=i.maxAzimuthAngle;isFinite(rt)&&isFinite(yt)&&(rt<-Math.PI?rt+=We:rt>Math.PI&&(rt-=We),yt<-Math.PI?yt+=We:yt>Math.PI&&(yt-=We),rt<=yt?f.theta=Math.max(rt,Math.min(yt,f.theta)):f.theta=f.theta>(rt+yt)/2?Math.max(rt,f.theta):Math.min(yt,f.theta)),f.phi=Math.max(i.minPolarAngle,Math.min(i.maxPolarAngle,f.phi)),f.makeSafe(),i.enableDamping===!0?i.target.addScaledVector(g,i.dampingFactor):i.target.add(g),i.zoomToCursor&&O||i.object.isOrthographicCamera?f.radius=nt(f.radius):f.radius=nt(f.radius*m),Q.setFromSpherical(f),Q.applyQuaternion(q),we.copy(i.target).add(Q),i.object.matrixAutoUpdate||i.object.updateMatrix(),i.object.lookAt(i.target),i.enableDamping===!0?(d.theta*=1-i.dampingFactor,d.phi*=1-i.dampingFactor,g.multiplyScalar(1-i.dampingFactor)):(d.set(0,0,0),g.set(0,0,0));let Gt=!1;if(i.zoomToCursor&&O){let Vt=null;if(i.object instanceof hi&&i.object.isPerspectiveCamera){const li=Q.length();Vt=nt(li*m);const ci=li-Vt;i.object.position.addScaledVector(I,ci),i.object.updateMatrixWorld()}else if(i.object.isOrthographicCamera){const li=new L(P.x,P.y,0);li.unproject(i.object),i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/m)),i.object.updateProjectionMatrix(),Gt=!0;const ci=new L(P.x,P.y,0);ci.unproject(i.object),i.object.position.sub(ci).add(li),i.object.updateMatrixWorld(),Vt=Q.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),i.zoomToCursor=!1;Vt!==null&&(i.screenSpacePanning?i.target.set(0,0,-1).transformDirection(i.object.matrix).multiplyScalar(Vt).add(i.object.position):(Vv.origin.copy(i.object.position),Vv.direction.set(0,0,-1).transformDirection(i.object.matrix),Math.abs(i.object.up.dot(Vv.direction))h||8*(1-me.dot(i.object.quaternion))>h?(i.dispatchEvent(a),Ve.copy(i.object.position),me.copy(i.object.quaternion),Gt=!1,!0):!1}})(),this.connect=Q=>{i.domElement=Q,i.domElement.style.touchAction="none",i.domElement.addEventListener("contextmenu",_t),i.domElement.addEventListener("pointerdown",ct),i.domElement.addEventListener("pointercancel",U),i.domElement.addEventListener("wheel",Le)},this.dispose=()=>{var Q,pe,Oe,q,Ve,me;i.domElement&&(i.domElement.style.touchAction="auto"),(Q=i.domElement)==null||Q.removeEventListener("contextmenu",_t),(pe=i.domElement)==null||pe.removeEventListener("pointerdown",ct),(Oe=i.domElement)==null||Oe.removeEventListener("pointercancel",U),(q=i.domElement)==null||q.removeEventListener("wheel",Le),(Ve=i.domElement)==null||Ve.ownerDocument.removeEventListener("pointermove",k),(me=i.domElement)==null||me.ownerDocument.removeEventListener("pointerup",U),i._domElementKeyEvents!==null&&i._domElementKeyEvents.removeEventListener("keydown",ye)};const i=this,a={type:"change"},r={type:"start"},s={type:"end"},o={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let c=o.NONE;const h=1e-6,f=new pE,d=new pE;let m=1;const g=new L,x=new de,T=new de,y=new de,v=new de,S=new de,E=new de,b=new de,D=new de,C=new de,I=new L,P=new de;let O=!1;const w=[],B={};function j(){return 2*Math.PI/60/60*i.autoRotateSpeed}function ee(){return Math.pow(.95,i.zoomSpeed)}function se(Q){i.reverseOrbit||i.reverseHorizontalOrbit?d.theta+=Q:d.theta-=Q}function re(Q){i.reverseOrbit||i.reverseVerticalOrbit?d.phi+=Q:d.phi-=Q}const W=(()=>{const Q=new L;return function(Oe,q){Q.setFromMatrixColumn(q,0),Q.multiplyScalar(-Oe),g.add(Q)}})(),te=(()=>{const Q=new L;return function(Oe,q){i.screenSpacePanning===!0?Q.setFromMatrixColumn(q,1):(Q.setFromMatrixColumn(q,0),Q.crossVectors(i.object.up,Q)),Q.multiplyScalar(Oe),g.add(Q)}})(),K=(()=>{const Q=new L;return function(Oe,q){const Ve=i.domElement;if(Ve&&i.object instanceof hi&&i.object.isPerspectiveCamera){const me=i.object.position;Q.copy(me).sub(i.target);let We=Q.length();We*=Math.tan(i.object.fov/2*Math.PI/180),W(2*Oe*We/Ve.clientHeight,i.object.matrix),te(2*q*We/Ve.clientHeight,i.object.matrix)}else Ve&&i.object instanceof ao&&i.object.isOrthographicCamera?(W(Oe*(i.object.right-i.object.left)/i.object.zoom/Ve.clientWidth,i.object.matrix),te(q*(i.object.top-i.object.bottom)/i.object.zoom/Ve.clientHeight,i.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),i.enablePan=!1)}})();function oe(Q){i.object instanceof hi&&i.object.isPerspectiveCamera||i.object instanceof ao&&i.object.isOrthographicCamera?m=Q:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function ie(Q){oe(m/Q)}function Ce(Q){oe(m*Q)}function Xe(Q){if(!i.zoomToCursor||!i.domElement)return;O=!0;const pe=i.domElement.getBoundingClientRect(),Oe=Q.clientX-pe.left,q=Q.clientY-pe.top,Ve=pe.width,me=pe.height;P.x=Oe/Ve*2-1,P.y=-(q/me)*2+1,I.set(P.x,P.y,1).unproject(i.object).sub(i.object.position).normalize()}function nt(Q){return Math.max(i.minDistance,Math.min(i.maxDistance,Q))}function tt(Q){x.set(Q.clientX,Q.clientY)}function gt(Q){Xe(Q),b.set(Q.clientX,Q.clientY)}function ge(Q){v.set(Q.clientX,Q.clientY)}function Ae(Q){T.set(Q.clientX,Q.clientY),y.subVectors(T,x).multiplyScalar(i.rotateSpeed);const pe=i.domElement;pe&&(se(2*Math.PI*y.x/pe.clientHeight),re(2*Math.PI*y.y/pe.clientHeight)),x.copy(T),i.update()}function Ze(Q){D.set(Q.clientX,Q.clientY),C.subVectors(D,b),C.y>0?ie(ee()):C.y<0&&Ce(ee()),b.copy(D),i.update()}function ue(Q){S.set(Q.clientX,Q.clientY),E.subVectors(S,v).multiplyScalar(i.panSpeed),K(E.x,E.y),v.copy(S),i.update()}function it(Q){Xe(Q),Q.deltaY<0?Ce(ee()):Q.deltaY>0&&ie(ee()),i.update()}function Mt(Q){let pe=!1;switch(Q.code){case i.keys.UP:K(0,i.keyPanSpeed),pe=!0;break;case i.keys.BOTTOM:K(0,-i.keyPanSpeed),pe=!0;break;case i.keys.LEFT:K(i.keyPanSpeed,0),pe=!0;break;case i.keys.RIGHT:K(-i.keyPanSpeed,0),pe=!0;break}pe&&(Q.preventDefault(),i.update())}function ot(){if(w.length==1)x.set(w[0].pageX,w[0].pageY);else{const Q=.5*(w[0].pageX+w[1].pageX),pe=.5*(w[0].pageY+w[1].pageY);x.set(Q,pe)}}function Ke(){if(w.length==1)v.set(w[0].pageX,w[0].pageY);else{const Q=.5*(w[0].pageX+w[1].pageX),pe=.5*(w[0].pageY+w[1].pageY);v.set(Q,pe)}}function Te(){const Q=w[0].pageX-w[1].pageX,pe=w[0].pageY-w[1].pageY,Oe=Math.sqrt(Q*Q+pe*pe);b.set(0,Oe)}function G(){i.enableZoom&&Te(),i.enablePan&&Ke()}function be(){i.enableZoom&&Te(),i.enableRotate&&ot()}function De(Q){if(w.length==1)T.set(Q.pageX,Q.pageY);else{const Oe=ht(Q),q=.5*(Q.pageX+Oe.x),Ve=.5*(Q.pageY+Oe.y);T.set(q,Ve)}y.subVectors(T,x).multiplyScalar(i.rotateSpeed);const pe=i.domElement;pe&&(se(2*Math.PI*y.x/pe.clientHeight),re(2*Math.PI*y.y/pe.clientHeight)),x.copy(T)}function Fe(Q){if(w.length==1)S.set(Q.pageX,Q.pageY);else{const pe=ht(Q),Oe=.5*(Q.pageX+pe.x),q=.5*(Q.pageY+pe.y);S.set(Oe,q)}E.subVectors(S,v).multiplyScalar(i.panSpeed),K(E.x,E.y),v.copy(S)}function Be(Q){const pe=ht(Q),Oe=Q.pageX-pe.x,q=Q.pageY-pe.y,Ve=Math.sqrt(Oe*Oe+q*q);D.set(0,Ve),C.set(0,Math.pow(D.y/b.y,i.zoomSpeed)),ie(C.y),b.copy(D)}function $e(Q){i.enableZoom&&Be(Q),i.enablePan&&Fe(Q)}function Je(Q){i.enableZoom&&Be(Q),i.enableRotate&&De(Q)}function ct(Q){var pe,Oe;i.enabled!==!1&&(w.length===0&&((pe=i.domElement)==null||pe.ownerDocument.addEventListener("pointermove",k),(Oe=i.domElement)==null||Oe.ownerDocument.addEventListener("pointerup",U)),pt(Q),Q.pointerType==="touch"?vt(Q):ce(Q))}function k(Q){i.enabled!==!1&&(Q.pointerType==="touch"?qe(Q):Ee(Q))}function U(Q){var pe,Oe,q;Ie(Q),w.length===0&&((pe=i.domElement)==null||pe.releasePointerCapture(Q.pointerId),(Oe=i.domElement)==null||Oe.ownerDocument.removeEventListener("pointermove",k),(q=i.domElement)==null||q.ownerDocument.removeEventListener("pointerup",U)),i.dispatchEvent(s),c=o.NONE}function ce(Q){let pe;switch(Q.button){case 0:pe=i.mouseButtons.LEFT;break;case 1:pe=i.mouseButtons.MIDDLE;break;case 2:pe=i.mouseButtons.RIGHT;break;default:pe=-1}switch(pe){case vu.DOLLY:if(i.enableZoom===!1)return;gt(Q),c=o.DOLLY;break;case vu.ROTATE:if(Q.ctrlKey||Q.metaKey||Q.shiftKey){if(i.enablePan===!1)return;ge(Q),c=o.PAN}else{if(i.enableRotate===!1)return;tt(Q),c=o.ROTATE}break;case vu.PAN:if(Q.ctrlKey||Q.metaKey||Q.shiftKey){if(i.enableRotate===!1)return;tt(Q),c=o.ROTATE}else{if(i.enablePan===!1)return;ge(Q),c=o.PAN}break;default:c=o.NONE}c!==o.NONE&&i.dispatchEvent(r)}function Ee(Q){if(i.enabled!==!1)switch(c){case o.ROTATE:if(i.enableRotate===!1)return;Ae(Q);break;case o.DOLLY:if(i.enableZoom===!1)return;Ze(Q);break;case o.PAN:if(i.enablePan===!1)return;ue(Q);break}}function Le(Q){i.enabled===!1||i.enableZoom===!1||c!==o.NONE&&c!==o.ROTATE||(Q.preventDefault(),i.dispatchEvent(r),it(Q),i.dispatchEvent(s))}function ye(Q){i.enabled===!1||i.enablePan===!1||Mt(Q)}function vt(Q){switch(He(Q),w.length){case 1:switch(i.touches.ONE){case _u.ROTATE:if(i.enableRotate===!1)return;ot(),c=o.TOUCH_ROTATE;break;case _u.PAN:if(i.enablePan===!1)return;Ke(),c=o.TOUCH_PAN;break;default:c=o.NONE}break;case 2:switch(i.touches.TWO){case _u.DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;G(),c=o.TOUCH_DOLLY_PAN;break;case _u.DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;be(),c=o.TOUCH_DOLLY_ROTATE;break;default:c=o.NONE}break;default:c=o.NONE}c!==o.NONE&&i.dispatchEvent(r)}function qe(Q){switch(He(Q),c){case o.TOUCH_ROTATE:if(i.enableRotate===!1)return;De(Q),i.update();break;case o.TOUCH_PAN:if(i.enablePan===!1)return;Fe(Q),i.update();break;case o.TOUCH_DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;$e(Q),i.update();break;case o.TOUCH_DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;Je(Q),i.update();break;default:c=o.NONE}}function _t(Q){i.enabled!==!1&&Q.preventDefault()}function pt(Q){w.push(Q)}function Ie(Q){delete B[Q.pointerId];for(let pe=0;pe{Ce(Q),i.update()},this.dollyOut=(Q=ee())=>{ie(Q),i.update()},this.getScale=()=>m,this.setScale=Q=>{oe(Q),i.update()},this.getZoomScale=()=>ee(),t!==void 0&&this.connect(t),this.update()}};function JJ(n,e,t){const i=Oi(g=>g.size),a=Oi(g=>g.viewport),r=typeof n=="number"?n:i.width*a.dpr,s=i.height*a.dpr,o=(typeof n=="number"?t:n)||{},{samples:c=0,depth:h,...f}=o,d=h??o.depthBuffer,m=Me.useMemo(()=>{const g=new xi(r,s,{minFilter:Ht,magFilter:Ht,type:Xn,...f});return d&&(g.depthTexture=new z0(r,s,si)),g.samples=c,g},[]);return Me.useLayoutEffect(()=>{m.setSize(r,s),c&&(m.samples=c)},[c,m,r,s]),Me.useEffect(()=>()=>m.dispose(),[]),m}const $J=n=>typeof n=="function",W8=Me.forwardRef(({envMap:n,resolution:e=256,frames:t=1/0,makeDefault:i,children:a,...r},s)=>{const o=Oi(({set:y})=>y),c=Oi(({camera:y})=>y),h=Oi(({size:y})=>y),f=Me.useRef(null);Me.useImperativeHandle(s,()=>f.current,[]);const d=Me.useRef(null),m=JJ(e);Me.useLayoutEffect(()=>{r.manual||(f.current.aspect=h.width/h.height)},[h,r]),Me.useLayoutEffect(()=>{f.current.updateProjectionMatrix()});let g=0,x=null;const T=$J(a);return cl(y=>{T&&(t===1/0||g{if(i){const y=c;return o(()=>({camera:f.current})),()=>o(()=>({camera:y}))}},[f,i,o]),Me.createElement(Me.Fragment,null,Me.createElement("perspectiveCamera",Zx({ref:f},r),!T&&a),Me.createElement("group",{ref:d},T&&a(m.texture)))}),e$=Me.forwardRef(({makeDefault:n,camera:e,regress:t,domElement:i,enableDamping:a=!0,keyEvents:r=!1,onChange:s,onStart:o,onEnd:c,...h},f)=>{const d=Oi(C=>C.invalidate),m=Oi(C=>C.camera),g=Oi(C=>C.gl),x=Oi(C=>C.events),T=Oi(C=>C.setEvents),y=Oi(C=>C.set),v=Oi(C=>C.get),S=Oi(C=>C.performance),E=e||m,b=i||x.connected||g.domElement,D=Me.useMemo(()=>new QJ(E),[E]);return cl(()=>{D.enabled&&D.update()},-1),Me.useEffect(()=>(r&&D.connect(r===!0?b:r),D.connect(b),()=>void D.dispose()),[r,b,t,D,d]),Me.useEffect(()=>{const C=O=>{d(),t&&S.regress(),s&&s(O)},I=O=>{o&&o(O)},P=O=>{c&&c(O)};return D.addEventListener("change",C),D.addEventListener("start",I),D.addEventListener("end",P),()=>{D.removeEventListener("start",I),D.removeEventListener("end",P),D.removeEventListener("change",C)}},[s,o,c,D,d,T]),Me.useEffect(()=>{if(n){const C=v().controls;return y({controls:D}),()=>y({controls:C})}},[n,D]),Me.createElement("primitive",Zx({ref:f,object:D,enableDamping:a},h))});/** - * postprocessing v6.38.0 build Sat Nov 08 2025 - * https://github.com/pmndrs/postprocessing - * Copyright 2015-2025 Raoul van Rüschen - * @license Zlib - */var W2=1/1e3,t$=1e3,n$=class{constructor(){this.startTime=performance.now(),this.previousTime=0,this.currentTime=0,this._delta=0,this._elapsed=0,this._fixedDelta=1e3/60,this.timescale=1,this.useFixedDelta=!1,this._autoReset=!1}get autoReset(){return this._autoReset}set autoReset(n){typeof document<"u"&&document.hidden!==void 0&&(n?document.addEventListener("visibilitychange",this):document.removeEventListener("visibilitychange",this),this._autoReset=n)}get delta(){return this._delta*W2}get fixedDelta(){return this._fixedDelta*W2}set fixedDelta(n){this._fixedDelta=n*t$}get elapsed(){return this._elapsed*W2}update(n){this.useFixedDelta?this._delta=this.fixedDelta:(this.previousTime=this.currentTime,this.currentTime=(n!==void 0?n:performance.now())-this.startTime,this._delta=this.currentTime-this.previousTime),this._delta*=this.timescale,this._elapsed+=this._delta}reset(){this._delta=0,this._elapsed=0,this.currentTime=performance.now()-this.startTime}getDelta(){return this.delta}getElapsed(){return this.elapsed}handleEvent(n){document.hidden||(this.currentTime=performance.now()-this.startTime)}dispose(){this.autoReset=!1}},i$=(()=>{const n=new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),e=new Float32Array([0,0,2,0,0,2]),t=new Ct;return t.setAttribute("position",new Ot(n,3)),t.setAttribute("uv",new Ot(e,2)),t})(),za=class LE{static get fullscreenGeometry(){return i$}constructor(e="Pass",t=new Rd,i=new ao){this.name=e,this.renderer=null,this.scene=t,this.camera=i,this.screen=null,this.rtt=!0,this.needsSwap=!0,this.needsDepthTexture=!1,this.enabled=!0}get renderToScreen(){return!this.rtt}set renderToScreen(e){if(this.rtt===e){const t=this.fullscreenMaterial;t!==null&&(t.needsUpdate=!0),this.rtt=!e}}set mainScene(e){}set mainCamera(e){}setRenderer(e){this.renderer=e}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}get fullscreenMaterial(){return this.screen!==null?this.screen.material:null}set fullscreenMaterial(e){let t=this.screen;t!==null?t.material=e:(t=new oi(LE.fullscreenGeometry,e),t.frustumCulled=!1,this.scene===null&&(this.scene=new Rd),this.scene.add(t),this.screen=t)}getFullscreenMaterial(){return this.fullscreenMaterial}setFullscreenMaterial(e){this.fullscreenMaterial=e}getDepthTexture(){return null}setDepthTexture(e,t=Mc){}render(e,t,i,a,r){throw new Error("Render method not implemented!")}setSize(e,t){}initialize(e,t,i){}dispose(){for(const e of Object.keys(this)){const t=this[e];(t instanceof xi||t instanceof qn||t instanceof Nn||t instanceof LE)&&this[e].dispose()}this.fullscreenMaterial!==null&&this.fullscreenMaterial.dispose()}},a$=class extends za{constructor(){super("ClearMaskPass",null,null),this.needsSwap=!1}render(n,e,t,i,a){const r=n.state.buffers.stencil;r.setLocked(!1),r.setTest(!1)}},r$=`#ifdef COLOR_WRITE -#include -#include -#ifdef FRAMEBUFFER_PRECISION_HIGH -uniform mediump sampler2D inputBuffer; -#else -uniform lowp sampler2D inputBuffer; -#endif -#endif -#ifdef DEPTH_WRITE -#include -#ifdef GL_FRAGMENT_PRECISION_HIGH -uniform highp sampler2D depthBuffer; -#else -uniform mediump sampler2D depthBuffer; -#endif -float readDepth(const in vec2 uv){ -#if DEPTH_PACKING == 3201 -return unpackRGBAToDepth(texture2D(depthBuffer,uv)); -#else -return texture2D(depthBuffer,uv).r; -#endif -} -#endif -#ifdef USE_WEIGHTS -uniform vec4 channelWeights; -#endif -uniform float opacity;varying vec2 vUv;void main(){ -#ifdef COLOR_WRITE -vec4 texel=texture2D(inputBuffer,vUv); -#ifdef USE_WEIGHTS -texel*=channelWeights; -#endif -gl_FragColor=opacity*texel; -#ifdef COLOR_SPACE_CONVERSION -#include -#endif -#include -#else -gl_FragColor=vec4(0.0); -#endif -#ifdef DEPTH_WRITE -gl_FragDepth=readDepth(vUv); -#endif -}`,sA="varying vec2 vUv;void main(){vUv=position.xy*0.5+0.5;gl_Position=vec4(position.xy,1.0,1.0);}",s$=class extends Vi{constructor(){super({name:"CopyMaterial",defines:{DEPTH_PACKING:"0",COLOR_WRITE:"1"},uniforms:{inputBuffer:new J(null),depthBuffer:new J(null),channelWeights:new J(null),opacity:new J(1)},blending:Ta,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:r$,vertexShader:sA}),this.depthFunc=r0}get inputBuffer(){return this.uniforms.inputBuffer.value}set inputBuffer(n){const e=n!==null;this.colorWrite!==e&&(e?this.defines.COLOR_WRITE=!0:delete this.defines.COLOR_WRITE,this.colorWrite=e,this.needsUpdate=!0),this.uniforms.inputBuffer.value=n}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(n){const e=n!==null;this.depthWrite!==e&&(e?this.defines.DEPTH_WRITE=!0:delete this.defines.DEPTH_WRITE,this.depthTest=e,this.depthWrite=e,this.needsUpdate=!0),this.uniforms.depthBuffer.value=n}set depthPacking(n){this.defines.DEPTH_PACKING=n.toFixed(0),this.needsUpdate=!0}get channelWeights(){return this.uniforms.channelWeights.value}set channelWeights(n){n!==null?(this.defines.USE_WEIGHTS="1",this.uniforms.channelWeights.value=n):delete this.defines.USE_WEIGHTS,this.needsUpdate=!0}setInputBuffer(n){this.uniforms.inputBuffer.value=n}getOpacity(n){return this.uniforms.opacity.value}setOpacity(n){this.uniforms.opacity.value=n}},X8=class extends za{constructor(n,e=!0){super("CopyPass"),this.fullscreenMaterial=new s$,this.needsSwap=!1,this.renderTarget=n,n===void 0&&(this.renderTarget=new xi(1,1,{minFilter:Ht,magFilter:Ht,stencilBuffer:!1,depthBuffer:!1}),this.renderTarget.texture.name="CopyPass.Target"),this.autoResize=e}get resize(){return this.autoResize}set resize(n){this.autoResize=n}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}setAutoResizeEnabled(n){this.autoResize=n}render(n,e,t,i,a){this.fullscreenMaterial.inputBuffer=e.texture,n.setRenderTarget(this.renderToScreen?null:this.renderTarget),n.render(this.scene,this.camera)}setSize(n,e){this.autoResize&&this.renderTarget.setSize(n,e)}initialize(n,e,t){t!==void 0&&(this.renderTarget.texture.type=t,t!==zi?this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1":n!==null&&n.outputColorSpace===En&&(this.renderTarget.texture.colorSpace=En))}},jD=new je,Y8=class extends za{constructor(n=!0,e=!0,t=!1){super("ClearPass",null,null),this.needsSwap=!1,this.color=n,this.depth=e,this.stencil=t,this.overrideClearColor=null,this.overrideClearAlpha=-1}setClearFlags(n,e,t){this.color=n,this.depth=e,this.stencil=t}getOverrideClearColor(){return this.overrideClearColor}setOverrideClearColor(n){this.overrideClearColor=n}getOverrideClearAlpha(){return this.overrideClearAlpha}setOverrideClearAlpha(n){this.overrideClearAlpha=n}render(n,e,t,i,a){const r=this.overrideClearColor,s=this.overrideClearAlpha,o=n.getClearAlpha(),c=r!==null,h=s>=0;c?(n.getClearColor(jD),n.setClearColor(r,h?s:o)):h&&n.setClearAlpha(s),n.setRenderTarget(this.renderToScreen?null:e),n.clear(this.color,this.depth,this.stencil),c?n.setClearColor(jD,o):h&&n.setClearAlpha(o)}},o$=class extends za{constructor(n,e){super("MaskPass",n,e),this.needsSwap=!1,this.clearPass=new Y8(!1,!1,!0),this.inverse=!1}set mainScene(n){this.scene=n}set mainCamera(n){this.camera=n}get inverted(){return this.inverse}set inverted(n){this.inverse=n}get clear(){return this.clearPass.enabled}set clear(n){this.clearPass.enabled=n}getClearPass(){return this.clearPass}isInverted(){return this.inverted}setInverted(n){this.inverted=n}render(n,e,t,i,a){const r=n.getContext(),s=n.state.buffers,o=this.scene,c=this.camera,h=this.clearPass,f=this.inverted?0:1,d=1-f;s.color.setMask(!1),s.depth.setMask(!1),s.color.setLocked(!0),s.depth.setLocked(!0),s.stencil.setTest(!0),s.stencil.setOp(r.REPLACE,r.REPLACE,r.REPLACE),s.stencil.setFunc(r.ALWAYS,f,4294967295),s.stencil.setClear(d),s.stencil.setLocked(!0),this.clearPass.enabled&&(this.renderToScreen?h.render(n,null):(h.render(n,e),h.render(n,t))),this.renderToScreen?(n.setRenderTarget(null),n.render(o,c)):(n.setRenderTarget(e),n.render(o,c),n.setRenderTarget(t),n.render(o,c)),s.color.setLocked(!1),s.depth.setLocked(!1),s.stencil.setLocked(!1),s.stencil.setFunc(r.EQUAL,1,4294967295),s.stencil.setOp(r.KEEP,r.KEEP,r.KEEP),s.stencil.setLocked(!0)}},l$=class{constructor(n=null,{depthBuffer:e=!0,stencilBuffer:t=!1,multisampling:i=0,frameBufferType:a}={}){this.renderer=null,this.inputBuffer=this.createBuffer(e,t,a,i),this.outputBuffer=this.inputBuffer.clone(),this.copyPass=new X8,this.depthTexture=null,this.passes=[],this.timer=new n$,this.autoRenderToScreen=!0,this.setRenderer(n)}get multisampling(){return this.inputBuffer.samples||0}set multisampling(n){const e=this.inputBuffer,t=this.multisampling;t>0&&n>0?(this.inputBuffer.samples=n,this.outputBuffer.samples=n,this.inputBuffer.dispose(),this.outputBuffer.dispose()):t!==n&&(this.inputBuffer.dispose(),this.outputBuffer.dispose(),this.inputBuffer=this.createBuffer(e.depthBuffer,e.stencilBuffer,e.texture.type,n),this.inputBuffer.depthTexture=this.depthTexture,this.outputBuffer=this.inputBuffer.clone())}getTimer(){return this.timer}getRenderer(){return this.renderer}setRenderer(n){if(this.renderer=n,n!==null){const e=n.getSize(new de),t=n.getContext().getContextAttributes().alpha,i=this.inputBuffer.texture.type;i===zi&&n.outputColorSpace===En&&(this.inputBuffer.texture.colorSpace=En,this.outputBuffer.texture.colorSpace=En,this.inputBuffer.dispose(),this.outputBuffer.dispose()),n.autoClear=!1,this.setSize(e.width,e.height);for(const a of this.passes)a.initialize(n,t,i)}}replaceRenderer(n,e=!0){const t=this.renderer,i=t.domElement.parentNode;return this.setRenderer(n),e&&i!==null&&(i.removeChild(t.domElement),i.appendChild(n.domElement)),t}createDepthTexture(){const n=this.depthTexture=new z0;return this.inputBuffer.depthTexture=n,this.inputBuffer.dispose(),this.inputBuffer.stencilBuffer?(n.format=ju,n.type=qu):n.type=Ds,n}deleteDepthTexture(){if(this.depthTexture!==null){this.depthTexture.dispose(),this.depthTexture=null,this.inputBuffer.depthTexture=null,this.inputBuffer.dispose();for(const n of this.passes)n.setDepthTexture(null)}}createBuffer(n,e,t,i){const a=this.renderer,r=a===null?new de:a.getDrawingBufferSize(new de),s={minFilter:Ht,magFilter:Ht,stencilBuffer:e,depthBuffer:n,type:t},o=new xi(r.width,r.height,s);return i>0&&(o.samples=i),t===zi&&a!==null&&a.outputColorSpace===En&&(o.texture.colorSpace=En),o.texture.name="EffectComposer.Buffer",o.texture.generateMipmaps=!1,o}setMainScene(n){for(const e of this.passes)e.mainScene=n}setMainCamera(n){for(const e of this.passes)e.mainCamera=n}addPass(n,e){const t=this.passes,i=this.renderer,a=i.getDrawingBufferSize(new de),r=i.getContext().getContextAttributes().alpha,s=this.inputBuffer.texture.type;if(n.setRenderer(i),n.setSize(a.width,a.height),n.initialize(i,r,s),this.autoRenderToScreen&&(t.length>0&&(t[t.length-1].renderToScreen=!1),n.renderToScreen&&(this.autoRenderToScreen=!1)),e!==void 0?t.splice(e,0,n):t.push(n),this.autoRenderToScreen&&(t[t.length-1].renderToScreen=!0),n.needsDepthTexture||this.depthTexture!==null)if(this.depthTexture===null){const o=this.createDepthTexture();for(n of t)n.setDepthTexture(o)}else n.setDepthTexture(this.depthTexture)}removePass(n){const e=this.passes,t=e.indexOf(n);if(t!==-1&&e.splice(t,1).length>0){if(this.depthTexture!==null){const r=(o,c)=>o||c.needsDepthTexture;e.reduce(r,!1)||(n.getDepthTexture()===this.depthTexture&&n.setDepthTexture(null),this.deleteDepthTexture())}this.autoRenderToScreen&&t===e.length&&(n.renderToScreen=!1,e.length>0&&(e[e.length-1].renderToScreen=!0))}}removeAllPasses(){const n=this.passes;this.deleteDepthTexture(),n.length>0&&(this.autoRenderToScreen&&(n[n.length-1].renderToScreen=!1),this.passes=[])}render(n){const e=this.renderer,t=this.copyPass;let i=this.inputBuffer,a=this.outputBuffer,r=!1,s,o,c;n===void 0&&(this.timer.update(),n=this.timer.getDelta());for(const h of this.passes)h.enabled&&(h.render(e,i,a,n,r),h.needsSwap&&(r&&(t.renderToScreen=h.renderToScreen,s=e.getContext(),o=e.state.buffers.stencil,o.setFunc(s.NOTEQUAL,1,4294967295),t.render(e,i,a,n,r),o.setFunc(s.EQUAL,1,4294967295)),c=i,i=a,a=c),h instanceof o$?r=!0:h instanceof a$&&(r=!1))}setSize(n,e,t){const i=this.renderer,a=i.getSize(new de);(n===void 0||e===void 0)&&(n=a.width,e=a.height),(a.width!==n||a.height!==e)&&i.setSize(n,e,t);const r=i.getDrawingBufferSize(new de);this.inputBuffer.setSize(r.width,r.height),this.outputBuffer.setSize(r.width,r.height);for(const s of this.passes)s.setSize(r.width,r.height)}reset(){this.dispose(),this.autoRenderToScreen=!0}dispose(){for(const n of this.passes)n.dispose();this.passes=[],this.inputBuffer!==null&&this.inputBuffer.dispose(),this.outputBuffer!==null&&this.outputBuffer.dispose(),this.deleteDepthTexture(),this.copyPass.dispose(),this.timer.dispose(),za.fullscreenGeometry.dispose()}},$o={NONE:0,DEPTH:1,CONVOLUTION:2},_n={FRAGMENT_HEAD:"FRAGMENT_HEAD",FRAGMENT_MAIN_UV:"FRAGMENT_MAIN_UV",FRAGMENT_MAIN_IMAGE:"FRAGMENT_MAIN_IMAGE",VERTEX_HEAD:"VERTEX_HEAD",VERTEX_MAIN_SUPPORT:"VERTEX_MAIN_SUPPORT"},c$=class{constructor(){this.shaderParts=new Map([[_n.FRAGMENT_HEAD,null],[_n.FRAGMENT_MAIN_UV,null],[_n.FRAGMENT_MAIN_IMAGE,null],[_n.VERTEX_HEAD,null],[_n.VERTEX_MAIN_SUPPORT,null]]),this.defines=new Map,this.uniforms=new Map,this.blendModes=new Map,this.extensions=new Set,this.attributes=$o.NONE,this.varyings=new Set,this.uvTransformation=!1,this.readDepth=!1,this.colorSpace=Wn}},X2=!1,ZD=class{constructor(n=null){this.originalMaterials=new Map,this.material=null,this.materials=null,this.materialsBackSide=null,this.materialsDoubleSide=null,this.materialsFlatShaded=null,this.materialsFlatShadedBackSide=null,this.materialsFlatShadedDoubleSide=null,this.setMaterial(n),this.meshCount=0,this.replaceMaterial=e=>{if(e.isMesh){let t;if(e.material.flatShading)switch(e.material.side){case ca:t=this.materialsFlatShadedDoubleSide;break;case Ui:t=this.materialsFlatShadedBackSide;break;default:t=this.materialsFlatShaded;break}else switch(e.material.side){case ca:t=this.materialsDoubleSide;break;case Ui:t=this.materialsBackSide;break;default:t=this.materials;break}this.originalMaterials.set(e,e.material),e.isSkinnedMesh?e.material=t[2]:e.isInstancedMesh?e.material=t[1]:e.material=t[0],++this.meshCount}}}cloneMaterial(n){if(!(n instanceof Vi))return n.clone();const e=n.uniforms,t=new Map;for(const a in e){const r=e[a].value;r.isRenderTargetTexture&&(e[a].value=null,t.set(a,r))}const i=n.clone();for(const a of t)e[a[0]].value=a[1],i.uniforms[a[0]].value=a[1];return i}setMaterial(n){if(this.disposeMaterials(),this.material=n,n!==null){const e=this.materials=[this.cloneMaterial(n),this.cloneMaterial(n),this.cloneMaterial(n)];for(const t of e)t.uniforms=Object.assign({},n.uniforms),t.side=Ns;e[2].skinning=!0,this.materialsBackSide=e.map(t=>{const i=this.cloneMaterial(t);return i.uniforms=Object.assign({},n.uniforms),i.side=Ui,i}),this.materialsDoubleSide=e.map(t=>{const i=this.cloneMaterial(t);return i.uniforms=Object.assign({},n.uniforms),i.side=ca,i}),this.materialsFlatShaded=e.map(t=>{const i=this.cloneMaterial(t);return i.uniforms=Object.assign({},n.uniforms),i.flatShading=!0,i}),this.materialsFlatShadedBackSide=e.map(t=>{const i=this.cloneMaterial(t);return i.uniforms=Object.assign({},n.uniforms),i.flatShading=!0,i.side=Ui,i}),this.materialsFlatShadedDoubleSide=e.map(t=>{const i=this.cloneMaterial(t);return i.uniforms=Object.assign({},n.uniforms),i.flatShading=!0,i.side=ca,i})}}render(n,e,t){const i=n.shadowMap.enabled;if(n.shadowMap.enabled=!1,X2){const a=this.originalMaterials;this.meshCount=0,e.traverse(this.replaceMaterial),n.render(e,t);for(const r of a)r[0].material=r[1];this.meshCount!==a.size&&a.clear()}else{const a=e.overrideMaterial;e.overrideMaterial=this.material,n.render(e,t),e.overrideMaterial=a}n.shadowMap.enabled=i}disposeMaterials(){if(this.material!==null){const n=this.materials.concat(this.materialsBackSide).concat(this.materialsDoubleSide).concat(this.materialsFlatShaded).concat(this.materialsFlatShadedBackSide).concat(this.materialsFlatShadedDoubleSide);for(const e of n)e.dispose()}}dispose(){this.originalMaterials.clear(),this.disposeMaterials()}static get workaroundEnabled(){return X2}static set workaroundEnabled(n){X2=n}},Pl=-1,rs=class extends nr{constructor(n,e=Pl,t=Pl,i=1){super(),this.resizable=n,this.baseSize=new de(1,1),this.preferredSize=new de(e,t),this.target=this.preferredSize,this.s=i,this.effectiveSize=new de,this.addEventListener("change",()=>this.updateEffectiveSize()),this.updateEffectiveSize()}updateEffectiveSize(){const n=this.baseSize,e=this.preferredSize,t=this.effectiveSize,i=this.scale;e.width!==Pl?t.width=e.width:e.height!==Pl?t.width=Math.round(e.height*(n.width/Math.max(n.height,1))):t.width=Math.round(n.width*i),e.height!==Pl?t.height=e.height:e.width!==Pl?t.height=Math.round(e.width/Math.max(n.width/Math.max(n.height,1),1)):t.height=Math.round(n.height*i)}get width(){return this.effectiveSize.width}set width(n){this.preferredWidth=n}get height(){return this.effectiveSize.height}set height(n){this.preferredHeight=n}getWidth(){return this.width}getHeight(){return this.height}get scale(){return this.s}set scale(n){this.s!==n&&(this.s=n,this.preferredSize.setScalar(Pl),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getScale(){return this.scale}setScale(n){this.scale=n}get baseWidth(){return this.baseSize.width}set baseWidth(n){this.baseSize.width!==n&&(this.baseSize.width=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseWidth(){return this.baseWidth}setBaseWidth(n){this.baseWidth=n}get baseHeight(){return this.baseSize.height}set baseHeight(n){this.baseSize.height!==n&&(this.baseSize.height=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseHeight(){return this.baseHeight}setBaseHeight(n){this.baseHeight=n}setBaseSize(n,e){(this.baseSize.width!==n||this.baseSize.height!==e)&&(this.baseSize.set(n,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}get preferredWidth(){return this.preferredSize.width}set preferredWidth(n){this.preferredSize.width!==n&&(this.preferredSize.width=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredWidth(){return this.preferredWidth}setPreferredWidth(n){this.preferredWidth=n}get preferredHeight(){return this.preferredSize.height}set preferredHeight(n){this.preferredSize.height!==n&&(this.preferredSize.height=n,this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredHeight(){return this.preferredHeight}setPreferredHeight(n){this.preferredHeight=n}setPreferredSize(n,e){(this.preferredSize.width!==n||this.preferredSize.height!==e)&&(this.preferredSize.set(n,e),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}copy(n){this.s=n.scale,this.baseSize.set(n.baseWidth,n.baseHeight),this.preferredSize.set(n.preferredWidth,n.preferredHeight),this.dispatchEvent({type:"change"}),this.resizable.setSize(this.baseSize.width,this.baseSize.height)}static get AUTO_SIZE(){return Pl}},ln={ADD:0,AVERAGE:2,COLOR:3,COLOR_BURN:4,COLOR_DODGE:5,DARKEN:6,DIFFERENCE:7,DIVIDE:8,DST:9,EXCLUSION:10,HARD_LIGHT:11,HARD_MIX:12,HUE:13,INVERT:14,INVERT_RGB:15,LIGHTEN:16,LINEAR_BURN:17,LINEAR_DODGE:18,LINEAR_LIGHT:19,LUMINOSITY:20,MULTIPLY:21,NEGATION:22,NORMAL:23,OVERLAY:24,PIN_LIGHT:25,REFLECT:26,SATURATION:27,SCREEN:28,SOFT_LIGHT:29,SRC:30,SUBTRACT:31,VIVID_LIGHT:32},u$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(x.rgb+y.rgb,y.a),y.a*opacity);}",h$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4((x.rgb+y.rgb)*0.5,y.a),y.a*opacity);}",f$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.xy,xHSL.z));return mix(x,vec4(z,y.a),y.a*opacity);}",d$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 a=x.rgb,b=y.rgb;vec3 z=mix(step(0.0,b)*(1.0-min(vec3(1.0),(1.0-a)/b)),vec3(1.0),step(1.0,a));return mix(x,vec4(z,y.a),y.a*opacity);}",p$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 a=x.rgb,b=y.rgb;vec3 z=step(0.0,a)*mix(min(vec3(1.0),a/max(1.0-b,1e-9)),vec3(1.0),step(1.0,b));return mix(x,vec4(z,y.a),y.a*opacity);}",m$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(min(x.rgb,y.rgb),y.a),y.a*opacity);}",g$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(abs(x.rgb-y.rgb),y.a),y.a*opacity);}",v$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(x.rgb/max(y.rgb,1e-12),y.a),y.a*opacity);}",_$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4((x.rgb+y.rgb-2.0*x.rgb*y.rgb),y.a),y.a*opacity);}",x$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 a=min(x.rgb,1.0);vec3 b=min(y.rgb,1.0);vec3 z=mix(2.0*a*b,1.0-2.0*(1.0-a)*(1.0-b),step(0.5,b));return mix(x,vec4(z,y.a),y.a*opacity);}",y$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(step(1.0,x.rgb+y.rgb),y.a),y.a*opacity);}",S$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(yHSL.x,xHSL.yz));return mix(x,vec4(z,y.a),y.a*opacity);}",T$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(1.0-y.rgb,y.a),y.a*opacity);}",E$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(y.rgb*(1.0-x.rgb),y.a),y.a*opacity);}",M$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(max(x.rgb,y.rgb),y.a),y.a*opacity);}",b$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(clamp(y.rgb+x.rgb-1.0,0.0,1.0),y.a),y.a*opacity);}",A$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(min(x.rgb+y.rgb,1.0),y.a),y.a*opacity);}",w$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(clamp(2.0*y.rgb+x.rgb-1.0,0.0,1.0),y.a),y.a*opacity);}",R$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.xy,yHSL.z));return mix(x,vec4(z,y.a),y.a*opacity);}",C$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(x.rgb*y.rgb,y.a),y.a*opacity);}",N$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(1.0-abs(1.0-x.rgb-y.rgb),y.a),y.a*opacity);}",D$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,y,y.a*opacity);}",O$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 z=mix(2.0*y.rgb*x.rgb,1.0-2.0*(1.0-y.rgb)*(1.0-x.rgb),step(0.5,x.rgb));return mix(x,vec4(z,y.a),y.a*opacity);}",L$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 y2=2.0*y.rgb;vec3 z=mix(mix(y2,x.rgb,step(0.5*x.rgb,y.rgb)),max(y2-1.0,vec3(0.0)),step(x.rgb,y2-1.0));return mix(x,vec4(z,y.a),y.a*opacity);}",I$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 z=mix(min(x.rgb*x.rgb/max(1.0-y.rgb,1e-12),1.0),y.rgb,step(1.0,y.rgb));return mix(x,vec4(z,y.a),y.a*opacity);}",U$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 xHSL=RGBToHSL(x.rgb);vec3 yHSL=RGBToHSL(y.rgb);vec3 z=HSLToRGB(vec3(xHSL.x,yHSL.y,xHSL.z));return mix(x,vec4(z,y.a),y.a*opacity);}",P$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(x.rgb+y.rgb-min(x.rgb*y.rgb,1.0),y.a),y.a*opacity);}",z$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 a=x.rgb;vec3 b=y.rgb;vec3 y2=2.0*b;vec3 w=step(0.5,b);vec3 c=a-(1.0-y2)*a*(1.0-a);vec3 d=mix(a+(y2-1.0)*(sqrt(a)-a),a+(y2-1.0)*a*((16.0*a-12.0)*a+3.0),w*(1.0-step(0.25,a)));vec3 z=mix(c,d,w);return mix(x,vec4(z,y.a),y.a*opacity);}",B$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return y;}",H$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){return mix(x,vec4(max(x.rgb+y.rgb-1.0,0.0),y.a),y.a*opacity);}",F$="vec4 blend(const in vec4 x,const in vec4 y,const in float opacity){vec3 z=mix(max(1.0-min((1.0-x.rgb)/(2.0*y.rgb),1.0),0.0),min(x.rgb/(2.0*(1.0-y.rgb)),1.0),step(0.5,y.rgb));return mix(x,vec4(z,y.a),y.a*opacity);}",G$=new Map([[ln.ADD,u$],[ln.AVERAGE,h$],[ln.COLOR,f$],[ln.COLOR_BURN,d$],[ln.COLOR_DODGE,p$],[ln.DARKEN,m$],[ln.DIFFERENCE,g$],[ln.DIVIDE,v$],[ln.DST,null],[ln.EXCLUSION,_$],[ln.HARD_LIGHT,x$],[ln.HARD_MIX,y$],[ln.HUE,S$],[ln.INVERT,T$],[ln.INVERT_RGB,E$],[ln.LIGHTEN,M$],[ln.LINEAR_BURN,b$],[ln.LINEAR_DODGE,A$],[ln.LINEAR_LIGHT,w$],[ln.LUMINOSITY,R$],[ln.MULTIPLY,C$],[ln.NEGATION,N$],[ln.NORMAL,D$],[ln.OVERLAY,O$],[ln.PIN_LIGHT,L$],[ln.REFLECT,I$],[ln.SATURATION,U$],[ln.SCREEN,P$],[ln.SOFT_LIGHT,z$],[ln.SRC,B$],[ln.SUBTRACT,H$],[ln.VIVID_LIGHT,F$]]),V$=class extends nr{constructor(n,e=1){super(),this._blendFunction=n,this.opacity=new J(e)}getOpacity(){return this.opacity.value}setOpacity(n){this.opacity.value=n}get blendFunction(){return this._blendFunction}set blendFunction(n){this._blendFunction=n,this.dispatchEvent({type:"change"})}getBlendFunction(){return this.blendFunction}setBlendFunction(n){this.blendFunction=n}getShaderCode(){return G$.get(this.blendFunction)}},v0=class extends nr{constructor(n,e,{attributes:t=$o.NONE,blendFunction:i=ln.NORMAL,defines:a=new Map,uniforms:r=new Map,extensions:s=null,vertexShader:o=null}={}){super(),this.name=n,this.renderer=null,this.attributes=t,this.fragmentShader=e,this.vertexShader=o,this.defines=a,this.uniforms=r,this.extensions=s,this.blendMode=new V$(i),this.blendMode.addEventListener("change",c=>this.setChanged()),this._inputColorSpace=Wn,this._outputColorSpace=Da}get inputColorSpace(){return this._inputColorSpace}set inputColorSpace(n){this._inputColorSpace=n,this.setChanged()}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(n){this._outputColorSpace=n,this.setChanged()}set mainScene(n){}set mainCamera(n){}getName(){return this.name}setRenderer(n){this.renderer=n}getDefines(){return this.defines}getUniforms(){return this.uniforms}getExtensions(){return this.extensions}getBlendMode(){return this.blendMode}getAttributes(){return this.attributes}setAttributes(n){this.attributes=n,this.setChanged()}getFragmentShader(){return this.fragmentShader}setFragmentShader(n){this.fragmentShader=n,this.setChanged()}getVertexShader(){return this.vertexShader}setVertexShader(n){this.vertexShader=n,this.setChanged()}setChanged(){this.dispatchEvent({type:"change"})}setDepthTexture(n,e=Mc){}update(n,e,t){}setSize(n,e){}initialize(n,e,t){}dispose(){for(const n of Object.keys(this)){const e=this[n];(e instanceof xi||e instanceof qn||e instanceof Nn||e instanceof za)&&this[n].dispose()}}},k$=`#include -#ifdef FRAMEBUFFER_PRECISION_HIGH -uniform mediump sampler2D inputBuffer; -#else -uniform lowp sampler2D inputBuffer; -#endif -#ifdef RANGE -uniform vec2 range; -#elif defined(THRESHOLD) -uniform float threshold;uniform float smoothing; -#endif -varying vec2 vUv;void main(){vec4 texel=texture2D(inputBuffer,vUv);float l=luminance(texel.rgb);float mask=1.0; -#ifdef RANGE -float low=step(range.x,l);float high=step(l,range.y);mask=low*high; -#elif defined(THRESHOLD) -mask=smoothstep(threshold,threshold+smoothing,l); -#endif -#ifdef COLOR -gl_FragColor=texel*mask; -#else -gl_FragColor=vec4(l*mask); -#endif -}`,W$=class extends Vi{constructor(n=!1,e=null){super({name:"LuminanceMaterial",defines:{THREE_REVISION:Cs.replace(/\D+/g,"")},uniforms:{inputBuffer:new J(null),threshold:new J(0),smoothing:new J(1),range:new J(null)},blending:Ta,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:k$,vertexShader:sA}),this.colorOutput=n,this.luminanceRange=e}set inputBuffer(n){this.uniforms.inputBuffer.value=n}setInputBuffer(n){this.uniforms.inputBuffer.value=n}get threshold(){return this.uniforms.threshold.value}set threshold(n){this.smoothing>0||n>0?this.defines.THRESHOLD="1":delete this.defines.THRESHOLD,this.uniforms.threshold.value=n}getThreshold(){return this.threshold}setThreshold(n){this.threshold=n}get smoothing(){return this.uniforms.smoothing.value}set smoothing(n){this.threshold>0||n>0?this.defines.THRESHOLD="1":delete this.defines.THRESHOLD,this.uniforms.smoothing.value=n}getSmoothingFactor(){return this.smoothing}setSmoothingFactor(n){this.smoothing=n}get useThreshold(){return this.threshold>0||this.smoothing>0}set useThreshold(n){}get colorOutput(){return this.defines.COLOR!==void 0}set colorOutput(n){n?this.defines.COLOR="1":delete this.defines.COLOR,this.needsUpdate=!0}isColorOutputEnabled(n){return this.colorOutput}setColorOutputEnabled(n){this.colorOutput=n}get useRange(){return this.luminanceRange!==null}set useRange(n){this.luminanceRange=null}get luminanceRange(){return this.uniforms.range.value}set luminanceRange(n){n!==null?this.defines.RANGE="1":delete this.defines.RANGE,this.uniforms.range.value=n,this.needsUpdate=!0}getLuminanceRange(){return this.luminanceRange}setLuminanceRange(n){this.luminanceRange=n}},X$=class extends za{constructor({renderTarget:n,luminanceRange:e,colorOutput:t,resolutionScale:i=1,width:a=rs.AUTO_SIZE,height:r=rs.AUTO_SIZE,resolutionX:s=a,resolutionY:o=r}={}){super("LuminancePass"),this.fullscreenMaterial=new W$(t,e),this.needsSwap=!1,this.renderTarget=n,this.renderTarget===void 0&&(this.renderTarget=new xi(1,1,{depthBuffer:!1}),this.renderTarget.texture.name="LuminancePass.Target");const c=this.resolution=new rs(this,s,o,i);c.addEventListener("change",h=>this.setSize(c.baseWidth,c.baseHeight))}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}render(n,e,t,i,a){const r=this.fullscreenMaterial;r.inputBuffer=e.texture,n.setRenderTarget(this.renderToScreen?null:this.renderTarget),n.render(this.scene,this.camera)}setSize(n,e){const t=this.resolution;t.setBaseSize(n,e),this.renderTarget.setSize(t.width,t.height)}initialize(n,e,t){t!==void 0&&t!==zi&&(this.renderTarget.texture.type=t,this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1")}},IE=class extends za{constructor(n,e="inputBuffer"){super("ShaderPass"),this.fullscreenMaterial=n,this.input=e}setInput(n){this.input=n}render(n,e,t,i,a){const r=this.fullscreenMaterial.uniforms;e!==null&&r!==void 0&&r[this.input]!==void 0&&(r[this.input].value=e.texture),n.setRenderTarget(this.renderToScreen?null:t),n.render(this.scene,this.camera)}initialize(n,e,t){t!==void 0&&t!==zi&&(this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1")}},oA=class extends za{constructor(n,e,t=null){super("RenderPass",n,e),this.needsSwap=!1,this.clearPass=new Y8,this.overrideMaterialManager=t===null?null:new ZD(t),this.ignoreBackground=!1,this.skipShadowMapUpdate=!1,this.selection=null}set mainScene(n){this.scene=n}set mainCamera(n){this.camera=n}get renderToScreen(){return super.renderToScreen}set renderToScreen(n){super.renderToScreen=n,this.clearPass.renderToScreen=n}get overrideMaterial(){const n=this.overrideMaterialManager;return n!==null?n.material:null}set overrideMaterial(n){const e=this.overrideMaterialManager;n!==null?e!==null?e.setMaterial(n):this.overrideMaterialManager=new ZD(n):e!==null&&(e.dispose(),this.overrideMaterialManager=null)}getOverrideMaterial(){return this.overrideMaterial}setOverrideMaterial(n){this.overrideMaterial=n}get clear(){return this.clearPass.enabled}set clear(n){this.clearPass.enabled=n}getSelection(){return this.selection}setSelection(n){this.selection=n}isBackgroundDisabled(){return this.ignoreBackground}setBackgroundDisabled(n){this.ignoreBackground=n}isShadowMapDisabled(){return this.skipShadowMapUpdate}setShadowMapDisabled(n){this.skipShadowMapUpdate=n}getClearPass(){return this.clearPass}render(n,e,t,i,a){const r=this.scene,s=this.camera,o=this.selection,c=s.layers.mask,h=r.background,f=n.shadowMap.autoUpdate,d=this.renderToScreen?null:e;o!==null&&s.layers.set(o.getLayer()),this.skipShadowMapUpdate&&(n.shadowMap.autoUpdate=!1),(this.ignoreBackground||this.clearPass.overrideClearColor!==null)&&(r.background=null),this.clearPass.enabled&&this.clearPass.render(n,e),n.setRenderTarget(d),this.overrideMaterialManager!==null?this.overrideMaterialManager.render(n,r,s):n.render(r,s),s.layers.mask=c,r.background=h,n.shadowMap.autoUpdate=f}},qa={LINEAR:0,REINHARD:1,REINHARD2:2,REINHARD2_ADAPTIVE:3,OPTIMIZED_CINEON:5,CINEON:5,ACES_FILMIC:6,AGX:7,NEUTRAL:8},Y$=`#include -#ifdef GL_FRAGMENT_PRECISION_HIGH -uniform highp sampler2D depthBuffer; -#else -uniform mediump sampler2D depthBuffer; -#endif -#ifdef DOWNSAMPLE_NORMALS -uniform lowp sampler2D normalBuffer; -#endif -varying vec2 vUv0;varying vec2 vUv1;varying vec2 vUv2;varying vec2 vUv3;float readDepth(const in vec2 uv){ -#if DEPTH_PACKING == 3201 -return unpackRGBAToDepth(texture2D(depthBuffer,uv)); -#else -return texture2D(depthBuffer,uv).r; -#endif -}int findBestDepth(const in float samples[4]){float c=(samples[0]+samples[1]+samples[2]+samples[3])*0.25;float distances[4];distances[0]=abs(c-samples[0]);distances[1]=abs(c-samples[1]);distances[2]=abs(c-samples[2]);distances[3]=abs(c-samples[3]);float maxDistance=max(max(distances[0],distances[1]),max(distances[2],distances[3]));int remaining[3];int rejected[3];int i,j,k;for(i=0,j=0,k=0;i<4;++i){if(distances[i]this.setSize(o.baseWidth,o.baseHeight))}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}setDepthTexture(n,e=Mc){this.fullscreenMaterial.depthBuffer=n,this.fullscreenMaterial.depthPacking=e}render(n,e,t,i,a){n.setRenderTarget(this.renderToScreen?null:this.renderTarget),n.render(this.scene,this.camera)}setSize(n,e){const t=this.resolution;t.setBaseSize(n,e),this.renderTarget.setSize(t.width,t.height),this.fullscreenMaterial.setSize(n,e)}initialize(n,e,t){const i=n.getContext();if(!(i.getExtension("EXT_color_buffer_float")||i.getExtension("EXT_color_buffer_half_float")))throw new Error("Rendering to float texture is not supported.")}},K$=`#include -#define packFloatToRGBA(v) packDepthToRGBA(v) -#define unpackRGBAToFloat(v) unpackRGBAToDepth(v) -uniform lowp sampler2D luminanceBuffer0;uniform lowp sampler2D luminanceBuffer1;uniform float minLuminance;uniform float deltaTime;uniform float tau;varying vec2 vUv;void main(){float l0=unpackRGBAToFloat(texture2D(luminanceBuffer0,vUv)); -#if __VERSION__ < 300 -float l1=texture2DLodEXT(luminanceBuffer1,vUv,MIP_LEVEL_1X1).r; -#else -float l1=textureLod(luminanceBuffer1,vUv,MIP_LEVEL_1X1).r; -#endif -l0=max(minLuminance,l0);l1=max(minLuminance,l1);float adaptedLum=l0+(l1-l0)*(1.0-exp(-deltaTime*tau));gl_FragColor=(adaptedLum==1.0)?vec4(1.0):packFloatToRGBA(adaptedLum);}`,Q$=class extends Vi{constructor(){super({name:"AdaptiveLuminanceMaterial",defines:{MIP_LEVEL_1X1:"0.0"},uniforms:{luminanceBuffer0:new J(null),luminanceBuffer1:new J(null),minLuminance:new J(.01),deltaTime:new J(0),tau:new J(1)},extensions:{shaderTextureLOD:!0},blending:Ta,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:K$,vertexShader:sA})}set luminanceBuffer0(n){this.uniforms.luminanceBuffer0.value=n}setLuminanceBuffer0(n){this.uniforms.luminanceBuffer0.value=n}set luminanceBuffer1(n){this.uniforms.luminanceBuffer1.value=n}setLuminanceBuffer1(n){this.uniforms.luminanceBuffer1.value=n}set mipLevel1x1(n){this.defines.MIP_LEVEL_1X1=n.toFixed(1),this.needsUpdate=!0}setMipLevel1x1(n){this.mipLevel1x1=n}set deltaTime(n){this.uniforms.deltaTime.value=n}setDeltaTime(n){this.uniforms.deltaTime.value=n}get minLuminance(){return this.uniforms.minLuminance.value}set minLuminance(n){this.uniforms.minLuminance.value=n}getMinLuminance(){return this.uniforms.minLuminance.value}setMinLuminance(n){this.uniforms.minLuminance.value=n}get adaptationRate(){return this.uniforms.tau.value}set adaptationRate(n){this.uniforms.tau.value=n}getAdaptationRate(){return this.uniforms.tau.value}setAdaptationRate(n){this.uniforms.tau.value=n}},J$=class extends za{constructor(n,{minLuminance:e=.01,adaptationRate:t=1}={}){super("AdaptiveLuminancePass"),this.fullscreenMaterial=new Q$,this.needsSwap=!1,this.renderTargetPrevious=new xi(1,1,{minFilter:Fn,magFilter:Fn,depthBuffer:!1}),this.renderTargetPrevious.texture.name="Luminance.Previous";const i=this.fullscreenMaterial;i.luminanceBuffer0=this.renderTargetPrevious.texture,i.luminanceBuffer1=n,i.minLuminance=e,i.adaptationRate=t,this.renderTargetAdapted=this.renderTargetPrevious.clone(),this.renderTargetAdapted.texture.name="Luminance.Adapted",this.copyPass=new X8(this.renderTargetPrevious,!1)}get texture(){return this.renderTargetAdapted.texture}getTexture(){return this.renderTargetAdapted.texture}set mipLevel1x1(n){this.fullscreenMaterial.mipLevel1x1=n}get adaptationRate(){return this.fullscreenMaterial.adaptationRate}set adaptationRate(n){this.fullscreenMaterial.adaptationRate=n}render(n,e,t,i,a){this.fullscreenMaterial.deltaTime=i,n.setRenderTarget(this.renderToScreen?null:this.renderTargetAdapted),n.render(this.scene,this.camera),this.copyPass.render(n,this.renderTargetAdapted)}},$$=`#include -uniform float whitePoint; -#if TONE_MAPPING_MODE == 2 || TONE_MAPPING_MODE == 3 -uniform float middleGrey; -#if TONE_MAPPING_MODE == 3 -uniform lowp sampler2D luminanceBuffer; -#else -uniform float averageLuminance; -#endif -vec3 Reinhard2ToneMapping(vec3 color){color*=toneMappingExposure;float l=luminance(color); -#if TONE_MAPPING_MODE == 3 -float lumAvg=unpackRGBAToFloat(texture2D(luminanceBuffer,vec2(0.5))); -#else -float lumAvg=averageLuminance; -#endif -float lumScaled=(l*middleGrey)/max(lumAvg,1e-6);float lumCompressed=lumScaled*(1.0+lumScaled/(whitePoint*whitePoint));lumCompressed/=(1.0+lumScaled);return clamp(lumCompressed*color,0.0,1.0);} -#elif TONE_MAPPING_MODE == 4 -#define A 0.15 -#define B 0.50 -#define C 0.10 -#define D 0.20 -#define E 0.02 -#define F 0.30 -vec3 Uncharted2Helper(const in vec3 x){return((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}vec3 Uncharted2ToneMapping(vec3 color){color*=toneMappingExposure;return clamp(Uncharted2Helper(color)/Uncharted2Helper(vec3(whitePoint)),0.0,1.0);} -#endif -void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor){ -#if TONE_MAPPING_MODE == 2 || TONE_MAPPING_MODE == 3 -outputColor=vec4(Reinhard2ToneMapping(inputColor.rgb),inputColor.a); -#elif TONE_MAPPING_MODE == 4 -outputColor=vec4(Uncharted2ToneMapping(inputColor.rgb),inputColor.a); -#else -outputColor=vec4(toneMapping(inputColor.rgb),inputColor.a); -#endif -}`,eee=class extends v0{constructor({blendFunction:n=ln.SRC,adaptive:e=!1,mode:t=e?qa.REINHARD2_ADAPTIVE:qa.AGX,resolution:i=256,maxLuminance:a=4,whitePoint:r=a,middleGrey:s=.6,minLuminance:o=.01,averageLuminance:c=1,adaptationRate:h=1}={}){super("ToneMappingEffect",$$,{blendFunction:n,uniforms:new Map([["luminanceBuffer",new J(null)],["maxLuminance",new J(a)],["whitePoint",new J(r)],["middleGrey",new J(s)],["averageLuminance",new J(c)]])}),this.renderTargetLuminance=new xi(1,1,{minFilter:Mr,depthBuffer:!1}),this.renderTargetLuminance.texture.generateMipmaps=!0,this.renderTargetLuminance.texture.name="Luminance",this.luminancePass=new X$({renderTarget:this.renderTargetLuminance}),this.adaptiveLuminancePass=new J$(this.luminancePass.texture,{minLuminance:o,adaptationRate:h}),this.uniforms.get("luminanceBuffer").value=this.adaptiveLuminancePass.texture,this.resolution=i,this.mode=t}get mode(){return Number(this.defines.get("TONE_MAPPING_MODE"))}set mode(n){if(this.mode===n)return;const t=Cs.replace(/\D+/g,"")>=168?"CineonToneMapping(texel)":"OptimizedCineonToneMapping(texel)";switch(this.defines.clear(),this.defines.set("TONE_MAPPING_MODE",n.toFixed(0)),n){case qa.LINEAR:this.defines.set("toneMapping(texel)","LinearToneMapping(texel)");break;case qa.REINHARD:this.defines.set("toneMapping(texel)","ReinhardToneMapping(texel)");break;case qa.CINEON:case qa.OPTIMIZED_CINEON:this.defines.set("toneMapping(texel)",t);break;case qa.ACES_FILMIC:this.defines.set("toneMapping(texel)","ACESFilmicToneMapping(texel)");break;case qa.AGX:this.defines.set("toneMapping(texel)","AgXToneMapping(texel)");break;case qa.NEUTRAL:this.defines.set("toneMapping(texel)","NeutralToneMapping(texel)");break;default:this.defines.set("toneMapping(texel)","texel");break}this.adaptiveLuminancePass.enabled=n===qa.REINHARD2_ADAPTIVE,this.setChanged()}getMode(){return this.mode}setMode(n){this.mode=n}get whitePoint(){return this.uniforms.get("whitePoint").value}set whitePoint(n){this.uniforms.get("whitePoint").value=n}get middleGrey(){return this.uniforms.get("middleGrey").value}set middleGrey(n){this.uniforms.get("middleGrey").value=n}get averageLuminance(){return this.uniforms.get("averageLuminance").value}set averageLuminance(n){this.uniforms.get("averageLuminance").value=n}get adaptiveLuminanceMaterial(){return this.adaptiveLuminancePass.fullscreenMaterial}getAdaptiveLuminanceMaterial(){return this.adaptiveLuminanceMaterial}get resolution(){return this.luminancePass.resolution.width}set resolution(n){const e=Math.max(0,Math.ceil(Math.log2(n))),t=Math.pow(2,e);this.luminancePass.resolution.setPreferredSize(t,t),this.adaptiveLuminanceMaterial.mipLevel1x1=e}getResolution(){return this.resolution}setResolution(n){this.resolution=n}get adaptive(){return this.mode===qa.REINHARD2_ADAPTIVE}set adaptive(n){this.mode=n?qa.REINHARD2_ADAPTIVE:qa.REINHARD2}get adaptationRate(){return this.adaptiveLuminanceMaterial.adaptationRate}set adaptationRate(n){this.adaptiveLuminanceMaterial.adaptationRate=n}get distinction(){return console.warn(this.name,"distinction was removed."),1}set distinction(n){console.warn(this.name,"distinction was removed.")}update(n,e,t){this.adaptiveLuminancePass.enabled&&(this.luminancePass.render(n,e),this.adaptiveLuminancePass.render(n,null,null,t))}initialize(n,e,t){this.adaptiveLuminancePass.initialize(n,e,t)}},tee=`#include -#include -#include -#define packFloatToRGBA(v) packDepthToRGBA(v) -#define unpackRGBAToFloat(v) unpackRGBAToDepth(v) -#ifdef FRAMEBUFFER_PRECISION_HIGH -uniform mediump sampler2D inputBuffer; -#else -uniform lowp sampler2D inputBuffer; -#endif -#if DEPTH_PACKING == 3201 -uniform lowp sampler2D depthBuffer; -#elif defined(GL_FRAGMENT_PRECISION_HIGH) -uniform highp sampler2D depthBuffer; -#else -uniform mediump sampler2D depthBuffer; -#endif -uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;vec4 sRGBToLinear(const 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);}float readDepth(const in vec2 uv){ -#if DEPTH_PACKING == 3201 -float depth=unpackRGBAToDepth(texture2D(depthBuffer,uv)); -#else -float depth=texture2D(depthBuffer,uv).r; -#endif -#if defined(USE_LOGARITHMIC_DEPTH_BUFFER) || defined(LOG_DEPTH) -float d=pow(2.0,depth*log2(cameraFar+1.0))-1.0;float a=cameraFar/(cameraFar-cameraNear);float b=cameraFar*cameraNear/(cameraNear-cameraFar);depth=a+b/d; -#elif defined(USE_REVERSED_DEPTH_BUFFER) -depth=1.0-depth; -#endif -return depth;}float getViewZ(const in float depth){ -#ifdef PERSPECTIVE_CAMERA -return perspectiveDepthToViewZ(depth,cameraNear,cameraFar); -#else -return orthographicDepthToViewZ(depth,cameraNear,cameraFar); -#endif -}vec3 RGBToHCV(const in vec3 RGB){vec4 P=mix(vec4(RGB.bg,-1.0,2.0/3.0),vec4(RGB.gb,0.0,-1.0/3.0),step(RGB.b,RGB.g));vec4 Q=mix(vec4(P.xyw,RGB.r),vec4(RGB.r,P.yzx),step(P.x,RGB.r));float C=Q.x-min(Q.w,Q.y);float H=abs((Q.w-Q.y)/(6.0*C+EPSILON)+Q.z);return vec3(H,C,Q.x);}vec3 RGBToHSL(const in vec3 RGB){vec3 HCV=RGBToHCV(RGB);float L=HCV.z-HCV.y*0.5;float S=HCV.y/(1.0-abs(L*2.0-1.0)+EPSILON);return vec3(HCV.x,S,L);}vec3 HueToRGB(const in float H){float R=abs(H*6.0-3.0)-1.0;float G=2.0-abs(H*6.0-2.0);float B=2.0-abs(H*6.0-4.0);return clamp(vec3(R,G,B),0.0,1.0);}vec3 HSLToRGB(const in vec3 HSL){vec3 RGB=HueToRGB(HSL.x);float C=(1.0-abs(2.0*HSL.z-1.0))*HSL.y;return(RGB-0.5)*C+HSL.z;}FRAGMENT_HEAD void main(){FRAGMENT_MAIN_UV vec4 color0=texture2D(inputBuffer,UV);vec4 color1=vec4(0.0);FRAGMENT_MAIN_IMAGE color0.a=clamp(color0.a,0.0,1.0);gl_FragColor=color0; -#ifdef ENCODE_OUTPUT -#include -#endif -#include -}`,nee="uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;VERTEX_HEAD void main(){vUv=position.xy*0.5+0.5;VERTEX_MAIN_SUPPORT gl_Position=vec4(position.xy,1.0,1.0);}",iee=class extends Vi{constructor(n,e,t,i,a=!1){super({name:"EffectMaterial",defines:{THREE_REVISION:Cs.replace(/\D+/g,""),DEPTH_PACKING:"0",ENCODE_OUTPUT:"1"},uniforms:{inputBuffer:new J(null),depthBuffer:new J(null),resolution:new J(new de),texelSize:new J(new de),cameraNear:new J(.3),cameraFar:new J(1e3),aspect:new J(1),time:new J(0)},blending:Ta,toneMapped:!1,depthWrite:!1,depthTest:!1,dithering:a}),n&&this.setShaderParts(n),e&&this.setDefines(e),t&&this.setUniforms(t),this.copyCameraSettings(i)}set inputBuffer(n){this.uniforms.inputBuffer.value=n}setInputBuffer(n){this.uniforms.inputBuffer.value=n}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(n){this.uniforms.depthBuffer.value=n}get depthPacking(){return Number(this.defines.DEPTH_PACKING)}set depthPacking(n){this.defines.DEPTH_PACKING=n.toFixed(0),this.needsUpdate=!0}setDepthBuffer(n,e=Mc){this.depthBuffer=n,this.depthPacking=e}setShaderData(n){this.setShaderParts(n.shaderParts),this.setDefines(n.defines),this.setUniforms(n.uniforms),this.setExtensions(n.extensions)}setShaderParts(n){return this.fragmentShader=tee.replace(_n.FRAGMENT_HEAD,n.get(_n.FRAGMENT_HEAD)||"").replace(_n.FRAGMENT_MAIN_UV,n.get(_n.FRAGMENT_MAIN_UV)||"").replace(_n.FRAGMENT_MAIN_IMAGE,n.get(_n.FRAGMENT_MAIN_IMAGE)||""),this.vertexShader=nee.replace(_n.VERTEX_HEAD,n.get(_n.VERTEX_HEAD)||"").replace(_n.VERTEX_MAIN_SUPPORT,n.get(_n.VERTEX_MAIN_SUPPORT)||""),this.needsUpdate=!0,this}setDefines(n){for(const e of n.entries())this.defines[e[0]]=e[1];return this.needsUpdate=!0,this}setUniforms(n){for(const e of n.entries())this.uniforms[e[0]]=e[1];return this}setExtensions(n){this.extensions={};for(const e of n)this.extensions[e]=!0;return this}get encodeOutput(){return this.defines.ENCODE_OUTPUT!==void 0}set encodeOutput(n){this.encodeOutput!==n&&(n?this.defines.ENCODE_OUTPUT="1":delete this.defines.ENCODE_OUTPUT,this.needsUpdate=!0)}isOutputEncodingEnabled(n){return this.encodeOutput}setOutputEncodingEnabled(n){this.encodeOutput=n}get time(){return this.uniforms.time.value}set time(n){this.uniforms.time.value=n}setDeltaTime(n){this.uniforms.time.value+=n}adoptCameraSettings(n){this.copyCameraSettings(n)}copyCameraSettings(n){n&&(this.uniforms.cameraNear.value=n.near,this.uniforms.cameraFar.value=n.far,n instanceof hi?this.defines.PERSPECTIVE_CAMERA="1":delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0)}setSize(n,e){const t=this.uniforms;t.resolution.value.set(n,e),t.texelSize.value.set(1/n,1/e),t.aspect.value=n/e}static get Section(){return _n}};function KD(n,e,t){for(const i of e){const a="$1"+n+i.charAt(0).toUpperCase()+i.slice(1),r=new RegExp("([^\\.])(\\b"+i+"\\b)","g");for(const s of t.entries())s[1]!==null&&t.set(s[0],s[1].replace(r,a))}}function aee(n,e,t){let i=e.getFragmentShader(),a=e.getVertexShader();const r=i!==void 0&&/mainImage/.test(i),s=i!==void 0&&/mainUv/.test(i);if(t.attributes|=e.getAttributes(),i===void 0)throw new Error(`Missing fragment shader (${e.name})`);if(s&&t.attributes&$o.CONVOLUTION)throw new Error(`Effects that transform UVs are incompatible with convolution effects (${e.name})`);if(!r&&!s)throw new Error(`Could not find mainImage or mainUv function (${e.name})`);{const o=/\w+\s+(\w+)\([\w\s,]*\)\s*{/g,c=t.shaderParts;let h=c.get(_n.FRAGMENT_HEAD)||"",f=c.get(_n.FRAGMENT_MAIN_UV)||"",d=c.get(_n.FRAGMENT_MAIN_IMAGE)||"",m=c.get(_n.VERTEX_HEAD)||"",g=c.get(_n.VERTEX_MAIN_SUPPORT)||"";const x=new Set,T=new Set;if(s&&(f+=` ${n}MainUv(UV); -`,t.uvTransformation=!0),a!==null&&/mainSupport/.test(a)){const S=/mainSupport *\([\w\s]*?uv\s*?\)/.test(a);g+=` ${n}MainSupport(`,g+=S?`vUv); -`:`); -`;for(const E of a.matchAll(/(?:varying\s+\w+\s+([\S\s]*?);)/g))for(const b of E[1].split(/\s*,\s*/))t.varyings.add(b),x.add(b),T.add(b);for(const E of a.matchAll(o))T.add(E[1])}for(const S of i.matchAll(o))T.add(S[1]);for(const S of e.defines.keys())T.add(S.replace(/\([\w\s,]*\)/g,""));for(const S of e.uniforms.keys())T.add(S);T.delete("while"),T.delete("for"),T.delete("if"),e.uniforms.forEach((S,E)=>t.uniforms.set(n+E.charAt(0).toUpperCase()+E.slice(1),S)),e.defines.forEach((S,E)=>t.defines.set(n+E.charAt(0).toUpperCase()+E.slice(1),S));const y=new Map([["fragment",i],["vertex",a]]);KD(n,T,t.defines),KD(n,T,y),i=y.get("fragment"),a=y.get("vertex");const v=e.blendMode;if(t.blendModes.set(v.blendFunction,v),r){e.inputColorSpace!==null&&e.inputColorSpace!==t.colorSpace&&(d+=e.inputColorSpace===En?`color0 = sRGBTransferOETF(color0); - `:`color0 = sRGBToLinear(color0); - `),e.outputColorSpace!==Da?t.colorSpace=e.outputColorSpace:e.inputColorSpace!==null&&(t.colorSpace=e.inputColorSpace);const S=/MainImage *\([\w\s,]*?depth[\w\s,]*?\)/;d+=`${n}MainImage(color0, UV, `,t.attributes&$o.DEPTH&&S.test(i)&&(d+="depth, ",t.readDepth=!0),d+=`color1); - `;const E=n+"BlendOpacity";t.uniforms.set(E,v.opacity),d+=`color0 = blend${v.blendFunction}(color0, color1, ${E}); - - `,h+=`uniform float ${E}; - -`}if(h+=i+` -`,a!==null&&(m+=a+` -`),c.set(_n.FRAGMENT_HEAD,h),c.set(_n.FRAGMENT_MAIN_UV,f),c.set(_n.FRAGMENT_MAIN_IMAGE,d),c.set(_n.VERTEX_HEAD,m),c.set(_n.VERTEX_MAIN_SUPPORT,g),e.extensions!==null)for(const S of e.extensions)t.extensions.add(S)}}var ree=class extends za{constructor(n,...e){super("EffectPass"),this.fullscreenMaterial=new iee(null,null,null,n),this.listener=t=>this.handleEvent(t),this.effects=[],this.setEffects(e),this.skipRendering=!1,this.minTime=1,this.maxTime=Number.POSITIVE_INFINITY,this.timeScale=1}set mainScene(n){for(const e of this.effects)e.mainScene=n}set mainCamera(n){this.fullscreenMaterial.copyCameraSettings(n);for(const e of this.effects)e.mainCamera=n}get encodeOutput(){return this.fullscreenMaterial.encodeOutput}set encodeOutput(n){this.fullscreenMaterial.encodeOutput=n}get dithering(){return this.fullscreenMaterial.dithering}set dithering(n){const e=this.fullscreenMaterial;e.dithering=n,e.needsUpdate=!0}setEffects(n){for(const e of this.effects)e.removeEventListener("change",this.listener);this.effects=n.sort((e,t)=>t.attributes-e.attributes);for(const e of this.effects)e.addEventListener("change",this.listener)}updateMaterial(){const n=new c$;let e=0;for(const s of this.effects)if(s.blendMode.blendFunction===ln.DST)n.attributes|=s.getAttributes()&$o.DEPTH;else{if(n.attributes&s.getAttributes()&$o.CONVOLUTION)throw new Error(`Convolution effects cannot be merged (${s.name})`);aee("e"+e++,s,n)}let t=n.shaderParts.get(_n.FRAGMENT_HEAD),i=n.shaderParts.get(_n.FRAGMENT_MAIN_IMAGE),a=n.shaderParts.get(_n.FRAGMENT_MAIN_UV);const r=/\bblend\b/g;for(const s of n.blendModes.values())t+=s.getShaderCode().replace(r,`blend${s.blendFunction}`)+` -`;n.attributes&$o.DEPTH?(n.readDepth&&(i=`float depth = readDepth(UV); - - `+i),this.needsDepthTexture=this.getDepthTexture()===null):this.needsDepthTexture=!1,n.colorSpace===En&&(i+=`color0 = sRGBToLinear(color0); - `),n.uvTransformation?(a=`vec2 transformedUv = vUv; -`+a,n.defines.set("UV","transformedUv")):n.defines.set("UV","vUv"),n.shaderParts.set(_n.FRAGMENT_HEAD,t),n.shaderParts.set(_n.FRAGMENT_MAIN_IMAGE,i),n.shaderParts.set(_n.FRAGMENT_MAIN_UV,a);for(const[s,o]of n.shaderParts)o!==null&&n.shaderParts.set(s,o.trim().replace(/^#/,` -#`));this.skipRendering=e===0,this.needsSwap=!this.skipRendering,this.fullscreenMaterial.setShaderData(n)}recompile(){this.updateMaterial()}getDepthTexture(){return this.fullscreenMaterial.depthBuffer}setDepthTexture(n,e=Mc){this.fullscreenMaterial.depthBuffer=n,this.fullscreenMaterial.depthPacking=e;for(const t of this.effects)t.setDepthTexture(n,e)}render(n,e,t,i,a){for(const r of this.effects)r.update(n,e,i);if(!this.skipRendering||this.renderToScreen){const r=this.fullscreenMaterial;r.inputBuffer=e.texture,r.time+=i*this.timeScale,n.setRenderTarget(this.renderToScreen?null:t),n.render(this.scene,this.camera)}}setSize(n,e){this.fullscreenMaterial.setSize(n,e);for(const t of this.effects)t.setSize(n,e)}initialize(n,e,t){this.renderer=n;for(const i of this.effects)i.initialize(n,e,t);this.updateMaterial(),t!==void 0&&t!==zi&&(this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH="1")}dispose(){super.dispose();for(const n of this.effects)n.removeEventListener("change",this.listener),n.dispose()}handleEvent(n){switch(n.type){case"change":this.recompile();break}}},see=class extends za{constructor(n,e,{renderTarget:t,resolutionScale:i=1,width:a=rs.AUTO_SIZE,height:r=rs.AUTO_SIZE,resolutionX:s=a,resolutionY:o=r}={}){super("NormalPass"),this.needsSwap=!1,this.renderPass=new oA(n,e,new Pb);const c=this.renderPass;c.ignoreBackground=!0,c.skipShadowMapUpdate=!0;const h=c.getClearPass();h.overrideClearColor=new je(7829503),h.overrideClearAlpha=1,this.renderTarget=t,this.renderTarget===void 0&&(this.renderTarget=new xi(1,1,{minFilter:Fn,magFilter:Fn}),this.renderTarget.texture.name="NormalPass.Target");const f=this.resolution=new rs(this,s,o,i);f.addEventListener("change",d=>this.setSize(f.baseWidth,f.baseHeight))}set mainScene(n){this.renderPass.mainScene=n}set mainCamera(n){this.renderPass.mainCamera=n}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}getResolutionScale(){return this.resolution.scale}setResolutionScale(n){this.resolution.scale=n}render(n,e,t,i,a){const r=this.renderToScreen?null:this.renderTarget;this.renderPass.render(n,r,r)}setSize(n,e){const t=this.resolution;t.setBaseSize(n,e),this.renderTarget.setSize(t.width,t.height)}};function Fm(n,e,t){return e in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}new de;new de;function q8(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}var Xr=function n(e,t,i){var a=this;q8(this,n),Fm(this,"dot2",function(r,s){return a.x*r+a.y*s}),Fm(this,"dot3",function(r,s,o){return a.x*r+a.y*s+a.z*o}),this.x=e,this.y=t,this.z=i},oee=[new Xr(1,1,0),new Xr(-1,1,0),new Xr(1,-1,0),new Xr(-1,-1,0),new Xr(1,0,1),new Xr(-1,0,1),new Xr(1,0,-1),new Xr(-1,0,-1),new Xr(0,1,1),new Xr(0,-1,1),new Xr(0,1,-1),new Xr(0,-1,-1)],QD=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180],JD=new Array(512),$D=new Array(512),lee=function(e){e>0&&e<1&&(e*=65536),e=Math.floor(e),e<256&&(e|=e<<8);for(var t=0;t<256;t++){var i;t&1?i=QD[t]^e&255:i=QD[t]^e>>8&255,JD[t]=JD[t+256]=i,$D[t]=$D[t+256]=oee[i%12]}};lee(0);function cee(n){if(typeof n=="number")n=Math.abs(n);else if(typeof n=="string"){var e=n;n=0;for(var t=0;t(n.getAttributes()&2)===2,hee=Me.memo(Me.forwardRef(({children:n,camera:e,scene:t,resolutionScale:i,enabled:a=!0,renderPriority:r=1,autoClear:s=!0,depthBuffer:o,enableNormalPass:c,stencilBuffer:h,multisampling:f=8,frameBufferType:d=Xn},m)=>{const{gl:g,scene:x,camera:T,size:y}=Oi(),v=t||x,S=e||T,[E,b,D]=Me.useMemo(()=>{const P=new l$(g,{depthBuffer:o,stencilBuffer:h,multisampling:f,frameBufferType:d});P.addPass(new oA(v,S));let O=null,w=null;return c&&(w=new see(v,S),w.enabled=!1,P.addPass(w),i!==void 0&&(O=new Z$({normalBuffer:w.texture,resolutionScale:i}),O.enabled=!1,P.addPass(O))),[P,w,O]},[S,g,o,h,f,d,v,c,i]);Me.useEffect(()=>E==null?void 0:E.setSize(y.width,y.height),[E,y]),cl((P,O)=>{if(a){const w=g.autoClear;g.autoClear=s,h&&!s&&g.clearStencil(),E.render(O),g.autoClear=w}},a?r:0);const C=Me.useRef(null);Me.useLayoutEffect(()=>{var w;const P=[],O=C.current.__r3f;if(O&&E){const B=O.children;for(let j=0;j{for(const B of P)E==null||E.removePass(B);b&&(b.enabled=!1),D&&(D.enabled=!1)}},[E,n,S,b,D]),Me.useEffect(()=>{const P=g.toneMapping;return g.toneMapping=is,()=>{g.toneMapping=P}},[g]);const I=Me.useMemo(()=>({composer:E,normalPass:b,downSamplingPass:D,resolutionScale:i,camera:S,scene:v}),[E,b,D,i,S,v]);return Me.useImperativeHandle(m,()=>E,[E]),Rt.jsx(lA.Provider,{value:I,children:Rt.jsx("group",{ref:C,children:n})})}));let fee=0;const nO=new WeakMap,dee=(n,e)=>function({blendFunction:t=e==null?void 0:e.blendFunction,opacity:i=e==null?void 0:e.opacity,...a}){let r=nO.get(n);if(!r){const c=`@react-three/postprocessing/${n.name}-${fee++}`;u8({[c]:n}),nO.set(n,r=c)}const s=Oi(c=>c.camera),o=dM.useMemo(()=>[...(e==null?void 0:e.args)??[],...a.args??[{...e,...a}]],[JSON.stringify(a)]);return Rt.jsx(r,{camera:s,"blendMode-blendFunction":t,"blendMode-opacity-value":i,...a,args:o})},pee=dee(eee);var mee="Invariant failed";function Kx(n,e){if(!n)throw new Error(mee)}const gee=new L;function j8(n,e,t=new L,i){const{x:a,y:r,z:s}=n,o=e.x,c=e.y,h=e.z,f=a*a*o,d=r*r*c,m=s*s*h,g=f+d+m,x=Math.sqrt(1/g);if(!Number.isFinite(x))return;const T=gee.copy(n).multiplyScalar(x);if(g<((i==null?void 0:i.centerTolerance)??.1))return t.copy(T);const y=T.multiply(e).multiplyScalar(2);let v=(1-x)*n.length()/(y.length()/2),S=0,E,b,D,C;do{v-=S,E=1/(1+v*o),b=1/(1+v*c),D=1/(1+v*h);const I=E*E,P=b*b,O=D*D,w=I*E,B=P*b,j=O*D;C=f*I+d*P+m*O-1,S=C/((f*w*o+d*B*c+m*j*h)*-2)}while(Math.abs(C)>1e-12);return t.set(a*E,r*b,s*D)}const xf=new L,Y2=new L,q2=new L,UE=class{constructor(e,t,i){this.radii=new L(e,t,i)}get minimumRadius(){return Math.min(this.radii.x,this.radii.y,this.radii.z)}get maximumRadius(){return Math.max(this.radii.x,this.radii.y,this.radii.z)}get flattening(){return 1-this.minimumRadius/this.maximumRadius}get eccentricity(){return Math.sqrt(this.eccentricitySquared)}get eccentricitySquared(){const e=this.maximumRadius**2,t=this.minimumRadius**2;return(e-t)/e}reciprocalRadii(e=new L){const{x:t,y:i,z:a}=this.radii;return e.set(1/t,1/i,1/a)}reciprocalRadiiSquared(e=new L){const{x:t,y:i,z:a}=this.radii;return e.set(1/t**2,1/i**2,1/a**2)}projectOnSurface(e,t=new L,i){return j8(e,this.reciprocalRadiiSquared(),t,i)}getSurfaceNormal(e,t=new L){return t.multiplyVectors(this.reciprocalRadiiSquared(xf),e).normalize()}getEastNorthUpVectors(e,t=new L,i=new L,a=new L){this.getSurfaceNormal(e,a),t.set(-e.y,e.x,0).normalize(),i.crossVectors(a,t).normalize()}getEastNorthUpFrame(e,t=new ke){const i=xf,a=Y2,r=q2;return this.getEastNorthUpVectors(e,i,a,r),t.makeBasis(i,a,r).setPosition(e)}getNorthUpEastFrame(e,t=new ke){const i=xf,a=Y2,r=q2;return this.getEastNorthUpVectors(e,i,a,r),t.makeBasis(a,r,i).setPosition(e)}getIntersection(e,t=new L){const i=this.reciprocalRadii(xf),a=Y2.copy(i).multiply(e.origin),r=q2.copy(i).multiply(e.direction),s=a.lengthSq(),o=r.lengthSq(),c=a.dot(r),h=c**2-o*(s-1);if(s===1)return t.copy(e.origin);if(s>1){if(c>=0||h<0)return;const f=Math.sqrt(h),d=(-c-f)/o,m=(-c+f)/o;return e.at(Math.min(d,m),t)}if(s<1){const f=c**2-o*(s-1),d=Math.sqrt(f),m=(-c+d)/o;return e.at(m,t)}if(c<0)return e.at(-c/o,t)}getOsculatingSphereCenter(e,t,i=new L){Kx(this.radii.x===this.radii.y);const a=this.radii.x**2,r=this.radii.z**2,s=xf.set(e.x/a,e.y/a,e.z/r).normalize();return i.copy(s.multiplyScalar(-t).add(e))}getNormalAtHorizon(e,t,i=new L){Kx(this.radii.x===this.radii.y);const a=this.radii.x**2,r=this.radii.z**2,s=e,o=t;let c=(s.x*o.x+s.y*o.y)/a+s.z*o.z/r;c/=(s.x**2+s.y**2)/a+s.z**2/r;const h=xf.copy(o).multiplyScalar(-c).add(e);return i.set(h.x/a,h.y/a,h.z/r).normalize()}};UE.WGS84=new UE(6378137,6378137,6356752314245179e-9);let _0=UE;const kv=new L,iO=new L,dm=class PE{constructor(e=0,t=0,i=0){this.longitude=e,this.latitude=t,this.height=i}set(e,t,i){return this.longitude=e,this.latitude=t,i!=null&&(this.height=i),this}clone(){return new PE(this.longitude,this.latitude,this.height)}copy(e){return this.longitude=e.longitude,this.latitude=e.latitude,this.height=e.height,this}equals(e){return e.longitude===this.longitude&&e.latitude===this.latitude&&e.height===this.height}setLongitude(e){return this.longitude=e,this}setLatitude(e){return this.latitude=e,this}setHeight(e){return this.height=e,this}normalize(){return this.longitude -Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE -version 0.8.2 -*/var es=Uint8Array,Xf=Uint16Array,vee=Int32Array,K8=new es([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Q8=new es([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),_ee=new es([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),J8=function(n,e){for(var t=new Xf(31),i=0;i<31;++i)t[i]=e+=1<>1|(ei&21845)<<1;zl=(zl&52428)>>2|(zl&13107)<<2,zl=(zl&61680)>>4|(zl&3855)<<4,zE[ei]=((zl&65280)>>8|(zl&255)<<8)>>1}var Gm=function(n,e,t){for(var i=n.length,a=0,r=new Xf(e);a>c]=h}else for(o=new Xf(i),a=0;a>15-n[a]);return o},W0=new es(288);for(var ei=0;ei<144;++ei)W0[ei]=8;for(var ei=144;ei<256;++ei)W0[ei]=9;for(var ei=256;ei<280;++ei)W0[ei]=7;for(var ei=280;ei<288;++ei)W0[ei]=8;var tP=new es(32);for(var ei=0;ei<32;++ei)tP[ei]=5;var Tee=Gm(W0,9,1),Eee=Gm(tP,5,1),j2=function(n){for(var e=n[0],t=1;te&&(e=n[t]);return e},_s=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},Z2=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},Mee=function(n){return(n+7)/8|0},bee=function(n,e,t){return(t==null||t>n.length)&&(t=n.length),new es(n.subarray(e,t))},Aee=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ts=function(n,e,t){var i=new Error(e||Aee[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,Ts),!t)throw i;return i},wee=function(n,e,t,i){var a=n.length,r=0;if(!a||e.f&&!e.l)return t||new es(0);var s=!t,o=s||e.i!=2,c=e.i;s&&(t=new es(a*3));var h=function(Mt){var ot=t.length;if(Mt>ot){var Ke=new es(Math.max(ot*2,Mt));Ke.set(t),t=Ke}},f=e.f||0,d=e.p||0,m=e.b||0,g=e.l,x=e.d,T=e.m,y=e.n,v=a*8;do{if(!g){f=_s(n,d,1);var S=_s(n,d+1,3);if(d+=3,S)if(S==1)g=Tee,x=Eee,T=9,y=5;else if(S==2){var C=_s(n,d,31)+257,I=_s(n,d+10,15)+4,P=C+_s(n,d+5,31)+1;d+=14;for(var O=new es(P),w=new es(19),B=0;B>4;if(E<16)O[B++]=E;else{var W=0,te=0;for(E==16?(te=3+_s(n,d,3),d+=2,W=O[B-1]):E==17?(te=3+_s(n,d,7),d+=3):E==18&&(te=11+_s(n,d,127),d+=7);te--;)O[B++]=W}}var K=O.subarray(0,C),oe=O.subarray(C);T=j2(K),y=j2(oe),g=Gm(K,T,1),x=Gm(oe,y,1)}else Ts(1);else{var E=Mee(d)+4,b=n[E-4]|n[E-3]<<8,D=E+b;if(D>a){c&&Ts(0);break}o&&h(m+b),t.set(n.subarray(E,D),m),e.b=m+=b,e.p=d=D*8,e.f=f;continue}if(d>v){c&&Ts(0);break}}o&&h(m+131072);for(var ie=(1<>4;if(d+=W&15,d>v){c&&Ts(0);break}if(W||Ts(2),nt<256)t[m++]=nt;else if(nt==256){Xe=d,g=null;break}else{var tt=nt-254;if(nt>264){var B=nt-257,gt=K8[B];tt=_s(n,d,(1<>4;ge||Ts(3),d+=ge&15;var oe=See[Ae];if(Ae>3){var gt=Q8[Ae];oe+=Z2(n,d)&(1<v){c&&Ts(0);break}o&&h(m+131072);var Ze=m+tt;if(m>4>7||(n[0]<<8|n[1])%31)&&Ts(6,"invalid zlib data"),(n[1]>>5&1)==1&&Ts(6,"invalid zlib data: "+(n[1]&32?"need":"unexpected")+" dictionary"),(n[1]>>3&4)+2};function Wv(n,e){return wee(n.subarray(Cee(n),-4),{i:2},e,e)}var Nee=typeof TextDecoder<"u"&&new TextDecoder,Dee=0;try{Nee.decode(Ree,{stream:!0}),Dee=1}catch{}class nP extends _6{constructor(e){super(e),this.type=Xn,this.outputFormat=$n}parse(e){const O=Math.pow(2.7182818,2.2);function w(R,z){let Y=0;for(let V=0;V<65536;++V)(V==0||R[V>>3]&1<<(V&7))&&(z[Y++]=V);const N=Y-1;for(;Y<65536;)z[Y++]=0;return N}function B(R){for(let z=0;z<16384;z++)R[z]={},R[z].len=0,R[z].lit=0,R[z].p=null}const j={l:0,c:0,lc:0};function ee(R,z,Y,N,V){for(;Y>Y&(1<0;--Y){const N=z+se[Y]>>1;se[Y]=z,z=N}for(let Y=0;Y<65537;++Y){const N=R[Y];N>0&&(R[Y]=N|se[N]++<<6)}}function W(R,z,Y,N,V,Z){const H=z;let X=0,ne=0;for(;N<=V;N++){if(H.value-z.value>Y)return!1;ee(6,X,ne,R,H);const ae=j.l;if(X=j.c,ne=j.lc,Z[N]=ae,ae==63){if(H.value-z.value>Y)throw new Error("Something wrong with hufUnpackEncTable");ee(8,X,ne,R,H);let fe=j.l+6;if(X=j.c,ne=j.lc,N+fe>V+1)throw new Error("Something wrong with hufUnpackEncTable");for(;fe--;)Z[N++]=0;N--}else if(ae>=59){let fe=ae-59+2;if(N+fe>V+1)throw new Error("Something wrong with hufUnpackEncTable");for(;fe--;)Z[N++]=0;N--}}re(Z)}function te(R){return R&63}function K(R){return R>>6}function oe(R,z,Y,N){for(;z<=Y;z++){const V=K(R[z]),Z=te(R[z]);if(V>>Z)throw new Error("Invalid table entry");if(Z>14){const H=N[V>>Z-14];if(H.len)throw new Error("Invalid table entry");if(H.lit++,H.p){const X=H.p;H.p=new Array(H.lit);for(let ne=0;ne0;X--){const ne=N[(V<<14-Z)+H];if(ne.len||ne.p)throw new Error("Invalid table entry");ne.len=Z,ne.lit=z,H++}}}return!0}const ie={c:0,lc:0};function Ce(R,z,Y,N){R=R<<8|Q(Y,N),z+=8,ie.c=R,ie.lc=z}const Xe={c:0,lc:0};function nt(R,z,Y,N,V,Z,H,X,ne){if(R==z){N<8&&(Ce(Y,N,V,Z),Y=ie.c,N=ie.lc),N-=8;let ae=Y>>N;if(ae=new Uint8Array([ae])[0],X.value+ae>ne)return!1;const fe=H[X.value-1];for(;ae-- >0;)H[X.value++]=fe}else if(X.value32767?z-65536:z}const ge={a:0,b:0};function Ae(R,z){const Y=gt(R),V=gt(z),Z=Y+(V&1)+(V>>1),H=Z,X=Z-V;ge.a=H,ge.b=X}function Ze(R,z){const Y=tt(R),N=tt(z),V=Y-(N>>1)&65535,Z=N+V-32768&65535;ge.a=Z,ge.b=V}function ue(R,z,Y,N,V,Z,H){const X=H<16384,ne=Y>V?V:Y;let ae=1,fe,_e;for(;ae<=ne;)ae<<=1;for(ae>>=1,fe=ae,ae>>=1;ae>=1;){_e=0;const Se=_e+Z*(V-fe),Re=Z*ae,Pe=Z*fe,ze=N*ae,Ye=N*fe;let lt,Tt,bt,ft;for(;_e<=Se;_e+=Pe){let At=_e;const st=_e+N*(Y-fe);for(;At<=st;At+=Ye){const Kt=At+ze,On=At+Re,Yt=On+ze;X?(Ae(R[At+z],R[On+z]),lt=ge.a,bt=ge.b,Ae(R[Kt+z],R[Yt+z]),Tt=ge.a,ft=ge.b,Ae(lt,Tt),R[At+z]=ge.a,R[Kt+z]=ge.b,Ae(bt,ft),R[On+z]=ge.a,R[Yt+z]=ge.b):(Ze(R[At+z],R[On+z]),lt=ge.a,bt=ge.b,Ze(R[Kt+z],R[Yt+z]),Tt=ge.a,ft=ge.b,Ze(lt,Tt),R[At+z]=ge.a,R[Kt+z]=ge.b,Ze(bt,ft),R[On+z]=ge.a,R[Yt+z]=ge.b)}if(Y&ae){const Kt=At+Re;X?Ae(R[At+z],R[Kt+z]):Ze(R[At+z],R[Kt+z]),lt=ge.a,R[Kt+z]=ge.b,R[At+z]=lt}}if(V&ae){let At=_e;const st=_e+N*(Y-fe);for(;At<=st;At+=Ye){const Kt=At+ze;X?Ae(R[At+z],R[Kt+z]):Ze(R[At+z],R[Kt+z]),lt=ge.a,R[Kt+z]=ge.b,R[At+z]=lt}}fe=ae,ae>>=1}return _e}function it(R,z,Y,N,V,Z,H,X,ne){let ae=0,fe=0;const _e=H,Se=Math.trunc(N.value+(V+7)/8);for(;N.value=14;){const Pe=ae>>fe-14&16383,ze=z[Pe];if(ze.len)fe-=ze.len,nt(ze.lit,Z,ae,fe,Y,N,X,ne,_e),ae=Xe.c,fe=Xe.lc;else{if(!ze.p)throw new Error("hufDecode issues");let Ye;for(Ye=0;Ye=lt&&K(R[ze.p[Ye]])==(ae>>fe-lt&(1<>=Re,fe-=Re;fe>0;){const Pe=z[ae<<14-fe&16383];if(Pe.len)fe-=Pe.len,nt(Pe.lit,Z,ae,fe,Y,N,X,ne,_e),ae=Xe.c,fe=Xe.lc;else throw new Error("hufDecode issues")}return!0}function Mt(R,z,Y,N,V,Z){const H={value:0},X=Y.value,ne=ht(z,Y),ae=ht(z,Y);Y.value+=4;const fe=ht(z,Y);if(Y.value+=4,ne<0||ne>=65537||ae<0||ae>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const _e=new Array(65537),Se=new Array(16384);B(Se);const Re=N-(Y.value-X);if(W(R,Y,Re,ne,ae,_e),fe>8*(N-(Y.value-X)))throw new Error("Something wrong with hufUncompress");oe(_e,ne,ae,Se),it(_e,Se,R,Y,fe,ae,Z,V,H)}function ot(R,z,Y){for(let N=0;NZ||(z[V++]=R[Y++],V>Z));)z[V++]=R[N++]}function G(R){let z=R.byteLength;const Y=new Array;let N=0;const V=new DataView(R);for(;z>0;){const Z=V.getInt8(N++);if(Z<0){const H=-Z;z-=H+1;for(let X=0;X>8==255?V+=N&255:(Y[V]=N,V++),R.value++}function Be(R,z){z[0]=me(R[0]),z[1]=me(R[1]),z[2]=me(R[5]),z[3]=me(R[6]),z[4]=me(R[14]),z[5]=me(R[15]),z[6]=me(R[27]),z[7]=me(R[28]),z[8]=me(R[2]),z[9]=me(R[4]),z[10]=me(R[7]),z[11]=me(R[13]),z[12]=me(R[16]),z[13]=me(R[26]),z[14]=me(R[29]),z[15]=me(R[42]),z[16]=me(R[3]),z[17]=me(R[8]),z[18]=me(R[12]),z[19]=me(R[17]),z[20]=me(R[25]),z[21]=me(R[30]),z[22]=me(R[41]),z[23]=me(R[43]),z[24]=me(R[9]),z[25]=me(R[11]),z[26]=me(R[18]),z[27]=me(R[24]),z[28]=me(R[31]),z[29]=me(R[40]),z[30]=me(R[44]),z[31]=me(R[53]),z[32]=me(R[10]),z[33]=me(R[19]),z[34]=me(R[23]),z[35]=me(R[32]),z[36]=me(R[39]),z[37]=me(R[45]),z[38]=me(R[52]),z[39]=me(R[54]),z[40]=me(R[20]),z[41]=me(R[22]),z[42]=me(R[33]),z[43]=me(R[38]),z[44]=me(R[46]),z[45]=me(R[51]),z[46]=me(R[55]),z[47]=me(R[60]),z[48]=me(R[21]),z[49]=me(R[34]),z[50]=me(R[37]),z[51]=me(R[47]),z[52]=me(R[50]),z[53]=me(R[56]),z[54]=me(R[59]),z[55]=me(R[61]),z[56]=me(R[35]),z[57]=me(R[36]),z[58]=me(R[48]),z[59]=me(R[49]),z[60]=me(R[57]),z[61]=me(R[58]),z[62]=me(R[62]),z[63]=me(R[63])}function $e(R){const z=.5*Math.cos(.7853975),Y=.5*Math.cos(3.14159/16),N=.5*Math.cos(3.14159/8),V=.5*Math.cos(3*3.14159/16),Z=.5*Math.cos(5*3.14159/16),H=.5*Math.cos(3*3.14159/8),X=.5*Math.cos(7*3.14159/16),ne=new Array(4),ae=new Array(4),fe=new Array(4),_e=new Array(4);for(let Se=0;Se<8;++Se){const Re=Se*8;ne[0]=N*R[Re+2],ne[1]=H*R[Re+2],ne[2]=N*R[Re+6],ne[3]=H*R[Re+6],ae[0]=Y*R[Re+1]+V*R[Re+3]+Z*R[Re+5]+X*R[Re+7],ae[1]=V*R[Re+1]-X*R[Re+3]-Y*R[Re+5]-Z*R[Re+7],ae[2]=Z*R[Re+1]-Y*R[Re+3]+X*R[Re+5]+V*R[Re+7],ae[3]=X*R[Re+1]-Z*R[Re+3]+V*R[Re+5]-Y*R[Re+7],fe[0]=z*(R[Re+0]+R[Re+4]),fe[3]=z*(R[Re+0]-R[Re+4]),fe[1]=ne[0]+ne[3],fe[2]=ne[1]-ne[2],_e[0]=fe[0]+fe[1],_e[1]=fe[3]+fe[2],_e[2]=fe[3]-fe[2],_e[3]=fe[0]-fe[1],R[Re+0]=_e[0]+ae[0],R[Re+1]=_e[1]+ae[1],R[Re+2]=_e[2]+ae[2],R[Re+3]=_e[3]+ae[3],R[Re+4]=_e[3]-ae[3],R[Re+5]=_e[2]-ae[2],R[Re+6]=_e[1]-ae[1],R[Re+7]=_e[0]-ae[0]}for(let Se=0;Se<8;++Se)ne[0]=N*R[16+Se],ne[1]=H*R[16+Se],ne[2]=N*R[48+Se],ne[3]=H*R[48+Se],ae[0]=Y*R[8+Se]+V*R[24+Se]+Z*R[40+Se]+X*R[56+Se],ae[1]=V*R[8+Se]-X*R[24+Se]-Y*R[40+Se]-Z*R[56+Se],ae[2]=Z*R[8+Se]-Y*R[24+Se]+X*R[40+Se]+V*R[56+Se],ae[3]=X*R[8+Se]-Z*R[24+Se]+V*R[40+Se]-Y*R[56+Se],fe[0]=z*(R[Se]+R[32+Se]),fe[3]=z*(R[Se]-R[32+Se]),fe[1]=ne[0]+ne[3],fe[2]=ne[1]-ne[2],_e[0]=fe[0]+fe[1],_e[1]=fe[3]+fe[2],_e[2]=fe[3]-fe[2],_e[3]=fe[0]-fe[1],R[0+Se]=_e[0]+ae[0],R[8+Se]=_e[1]+ae[1],R[16+Se]=_e[2]+ae[2],R[24+Se]=_e[3]+ae[3],R[32+Se]=_e[3]-ae[3],R[40+Se]=_e[2]-ae[2],R[48+Se]=_e[1]-ae[1],R[56+Se]=_e[0]-ae[0]}function Je(R){for(let z=0;z<64;++z){const Y=R[0][z],N=R[1][z],V=R[2][z];R[0][z]=Y+1.5747*V,R[1][z]=Y-.1873*N-.4682*V,R[2][z]=Y+1.8556*N}}function ct(R,z,Y){for(let N=0;N<64;++N)z[Y+N]=oE.toHalfFloat(k(R[N]))}function k(R){return R<=1?Math.sign(R)*Math.pow(Math.abs(R),2.2):Math.sign(R)*Math.pow(O,Math.abs(R)-1)}function U(R){return new DataView(R.array.buffer,R.offset.value,R.size)}function ce(R){const z=R.viewer.buffer.slice(R.offset.value,R.offset.value+R.size),Y=new Uint8Array(G(z)),N=new Uint8Array(Y.length);return Ke(Y),Te(Y,N),new DataView(N.buffer)}function Ee(R){const z=R.array.slice(R.offset.value,R.offset.value+R.size),Y=Wv(z),N=new Uint8Array(Y.length);return Ke(Y),Te(Y,N),new DataView(N.buffer)}function Le(R){const z=R.viewer,Y={value:R.offset.value},N=new Uint16Array(R.columns*R.lines*(R.inputChannels.length*R.type)),V=new Uint8Array(8192);let Z=0;const H=new Array(R.inputChannels.length);for(let Pe=0,ze=R.inputChannels.length;Pe=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(X<=ne)for(let Pe=0;Pe0;){const ze=qe(z.buffer,Y),Ye=pe(z,Y),lt=Ye>>2&3,Tt=(Ye>>4)-1,bt=new Int8Array([Tt])[0],ft=pe(z,Y);Z.push({name:ze,index:bt,type:ft,compression:lt}),H-=ze.length+3}const X=sr.channels,ne=new Array(R.inputChannels.length);for(let ze=0;ze=0&&(ae.idx[Tt.index]=ze),Ye.offset=ze)}}let fe,_e,Se;if(V.acCompressedSize>0)switch(V.acCompression){case 0:fe=new Uint16Array(V.totalAcUncompressedCount),Mt(R.array,z,Y,V.acCompressedSize,fe,V.totalAcUncompressedCount);break;case 1:const ze=R.array.slice(Y.value,Y.value+V.totalAcUncompressedCount),Ye=Wv(ze);fe=new Uint16Array(Ye.buffer),Y.value+=V.totalAcUncompressedCount;break}if(V.dcCompressedSize>0){const ze={array:R.array,offset:Y,size:V.dcCompressedSize};_e=new Uint16Array(Ee(ze).buffer),Y.value+=V.dcCompressedSize}if(V.rleRawSize>0){const ze=R.array.slice(Y.value,Y.value+V.rleCompressedSize),Ye=Wv(ze);Se=G(Ye.buffer),Y.value+=V.rleCompressedSize}let Re=0;const Pe=new Array(ne.length);for(let ze=0;ze>10,Y=R&1023;return(R>>15?-1:1)*(z?z===31?Y?NaN:1/0:Math.pow(2,z-15)*(1+Y/1024):6103515625e-14*(Y/1024))}function We(R,z){const Y=R.getUint16(z.value,!0);return z.value+=2,Y}function Ge(R,z){return me(We(R,z))}function we(R,z,Y,N){const V=Y.value,Z=[];for(;Y.value>4]}}function uo(R,z){const Y=q(R,z),N=q(R,z);return[Y,N]}function Is(R,z){const Y=q(R,z),N=q(R,z),V=q(R,z);return[Y,N,V]}function Us(R,z,Y,N,V){if(N==="string"||N==="stringvector"||N==="iccProfile")return _t(z,Y,V);if(N==="chlist")return we(R,z,Y,V);if(N==="chromaticities")return rt(R,Y);if(N==="compression")return yt(R,Y);if(N==="box2i")return Gt(R,Y);if(N==="envmap")return li(R,Y);if(N==="tiledesc")return ci(R,Y);if(N==="lineOrder")return Vt(R,Y);if(N==="float")return q(R,Y);if(N==="v2f")return uo(R,Y);if(N==="v3f")return Is(R,Y);if(N==="int")return He(R,Y);if(N==="rational")return pt(R,Y);if(N==="timecode")return Ie(R,Y);if(N==="preview")return Y.value+=V,"skipped";Y.value+=V}function bi(R,z){const Y=Math.log2(R);return z=="ROUND_DOWN"?Math.floor(Y):Math.ceil(Y)}function Ps(R,z,Y){let N=0;switch(R.levelMode){case"ONE_LEVEL":N=1;break;case"MIPMAP_LEVELS":N=bi(Math.max(z,Y),R.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return N}function fa(R,z,Y,N){const V=new Array(R);for(let Z=0;ZR.width?R.width-H:R.blockWidth,R.lines=X+R.blockHeight>R.height?R.height-X:R.blockHeight;const ne=R.columns*R.totalBytes,fe=R.sizeR.height?R.height-V:R.blockHeight;const Z=R.columns*R.totalBytes,X=R.size=R.height)continue;const _e=ne*Z,Se=(R.height-1-fe)*R.outLineWidth;for(let Re=0;ReSe:H.scanOrder=Se=>H.height-1-Se,R.spec.singleTile){H.blockHeight=R.tiles.ySize,H.blockWidth=R.tiles.xSize;const Se=Ps(R.tiles,H.width,H.height),Re=fa(Se,H.width,R.tiles.xSize,R.tiles.roundingMode),Pe=fa(Se,H.height,R.tiles.ySize,R.tiles.roundingMode);H.tileCount=Re[0]*Pe[0];for(let ze=0;ze{Kx(s instanceof ArrayBuffer);try{t(s)}catch(o){a!=null?a(o):console.error(o),this.manager.itemError(e)}},i,a)}};function iP(n){var e,t;return n instanceof $b?n.getContext().getExtension("OES_texture_float_linear")!=null:((t=(e=n.backend).hasFeature)==null?void 0:t.call(e,"float32-filterable"))??!1}const Lee=128,Iee=128,Uee=64,Pee="9627216cc50057994c98a2118f3c4a23765d43b9",aP=`https://media.githubusercontent.com/media/takram-design-engineering/three-geospatial/${Pee}/packages/core/assets/stbn.bin`,zee="This is not an object",Bee="This is not a Float16Array object",aO="This constructor is not a subclass of Float16Array",rP="The constructor property value is not an object",Hee="Species constructor didn't return TypedArray object",Fee="Derived constructor created TypedArray object which was too small length",Vm="Attempting to access detached ArrayBuffer",BE="Cannot convert undefined or null to object",HE="Cannot mix BigInt and other types, use explicit conversions",rO="@@iterator property is not callable",sO="Reduce of empty array with no initial value",Gee="The comparison function must be either a function or undefined",K2="Offset is out of bounds";function jn(n){return(e,...t)=>ja(n,e,t)}function Kd(n,e){return jn(Ld(n,e).get)}const{apply:ja,construct:pm,defineProperty:Vee,get:Q2,getOwnPropertyDescriptor:Ld,getPrototypeOf:X0,has:FE,ownKeys:sP,set:oO,setPrototypeOf:oP}=Reflect,kee=Proxy,{EPSILON:Wee,MAX_SAFE_INTEGER:lO,isFinite:lP,isNaN:Id}=Number,{iterator:oo,species:Xee,toStringTag:cA,for:Yee}=Symbol,Ud=Object,{create:uy,defineProperty:Y0,freeze:qee,is:cO}=Ud,GE=Ud.prototype,jee=GE.__lookupGetter__?jn(GE.__lookupGetter__):(n,e)=>{if(n==null)throw ai(BE);let t=Ud(n);do{const i=Ld(t,e);if(i!==void 0)return Xo(i,"get")?i.get:void 0}while((t=X0(t))!==null)},Xo=Ud.hasOwn||jn(GE.hasOwnProperty),cP=Array,uP=cP.isArray,hy=cP.prototype,Zee=jn(hy.join),Kee=jn(hy.push),Qee=jn(hy.toLocaleString),uA=hy[oo],Jee=jn(uA),{abs:$ee,trunc:hP}=Math,fy=ArrayBuffer,ete=fy.isView,fP=fy.prototype,tte=jn(fP.slice),nte=Kd(fP,"byteLength"),VE=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:null,ite=VE&&Kd(VE.prototype,"byteLength"),hA=X0(Uint8Array),ate=hA.from,ia=hA.prototype,rte=ia[oo],ste=jn(ia.keys),ote=jn(ia.values),lte=jn(ia.entries),cte=jn(ia.set),uO=jn(ia.reverse),ute=jn(ia.fill),hte=jn(ia.copyWithin),hO=jn(ia.sort),$p=jn(ia.slice),fte=jn(ia.subarray),Ki=Kd(ia,"buffer"),fu=Kd(ia,"byteOffset"),Tn=Kd(ia,"length"),dP=Kd(ia,cA),dte=Uint8Array,xr=Uint16Array,fO=(...n)=>ja(ate,xr,n),fA=Uint32Array,pte=Float32Array,eh=X0([][oo]()),dy=jn(eh.next),mte=jn(function*(){}().next),gte=X0(eh),vte=DataView.prototype,_te=jn(vte.getUint16),ai=TypeError,J2=RangeError,pP=WeakSet,mP=pP.prototype,xte=jn(mP.add),yte=jn(mP.has),py=WeakMap,dA=py.prototype,Qx=jn(dA.get),Ste=jn(dA.has),pA=jn(dA.set),gP=new py,Tte=uy(null,{next:{value:function(){const n=Qx(gP,this);return dy(n)}},[oo]:{value:function(){return this}}});function mm(n){if(n[oo]===uA&&eh.next===dy)return n;const e=uy(Tte);return pA(gP,e,Jee(n)),e}const vP=new py,_P=uy(gte,{next:{value:function(){const n=Qx(vP,this);return mte(n)},writable:!0,configurable:!0}});for(const n of sP(eh))n!=="next"&&Y0(_P,n,Ld(eh,n));function dO(n){const e=uy(_P);return pA(vP,e,n),e}function Jx(n){return n!==null&&typeof n=="object"||typeof n=="function"}function pO(n){return n!==null&&typeof n=="object"}function $x(n){return dP(n)!==void 0}function kE(n){const e=dP(n);return e==="BigInt64Array"||e==="BigUint64Array"}function Ete(n){try{return uP(n)?!1:(nte(n),!0)}catch{return!1}}function xP(n){if(VE===null)return!1;try{return ite(n),!0}catch{return!1}}function Mte(n){return Ete(n)||xP(n)}function mO(n){return uP(n)?n[oo]===uA&&eh.next===dy:!1}function bte(n){return $x(n)?n[oo]===rte&&eh.next===dy:!1}function Xv(n){if(typeof n!="string")return!1;const e=+n;return n!==e+""||!lP(e)?!1:e===hP(e)}const e1=Yee("__Float16Array__");function Ate(n){if(!pO(n))return!1;const e=X0(n);if(!pO(e))return!1;const t=e.constructor;if(t===void 0)return!1;if(!Jx(t))throw ai(rP);return FE(t,e1)}const WE=1/Wee;function wte(n){return n+WE-WE}const yP=6103515625e-14,Rte=65504,SP=.0009765625,gO=SP*yP,Cte=SP*WE;function Nte(n){const e=+n;if(!lP(e)||e===0)return e;const t=e>0?1:-1,i=$ee(e);if(iRte||Id(r)?t*(1/0):t*r}const TP=new fy(4),EP=new pte(TP),MP=new fA(TP),xs=new xr(512),ys=new dte(512);for(let n=0;n<256;++n){const e=n-127;e<-24?(xs[n]=0,xs[n|256]=32768,ys[n]=24,ys[n|256]=24):e<-14?(xs[n]=1024>>-e-14,xs[n|256]=1024>>-e-14|32768,ys[n]=-e-1,ys[n|256]=-e-1):e<=15?(xs[n]=e+15<<10,xs[n|256]=e+15<<10|32768,ys[n]=13,ys[n|256]=13):e<128?(xs[n]=31744,xs[n|256]=64512,ys[n]=24,ys[n|256]=24):(xs[n]=31744,xs[n|256]=64512,ys[n]=13,ys[n|256]=13)}function Zs(n){EP[0]=Nte(n);const e=MP[0],t=e>>23&511;return xs[t]+((e&8388607)>>ys[t])}const mA=new fA(2048);for(let n=1;n<1024;++n){let e=n<<13,t=0;for(;!(e&8388608);)e<<=1,t-=8388608;e&=-8388609,t+=947912704,mA[n]=e|t}for(let n=1024;n<2048;++n)mA[n]=939524096+(n-1024<<13);const Qd=new fA(64);for(let n=1;n<31;++n)Qd[n]=n<<23;Qd[31]=1199570944;Qd[32]=2147483648;for(let n=33;n<63;++n)Qd[n]=2147483648+(n-32<<23);Qd[63]=3347054592;const bP=new xr(64);for(let n=1;n<64;++n)n!==32&&(bP[n]=1024);function An(n){const e=n>>10;return MP[0]=mA[bP[e]+(n&1023)]+Qd[e],EP[0]}function zo(n){const e=+n;return Id(e)||e===0?0:hP(e)}function $2(n){const e=zo(n);return e<0?0:ee)return 1;if(n===0&&e===0){const a=cO(n,0),r=cO(e,0);if(!a&&r)return-1;if(a&&!r)return 1}return 0}const gA=2,t1=new py;function Yf(n){return Ste(t1,n)||!ete(n)&&Ate(n)}function Sn(n){if(!Yf(n))throw ai(Bee)}function qv(n,e){const t=Yf(n),i=$x(n);if(!t&&!i)throw ai(Hee);if(typeof e=="number"){let a;if(t){const r=Jt(n);a=Tn(r)}else a=Tn(n);if(a=0?a:i+a;if(!(r<0||r>=i))return An(t[r])}with(e,t){Sn(this);const i=Jt(this),a=Tn(i),r=zo(e),s=r>=0?r:a+r,o=+t;if(s<0||s>=a)throw J2(K2);const c=new xr(Ki(i),fu(i),Tn(i)),h=new Qi(Ki($p(c))),f=Jt(h);return f[s]=Zs(o),h}map(e,...t){Sn(this);const i=Jt(this),a=Tn(i),r=t[0],s=Yv(i,Qi);if(s===Qi){const c=new Qi(a),h=Jt(c);for(let f=0;f=0;--o)r=e(r,An(i[o]),o,this);return r}forEach(e,...t){Sn(this);const i=Jt(this),a=Tn(i),r=t[0];for(let s=0;s=0;--s){const o=An(i[s]);if(ja(e,r,[o,s,this]))return o}}findLastIndex(e,...t){Sn(this);const i=Jt(this),a=Tn(i),r=t[0];for(let s=a-1;s>=0;--s){const o=An(i[s]);if(ja(e,r,[o,s,this]))return s}return-1}every(e,...t){Sn(this);const i=Jt(this),a=Tn(i),r=t[0];for(let s=0;sr)throw J2(K2);for(let c=0;ci(An(a),An(r))),this}toSorted(e){Sn(this);const t=Jt(this);if(e!==void 0&&typeof e!="function")throw new ai(Gee);const i=e!==void 0?e:vO,a=new xr(Ki(t),fu(t),Tn(t)),r=new Qi(Ki($p(a))),s=Jt(r);return hO(s,(o,c)=>i(An(o),An(c))),r}slice(e,t){Sn(this);const i=Jt(this),a=Yv(i,Qi);if(a===Qi){const x=new xr(Ki(i),fu(i),Tn(i));return new Qi(Ki($p(x,e,t)))}const r=Tn(i),s=zo(e),o=t===void 0?r:zo(t);let c;s===-1/0?c=0:s<0?c=r+s>0?r+s:0:c=r0?r+o:0:h=r0?h-c:0,d=new a(f);if(qv(d,f),f===0)return d;const m=Ki(i);if(km(m))throw ai(Vm);let g=0;for(;c=1?zo(t[0]):a-1;if(r===-1/0)return-1;r>=0?r=r=0;--s)if(Xo(i,s)&&An(i[s])===e)return s;return-1}includes(e,...t){Sn(this);const i=Jt(this),a=Tn(i);let r=zo(t[0]);if(r===1/0)return!1;r<0&&(r+=a,r<0&&(r=0));const s=Id(e);for(let o=r;o{try{t(this.parser(s))}catch(o){a!=null?a(o):console.error(o),this.manager.itemError(e)}},i,a)}};function Ite(n){const e=n instanceof Int8Array?D1:n instanceof Uint8Array||n instanceof Uint8ClampedArray?zi:n instanceof Int16Array?O1:n instanceof Uint16Array?Yu:n instanceof Int32Array?L0:n instanceof Uint32Array?Ds:n instanceof ul?Xn:n instanceof Float32Array||n instanceof Float64Array?si:null;return Kx(e!=null),e}let Su=class extends Mi{constructor(e,t,i={},a){super(a),this.textureClass=e,this.parser=t,this.options={format:$n,minFilter:Ht,magFilter:Ht,...i}}load(e,t,i,a){const r=new this.textureClass,s=new Lte(this.parser,this.manager);return s.setRequestHeader(this.requestHeader),s.setPath(this.path),s.setWithCredentials(this.withCredentials),s.load(e,o=>{r.image.data=o instanceof ul?new Uint16Array(o.buffer):o;const{width:c,height:h,depth:f,...d}=this.options;c!=null&&(r.image.width=c),h!=null&&(r.image.height=h),"depth"in r.image&&f!=null&&(r.image.depth=f),r.type=Ite(o),Object.assign(r,d),r.needsUpdate=!0,t==null||t(r)},i,a),r}};const i1=$t.clamp;$t.euclideanModulo;$t.inverseLerp;const wP=$t.lerp,Ute=$t.degToRad;$t.radToDeg;$t.isPowerOfTwo;$t.ceilPowerOfTwo;$t.floorPowerOfTwo;$t.normalize;function Pte(n,e,t,i=0,a=1){return $t.mapLinear(n,e,t,i,a)}function zte(n){return Math.min(Math.max(n,0),1)}function dn(n){return(e,t)=>{e instanceof qn?Object.defineProperty(e,t,{enumerable:!0,get(){var i;return((i=this.defines)==null?void 0:i[n])!=null},set(i){var a;i!==this[t]&&(i?(this.defines??(this.defines={}),this.defines[n]="1"):(a=this.defines)==null||delete a[n],this.needsUpdate=!0)}}):Object.defineProperty(e,t,{enumerable:!0,get(){return this.defines.has(n)},set(i){i!==this[t]&&(i?this.defines.set(n,"1"):this.defines.delete(n),this.setChanged())}})}}function mh(n,{min:e=Number.MIN_SAFE_INTEGER,max:t=Number.MAX_SAFE_INTEGER}={}){return(i,a)=>{i instanceof qn?Object.defineProperty(i,a,{enumerable:!0,get(){var s;const r=(s=this.defines)==null?void 0:s[n];return r!=null?parseInt(r,10):0},set(r){const s=this[a];r!==s&&(this.defines??(this.defines={}),this.defines[n]=i1(r,e,t).toFixed(0),this.needsUpdate=!0)}}):Object.defineProperty(i,a,{enumerable:!0,get(){const r=this.defines.get(n);return r!=null?parseInt(r,10):0},set(r){const s=this[a];r!==s&&(this.defines.set(n,i1(r,e,t).toFixed(0)),this.setChanged())}})}}function vA(n,{min:e=-1/0,max:t=1/0,precision:i=7}={}){return(a,r)=>{a instanceof qn?Object.defineProperty(a,r,{enumerable:!0,get(){var o;const s=(o=this.defines)==null?void 0:o[n];return s!=null?parseFloat(s):0},set(s){const o=this[r];s!==o&&(this.defines??(this.defines={}),this.defines[n]=i1(s,e,t).toFixed(i),this.needsUpdate=!0)}}):Object.defineProperty(a,r,{enumerable:!0,get(){const s=this.defines.get(n);return s!=null?parseFloat(s):0},set(s){const o=this[r];s!==o&&(this.defines.set(n,i1(s,e,t).toFixed(i)),this.setChanged())}})}}function RP(n,{validate:e}={}){return(t,i)=>{t instanceof qn?Object.defineProperty(t,i,{enumerable:!0,get(){var a;return((a=this.defines)==null?void 0:a[n])??""},set(a){if(a!==this[i]){if((e==null?void 0:e(a))===!1){console.error(`Expression validation failed: ${a}`);return}this.defines??(this.defines={}),this.defines[n]=a,this.needsUpdate=!0}}}):Object.defineProperty(t,i,{enumerable:!0,get(){return this.defines.get(n)??""},set(a){if(a!==this[i]){if((e==null?void 0:e(a))===!1){console.error(`Expression validation failed: ${a}`);return}this.defines.set(n,a),this.setChanged()}}})}}function xO(n,...e){const t={};for(let i=0;ia[s],set:o=>{a[s]=o}}}return Object.defineProperties(n,t),n}function yO(n,e,t){const i={};for(const a of t)i[a]={enumerable:!0,get:()=>e.uniforms[a].value,set:r=>{e.uniforms[a].value=r}};return Object.defineProperties(n,i),n}class e3 extends Mi{constructor(e={},t){super(t),this.options=e}load(e,t,i,a){const{width:r,height:s,depth:o}=this.options,c=new as(null,r,s,o),h=new nP(this.manager);return h.setRequestHeader(this.requestHeader),h.setPath(this.path),h.setWithCredentials(this.withCredentials),h.load(e,f=>{const{image:d}=f;c.image={data:d.data,width:r??d.width,height:s??d.height,depth:o??Math.sqrt(d.height)},c.type=f.type,c.format=f.format,c.colorSpace=f.colorSpace,c.needsUpdate=!0;try{t==null||t(c)}catch(m){a!=null?a(m):console.error(m),this.manager.itemError(e)}},i,a),c}}class SO extends Mi{constructor(e={},t){super(t),this.options=e}load(e,t,i,a){const{width:r,height:s}=this.options,o=new $a(null,r,s),c=new nP(this.manager);return c.setRequestHeader(this.requestHeader),c.setPath(this.path),c.setWithCredentials(this.withCredentials),c.load(e,h=>{const{image:f}=h;o.image={data:f.data,width:r??f.width,height:s??f.height},o.type=h.type,o.format=h.format,o.colorSpace=h.colorSpace,o.needsUpdate=!0;try{t==null||t(o)}catch(d){a!=null?a(d):console.error(d),this.manager.itemError(e)}},i,a),o}}const Bte=/^[ \t]*#include +"([\w\d./]+)"/gm;function Na(n,e){return n.replace(Bte,(t,i)=>{const a=i.split("/").reduce((r,s)=>typeof r!="string"&&r!=null?r[s]:void 0,e);if(typeof a!="string")throw new Error(`Could not find include for ${i}.`);return Na(a,e)})}let jv;function Hte(){if(jv!=null)return jv;const n=new Uint32Array([268435456]);return jv=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)[0]===0,jv}function Fte(n,e,t,i=!0){if(i===Hte())return new e(n);const a=Object.assign(new DataView(n),{getFloat16(s,o){return Ote(this,s,o)}}),r=new e(a.byteLength/e.BYTES_PER_ELEMENT);for(let s=0,o=0;snew Uint8Array(n),em=(n,e)=>Fte(n,ul,"getFloat16",e);class NP extends Su{constructor(e){super(as,CP,{format:As,minFilter:Fn,magFilter:Fn,wrapS:Ea,wrapT:Ea,wrapR:Ea,width:Lee,height:Iee,depth:Uee},e)}}const Gte=/#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*i)\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Vte(n,e,t,i){let a="";for(let r=parseInt(e,10);r= interval.x && depth < interval.y) { - return UNROLLED_LOOP_INDEX; - } - #endif // UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT - } - #pragma unroll_loop_end - return SHADOW_CASCADE_COUNT - 1; -} - -int getFadedCascadeIndex( - const mat4 viewMatrix, - const vec3 worldPosition, - const vec2 intervals[SHADOW_CASCADE_COUNT], - const float near, - const float far, - const float jitter -) { - vec4 viewPosition = viewMatrix * vec4(worldPosition, 1.0); - float depth = viewZToOrthographicDepth(viewPosition.z, near, far); - - vec2 interval; - float intervalCenter; - float closestEdge; - float margin; - int nextIndex = -1; - int prevIndex = -1; - float alpha; - - #pragma unroll_loop_start - for (int i = 0; i < 4; ++i) { - #if UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT - interval = intervals[i]; - intervalCenter = (interval.x + interval.y) * 0.5; - closestEdge = depth < intervalCenter ? interval.x : interval.y; - margin = closestEdge * closestEdge * 0.5; - interval += margin * vec2(-0.5, 0.5); - - #if UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT - 1 - if (depth >= interval.x && depth < interval.y) { - prevIndex = nextIndex; - nextIndex = UNROLLED_LOOP_INDEX; - alpha = saturate(min(depth - interval.x, interval.y - depth) / margin); - } - #else // UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT - 1 - // Don't fade out the last cascade. - if (depth >= interval.x) { - prevIndex = nextIndex; - nextIndex = UNROLLED_LOOP_INDEX; - alpha = saturate((depth - interval.x) / margin); - } - #endif // UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT - 1 - #endif // UNROLLED_LOOP_INDEX < SHADOW_CASCADE_COUNT - } - #pragma unroll_loop_end - - return jitter <= alpha - ? nextIndex - : prevIndex; -} -`,Wte=`// cSpell:words logdepthbuf - -float reverseLogDepth(const float depth, const float near, const float far) { - #if defined(USE_LOGDEPTHBUF) || defined(USE_LOGARITHMIC_DEPTH_BUFFER) - float d = pow(2.0, depth * log2(far + 1.0)) - 1.0; - float a = far / (far - near); - float b = far * near / (near - far); - return a + b / d; - #else // defined(USE_LOGARITHMIC_DEPTH_BUFFER) || defined(USE_LOGARITHMIC_DEPTH_BUFFER) - return depth; - #endif // defined(USE_LOGARITHMIC_DEPTH_BUFFER) || defined(USE_LOGARITHMIC_DEPTH_BUFFER) -} - -float linearizeDepth(const float depth, const float near, const float far) { - float ndc = depth * 2.0 - 1.0; - return 2.0 * near * far / (far + near - ndc * (far - near)); -} -`,Xte=`float checker(const vec2 uv, const vec2 repeats) { - vec2 c = floor(repeats * uv); - float result = mod(c.x + c.y, 2.0); - return sign(result); -} - -float checker(const vec2 uv, const float repeats) { - return checker(uv, vec2(repeats)); -} -`,Yte=`// Reference: https://advances.realtimerendering.com/s2014/index.html#_NEXT_GENERATION_POST - -float interleavedGradientNoise(const vec2 coord) { - const vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189); - return fract(magic.z * fract(dot(coord, magic.xy))); -} -`,qte=`#if !defined(saturate) -#define saturate(a) clamp(a, 0.0, 1.0) -#endif // !defined(saturate) - -float remap(const float x, const float min1, const float max1, const float min2, const float max2) { - return min2 + (x - min1) / (max1 - min1) * (max2 - min2); -} - -vec2 remap(const vec2 x, const vec2 min1, const vec2 max1, const vec2 min2, const vec2 max2) { - return min2 + (x - min1) / (max1 - min1) * (max2 - min2); -} - -vec3 remap(const vec3 x, const vec3 min1, const vec3 max1, const vec3 min2, const vec3 max2) { - return min2 + (x - min1) / (max1 - min1) * (max2 - min2); -} - -vec4 remap(const vec4 x, const vec4 min1, const vec4 max1, const vec4 min2, const vec4 max2) { - return min2 + (x - min1) / (max1 - min1) * (max2 - min2); -} - -float remapClamped( - const float x, - const float min1, - const float max1, - const float min2, - const float max2 -) { - return clamp(min2 + (x - min1) / (max1 - min1) * (max2 - min2), min2, max2); -} - -vec2 remapClamped( - const vec2 x, - const vec2 min1, - const vec2 max1, - const vec2 min2, - const vec2 max2 -) { - return clamp(min2 + (x - min1) / (max1 - min1) * (max2 - min2), min2, max2); -} - -vec3 remapClamped( - const vec3 x, - const vec3 min1, - const vec3 max1, - const vec3 min2, - const vec3 max2 -) { - return clamp(min2 + (x - min1) / (max1 - min1) * (max2 - min2), min2, max2); -} - -vec4 remapClamped( - const vec4 x, - const vec4 min1, - const vec4 max1, - const vec4 min2, - const vec4 max2 -) { - return clamp(min2 + (x - min1) / (max1 - min1) * (max2 - min2), min2, max2); -} - -// Implicitly remap to 0 and 1 -float remap(const float x, const float min1, const float max1) { - return (x - min1) / (max1 - min1); -} - -vec2 remap(const vec2 x, const vec2 min1, const vec2 max1) { - return (x - min1) / (max1 - min1); -} - -vec3 remap(const vec3 x, const vec3 min1, const vec3 max1) { - return (x - min1) / (max1 - min1); -} - -vec4 remap(const vec4 x, const vec4 min1, const vec4 max1) { - return (x - min1) / (max1 - min1); -} - -float remapClamped(const float x, const float min1, const float max1) { - return saturate((x - min1) / (max1 - min1)); -} - -vec2 remapClamped(const vec2 x, const vec2 min1, const vec2 max1) { - return saturate((x - min1) / (max1 - min1)); -} - -vec3 remapClamped(const vec3 x, const vec3 min1, const vec3 max1) { - return saturate((x - min1) / (max1 - min1)); -} - -vec4 remapClamped(const vec4 x, const vec4 min1, const vec4 max1) { - return saturate((x - min1) / (max1 - min1)); -} -`,jte=`// Reference: https://jcgt.org/published/0003/02/01/paper.pdf - -vec2 signNotZero(vec2 v) { - return vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0); -} - -vec2 packNormalToVec2(vec3 v) { - vec2 p = v.xy * (1.0 / (abs(v.x) + abs(v.y) + abs(v.z))); - return v.z <= 0.0 - ? (1.0 - abs(p.yx)) * signNotZero(p) - : p; -} - -vec3 unpackVec2ToNormal(vec2 e) { - vec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y)); - if (v.z < 0.0) { - v.xy = (1.0 - abs(v.yx)) * signNotZero(v.xy); - } - return normalize(v); -} -`,Zte=`float raySphereFirstIntersection( - const vec3 origin, - const vec3 direction, - const vec3 center, - const float radius -) { - vec3 a = origin - center; - float b = 2.0 * dot(direction, a); - float c = dot(a, a) - radius * radius; - float discriminant = b * b - 4.0 * c; - return discriminant < 0.0 - ? -1.0 - : (-b - sqrt(discriminant)) * 0.5; -} - -float raySphereFirstIntersection(const vec3 origin, const vec3 direction, const float radius) { - return raySphereFirstIntersection(origin, direction, vec3(0.0), radius); -} - -vec4 raySphereFirstIntersection( - const vec3 origin, - const vec3 direction, - const vec3 center, - const vec4 radius -) { - vec3 a = origin - center; - float b = 2.0 * dot(direction, a); - vec4 c = dot(a, a) - radius * radius; - vec4 discriminant = b * b - 4.0 * c; - vec4 mask = step(discriminant, vec4(0.0)); - return mix((-b - sqrt(max(vec4(0.0), discriminant))) * 0.5, vec4(-1.0), mask); -} - -vec4 raySphereFirstIntersection(const vec3 origin, const vec3 direction, const vec4 radius) { - return raySphereFirstIntersection(origin, direction, vec3(0.0), radius); -} - -float raySphereSecondIntersection( - const vec3 origin, - const vec3 direction, - const vec3 center, - const float radius -) { - vec3 a = origin - center; - float b = 2.0 * dot(direction, a); - float c = dot(a, a) - radius * radius; - float discriminant = b * b - 4.0 * c; - return discriminant < 0.0 - ? -1.0 - : (-b + sqrt(discriminant)) * 0.5; -} - -float raySphereSecondIntersection(const vec3 origin, const vec3 direction, const float radius) { - return raySphereSecondIntersection(origin, direction, vec3(0.0), radius); -} - -vec4 raySphereSecondIntersection( - const vec3 origin, - const vec3 direction, - const vec3 center, - const vec4 radius -) { - vec3 a = origin - center; - float b = 2.0 * dot(direction, a); - vec4 c = dot(a, a) - radius * radius; - vec4 discriminant = b * b - 4.0 * c; - vec4 mask = step(discriminant, vec4(0.0)); - return mix((-b + sqrt(max(vec4(0.0), discriminant))) * 0.5, vec4(-1.0), mask); -} - -vec4 raySphereSecondIntersection(const vec3 origin, const vec3 direction, const vec4 radius) { - return raySphereSecondIntersection(origin, direction, vec3(0.0), radius); -} - -void raySphereIntersections( - const vec3 origin, - const vec3 direction, - const vec3 center, - const float radius, - out float intersection1, - out float intersection2 -) { - vec3 a = origin - center; - float b = 2.0 * dot(direction, a); - float c = dot(a, a) - radius * radius; - float discriminant = b * b - 4.0 * c; - if (discriminant < 0.0) { - intersection1 = -1.0; - intersection2 = -1.0; - return; - } else { - float Q = sqrt(discriminant); - intersection1 = (-b - Q) * 0.5; - intersection2 = (-b + Q) * 0.5; - } -} - -void raySphereIntersections( - const vec3 origin, - const vec3 direction, - const float radius, - out float intersection1, - out float intersection2 -) { - raySphereIntersections(origin, direction, vec3(0.0), radius, intersection1, intersection2); -} - -void raySphereIntersections( - const vec3 origin, - const vec3 direction, - const vec3 center, - const vec4 radius, - out vec4 intersection1, - out vec4 intersection2 -) { - vec3 a = origin - center; - float b = 2.0 * dot(direction, a); - vec4 c = dot(a, a) - radius * radius; - vec4 discriminant = b * b - 4.0 * c; - vec4 mask = step(discriminant, vec4(0.0)); - vec4 Q = sqrt(max(vec4(0.0), discriminant)); - intersection1 = mix((-b - Q) * 0.5, vec4(-1.0), mask); - intersection2 = mix((-b + Q) * 0.5, vec4(-1.0), mask); -} - -void raySphereIntersections( - const vec3 origin, - const vec3 direction, - const vec4 radius, - out vec4 intersection1, - out vec4 intersection2 -) { - raySphereIntersections(origin, direction, vec3(0.0), radius, intersection1, intersection2); -} -`,Kte=`vec3 screenToView( - const vec2 uv, - const float depth, - const float viewZ, - const mat4 projectionMatrix, - const mat4 inverseProjectionMatrix -) { - vec4 clip = vec4(vec3(uv, depth) * 2.0 - 1.0, 1.0); - float clipW = projectionMatrix[2][3] * viewZ + projectionMatrix[3][3]; - clip *= clipW; - return (inverseProjectionMatrix * clip).xyz; -} -`,Qte=`// A fifth-order polynomial approximation of Turbo color map. -// See: https://observablehq.com/@mbostock/turbo -// prettier-ignore -vec3 turbo(const float x) { - float r = 0.1357 + x * (4.5974 - x * (42.3277 - x * (130.5887 - x * (150.5666 - x * 58.1375)))); - float g = 0.0914 + x * (2.1856 + x * (4.8052 - x * (14.0195 - x * (4.2109 + x * 2.7747)))); - float b = 0.1067 + x * (12.5925 - x * (60.1097 - x * (109.0745 - x * (88.5066 - x * 26.8183)))); - return vec3(r, g, b); -} -`,Jte=`// Reference: https://www.gamedev.net/tutorials/programming/graphics/contact-hardening-soft-shadows-made-fast-r4906/ - -vec2 vogelDisk(const int index, const int sampleCount, const float phi) { - const float goldenAngle = 2.39996322972865332; - float r = sqrt(float(index) + 0.5) / sqrt(float(sampleCount)); - float theta = float(index) * goldenAngle + phi; - return r * vec2(cos(theta), sin(theta)); -} -`,DP=kte,OP=Wte,$te=Xte,LP=Yte,_A=qte,ene=jte,my=Zte,tne=Kte,IP=Qte,UP=Jte,Jd=64,$d=16,gy=32,vy=128,_y=32,xy=8,zu=xy*_y,Bu=vy,Hu=gy,ep=256,tp=64,a1=1/1e3,nne=new L;function xA(n,e,t,i){const a=t.projectOnSurface(n,nne);return a!=null?t.getOsculatingSphereCenter(a,e,i).negate():i.setScalar(0)}var ine="Invariant failed";function ane(n,e){if(!n)throw new Error(ine)}const TO=typeof window<"u"&&window.requestIdleCallback!=null?window.requestIdleCallback:function(n,e={}){const t=e.timeout??1,i=performance.now();return setTimeout(function(){n({get didTimeout(){return e.timeout!=null?!1:performance.now()-i-1>t},timeRemaining:function(){return Math.max(0,1+(performance.now()-i))}})},1)},Ks=`// Based on: https://github.com/ebruneton/precomputed_atmospheric_scattering/blob/master/atmosphere/functions.glsl - -/** - * Copyright (c) 2017 Eric Bruneton - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - * - * Precomputed Atmospheric Scattering - * Copyright (c) 2008 INRIA - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -Number ClampCosine(const Number mu) { - return clamp(mu, Number(-1.0), Number(1.0)); -} - -Length ClampDistance(const Length d) { - return max(d, 0.0 * m); -} - -Length ClampRadius(const AtmosphereParameters atmosphere, const Length r) { - return clamp(r, atmosphere.bottom_radius, atmosphere.top_radius); -} - -Length SafeSqrt(const Area a) { - return sqrt(max(a, 0.0 * m2)); -} - -Length DistanceToTopAtmosphereBoundary(const AtmosphereParameters atmosphere, - const Length r, const Number mu) { - assert(r <= atmosphere.top_radius); - assert(mu >= -1.0 && mu <= 1.0); - Area discriminant = r * r * (mu * mu - 1.0) + - atmosphere.top_radius * atmosphere.top_radius; - return ClampDistance(-r * mu + SafeSqrt(discriminant)); -} - -Length DistanceToBottomAtmosphereBoundary(const AtmosphereParameters atmosphere, - const Length r, const Number mu) { - assert(r >= atmosphere.bottom_radius); - assert(mu >= -1.0 && mu <= 1.0); - Area discriminant = r * r * (mu * mu - 1.0) + - atmosphere.bottom_radius * atmosphere.bottom_radius; - return ClampDistance(-r * mu - SafeSqrt(discriminant)); -} - -bool RayIntersectsGround(const AtmosphereParameters atmosphere, - const Length r, const Number mu) { - assert(r >= atmosphere.bottom_radius); - assert(mu >= -1.0 && mu <= 1.0); - return mu < 0.0 && r * r * (mu * mu - 1.0) + - atmosphere.bottom_radius * atmosphere.bottom_radius >= 0.0 * m2; -} - -Number GetTextureCoordFromUnitRange(const Number x, const int texture_size) { - return 0.5 / Number(texture_size) + x * (1.0 - 1.0 / Number(texture_size)); -} - -vec2 GetTransmittanceTextureUvFromRMu(const AtmosphereParameters atmosphere, - const Length r, const Number mu) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu >= -1.0 && mu <= 1.0); - // Distance to top atmosphere boundary for a horizontal ray at ground level. - Length H = sqrt(atmosphere.top_radius * atmosphere.top_radius - - atmosphere.bottom_radius * atmosphere.bottom_radius); - // Distance to the horizon. - Length rho = - SafeSqrt(r * r - atmosphere.bottom_radius * atmosphere.bottom_radius); - // Distance to the top atmosphere boundary for the ray (r,mu), and its minimum - // and maximum values over all mu - obtained for (r,1) and (r,mu_horizon). - Length d = DistanceToTopAtmosphereBoundary(atmosphere, r, mu); - Length d_min = atmosphere.top_radius - r; - Length d_max = rho + H; - Number x_mu = (d - d_min) / (d_max - d_min); - Number x_r = rho / H; - return vec2(GetTextureCoordFromUnitRange(x_mu, TRANSMITTANCE_TEXTURE_WIDTH), - GetTextureCoordFromUnitRange(x_r, TRANSMITTANCE_TEXTURE_HEIGHT)); -} - -DimensionlessSpectrum GetTransmittanceToTopAtmosphereBoundary( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const Length r, const Number mu) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - vec2 uv = GetTransmittanceTextureUvFromRMu(atmosphere, r, mu); - // @shotamatsuda: Added for the precomputation stage in half-float precision. - #ifdef TRANSMITTANCE_PRECISION_LOG - // Manually interpolate the transmittance instead of the optical depth. - const vec2 size = vec2(TRANSMITTANCE_TEXTURE_WIDTH, TRANSMITTANCE_TEXTURE_HEIGHT); - const vec3 texel_size = vec3(1.0 / size, 0.0); - vec2 coord = (uv * size) - 0.5; - vec2 i = (floor(coord) + 0.5) * texel_size.xy; - vec2 f = fract(coord); - vec4 t1 = exp(-texture(transmittance_texture, i)); - vec4 t2 = exp(-texture(transmittance_texture, i + texel_size.xz)); - vec4 t3 = exp(-texture(transmittance_texture, i + texel_size.zy)); - vec4 t4 = exp(-texture(transmittance_texture, i + texel_size.xy)); - return DimensionlessSpectrum(mix(mix(t1, t2, f.x), mix(t3, t4, f.x), f.y)); - #else // TRANSMITTANCE_PRECISION_LOG - return DimensionlessSpectrum(texture(transmittance_texture, uv)); - #endif // TRANSMITTANCE_PRECISION_LOG -} - -DimensionlessSpectrum GetTransmittance( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const Length r, const Number mu, const Length d, - const bool ray_r_mu_intersects_ground) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu >= -1.0 && mu <= 1.0); - assert(d >= 0.0 * m); - - Length r_d = ClampRadius(atmosphere, sqrt(d * d + 2.0 * r * mu * d + r * r)); - Number mu_d = ClampCosine((r * mu + d) / r_d); - - if (ray_r_mu_intersects_ground) { - return min( - GetTransmittanceToTopAtmosphereBoundary( - atmosphere, transmittance_texture, r_d, -mu_d) / - GetTransmittanceToTopAtmosphereBoundary( - atmosphere, transmittance_texture, r, -mu), - DimensionlessSpectrum(1.0)); - } else { - return min( - GetTransmittanceToTopAtmosphereBoundary( - atmosphere, transmittance_texture, r, mu) / - GetTransmittanceToTopAtmosphereBoundary( - atmosphere, transmittance_texture, r_d, mu_d), - DimensionlessSpectrum(1.0)); - } -} - -DimensionlessSpectrum GetTransmittanceToSun( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const Length r, const Number mu_s) { - Number sin_theta_h = atmosphere.bottom_radius / r; - Number cos_theta_h = -sqrt(max(1.0 - sin_theta_h * sin_theta_h, 0.0)); - return GetTransmittanceToTopAtmosphereBoundary( - atmosphere, transmittance_texture, r, mu_s) * - smoothstep(-sin_theta_h * atmosphere.sun_angular_radius / rad, - sin_theta_h * atmosphere.sun_angular_radius / rad, - mu_s - cos_theta_h); -} - -InverseSolidAngle RayleighPhaseFunction(const Number nu) { - InverseSolidAngle k = 3.0 / (16.0 * PI * sr); - return k * (1.0 + nu * nu); -} - -InverseSolidAngle MiePhaseFunction(const Number g, const Number nu) { - InverseSolidAngle k = 3.0 / (8.0 * PI * sr) * (1.0 - g * g) / (2.0 + g * g); - return k * (1.0 + nu * nu) / pow(1.0 + g * g - 2.0 * g * nu, 1.5); -} - -vec4 GetScatteringTextureUvwzFromRMuMuSNu(const AtmosphereParameters atmosphere, - const Length r, const Number mu, const Number mu_s, const Number nu, - const bool ray_r_mu_intersects_ground) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu >= -1.0 && mu <= 1.0); - assert(mu_s >= -1.0 && mu_s <= 1.0); - assert(nu >= -1.0 && nu <= 1.0); - - // Distance to top atmosphere boundary for a horizontal ray at ground level. - Length H = sqrt(atmosphere.top_radius * atmosphere.top_radius - - atmosphere.bottom_radius * atmosphere.bottom_radius); - // Distance to the horizon. - Length rho = - SafeSqrt(r * r - atmosphere.bottom_radius * atmosphere.bottom_radius); - Number u_r = GetTextureCoordFromUnitRange(rho / H, SCATTERING_TEXTURE_R_SIZE); - - // Discriminant of the quadratic equation for the intersections of the ray - // (r,mu) with the ground (see RayIntersectsGround). - Length r_mu = r * mu; - Area discriminant = - r_mu * r_mu - r * r + atmosphere.bottom_radius * atmosphere.bottom_radius; - Number u_mu; - if (ray_r_mu_intersects_ground) { - // Distance to the ground for the ray (r,mu), and its minimum and maximum - // values over all mu - obtained for (r,-1) and (r,mu_horizon). - Length d = -r_mu - SafeSqrt(discriminant); - Length d_min = r - atmosphere.bottom_radius; - Length d_max = rho; - u_mu = 0.5 - 0.5 * GetTextureCoordFromUnitRange(d_max == d_min ? 0.0 : - (d - d_min) / (d_max - d_min), SCATTERING_TEXTURE_MU_SIZE / 2); - } else { - // Distance to the top atmosphere boundary for the ray (r,mu), and its - // minimum and maximum values over all mu - obtained for (r,1) and - // (r,mu_horizon). - Length d = -r_mu + SafeSqrt(discriminant + H * H); - Length d_min = atmosphere.top_radius - r; - Length d_max = rho + H; - u_mu = 0.5 + 0.5 * GetTextureCoordFromUnitRange( - (d - d_min) / (d_max - d_min), SCATTERING_TEXTURE_MU_SIZE / 2); - } - - Length d = DistanceToTopAtmosphereBoundary( - atmosphere, atmosphere.bottom_radius, mu_s); - Length d_min = atmosphere.top_radius - atmosphere.bottom_radius; - Length d_max = H; - Number a = (d - d_min) / (d_max - d_min); - Length D = DistanceToTopAtmosphereBoundary( - atmosphere, atmosphere.bottom_radius, atmosphere.mu_s_min); - Number A = (D - d_min) / (d_max - d_min); - // An ad-hoc function equal to 0 for mu_s = mu_s_min (because then d = D and - // thus a = A), equal to 1 for mu_s = 1 (because then d = d_min and thus - // a = 0), and with a large slope around mu_s = 0, to get more texture - // samples near the horizon. - Number u_mu_s = GetTextureCoordFromUnitRange( - max(1.0 - a / A, 0.0) / (1.0 + a), SCATTERING_TEXTURE_MU_S_SIZE); - - Number u_nu = (nu + 1.0) / 2.0; - return vec4(u_nu, u_mu_s, u_mu, u_r); -} - -vec2 GetIrradianceTextureUvFromRMuS(const AtmosphereParameters atmosphere, - const Length r, const Number mu_s) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu_s >= -1.0 && mu_s <= 1.0); - Number x_r = (r - atmosphere.bottom_radius) / - (atmosphere.top_radius - atmosphere.bottom_radius); - Number x_mu_s = mu_s * 0.5 + 0.5; - return vec2(GetTextureCoordFromUnitRange(x_mu_s, IRRADIANCE_TEXTURE_WIDTH), - GetTextureCoordFromUnitRange(x_r, IRRADIANCE_TEXTURE_HEIGHT)); -} - -IrradianceSpectrum GetIrradiance( - const AtmosphereParameters atmosphere, - const IrradianceTexture irradiance_texture, - const Length r, const Number mu_s) { - vec2 uv = GetIrradianceTextureUvFromRMuS(atmosphere, r, mu_s); - return IrradianceSpectrum(texture(irradiance_texture, uv)); -} -`,Qs=`// Based on: https://github.com/ebruneton/precomputed_atmospheric_scattering/blob/master/atmosphere/definitions.glsl - -/** - * Copyright (c) 2017 Eric Bruneton - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#define assert(x) - -#define Length float -#define Wavelength float -#define Angle float -#define SolidAngle float -#define Power float -#define LuminousPower float - -#define Number float -#define InverseLength float -#define Area float -#define Volume float -#define NumberDensity float -#define Irradiance float -#define Radiance float -#define SpectralPower float -#define SpectralIrradiance float -#define SpectralRadiance float -#define SpectralRadianceDensity float -#define ScatteringCoefficient float -#define InverseSolidAngle float -#define LuminousIntensity float -#define Luminance float -#define Illuminance float - -// A generic function from Wavelength to some other type. -#define AbstractSpectrum vec3 -// A function from Wavelength to Number. -#define DimensionlessSpectrum vec3 -// A function from Wavelength to SpectralPower. -#define PowerSpectrum vec3 -// A function from Wavelength to SpectralIrradiance. -#define IrradianceSpectrum vec3 -// A function from Wavelength to SpectralRadiance. -#define RadianceSpectrum vec3 -// A function from Wavelength to SpectralRadianceDensity. -#define RadianceDensitySpectrum vec3 -// A function from Wavelength to ScatteringCoefficient. -#define ScatteringSpectrum vec3 - -// A position in 3D (3 length values). -#define Position vec3 -// A unit direction vector in 3D (3 unit-less values). -#define Direction vec3 -// A vector of 3 luminance values. -#define Luminance3 vec3 -// A vector of 3 illuminance values. -#define Illuminance3 vec3 - -#define TransmittanceTexture sampler2D -#define AbstractScatteringTexture sampler3D -#define ReducedScatteringTexture sampler3D -#define ScatteringTexture sampler3D -#define ScatteringDensityTexture sampler3D -#define IrradianceTexture sampler2D - -const Length m = 1.0; -const Wavelength nm = 1.0; -const Angle rad = 1.0; -const SolidAngle sr = 1.0; -const Power watt = 1.0; -const LuminousPower lm = 1.0; - -#if !defined(PI) -const float PI = 3.14159265358979323846; -#endif // !defined(PI) - -const Length km = 1000.0 * m; -const Area m2 = m * m; -const Volume m3 = m * m * m; -const Angle pi = PI * rad; -const Angle deg = pi / 180.0; -const Irradiance watt_per_square_meter = watt / m2; -const Radiance watt_per_square_meter_per_sr = watt / (m2 * sr); -const SpectralIrradiance watt_per_square_meter_per_nm = watt / (m2 * nm); -const SpectralRadiance watt_per_square_meter_per_sr_per_nm = watt / (m2 * sr * nm); -const SpectralRadianceDensity watt_per_cubic_meter_per_sr_per_nm = watt / (m3 * sr * nm); -const LuminousIntensity cd = lm / sr; -const LuminousIntensity kcd = 1000.0 * cd; -const Luminance cd_per_square_meter = cd / m2; -const Luminance kcd_per_square_meter = kcd / m2; - -struct DensityProfileLayer { - Length width; - Number exp_term; - InverseLength exp_scale; - InverseLength linear_term; - Number constant_term; -}; - -struct DensityProfile { - DensityProfileLayer layers[2]; -}; - -// See AtmosphereParameter.ts for further details. -struct AtmosphereParameters { - IrradianceSpectrum solar_irradiance; - Angle sun_angular_radius; - Length bottom_radius; - Length top_radius; - DensityProfile rayleigh_density; - ScatteringSpectrum rayleigh_scattering; - DensityProfile mie_density; - ScatteringSpectrum mie_scattering; - ScatteringSpectrum mie_extinction; - Number mie_phase_function_g; - DensityProfile absorption_density; - ScatteringSpectrum absorption_extinction; - DimensionlessSpectrum ground_albedo; - Number mu_s_min; -}; -`,yy=`// Based on: https://github.com/ebruneton/precomputed_atmospheric_scattering/blob/master/atmosphere/functions.glsl - -/** - * Copyright (c) 2017 Eric Bruneton - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - * - * Precomputed Atmospheric Scattering - * Copyright (c) 2008 INRIA - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifdef COMBINED_SCATTERING_TEXTURES -vec3 GetExtrapolatedSingleMieScattering( - const AtmosphereParameters atmosphere, const vec4 scattering) { - // Algebraically this can never be negative, but rounding errors can produce - // that effect for sufficiently short view rays. - // @shotamatsuda: Avoid division by infinitesimal values. - // See https://github.com/takram-design-engineering/three-geospatial/issues/47 - if (scattering.r < 1e-5) { - return vec3(0.0); - } - return scattering.rgb * scattering.a / scattering.r * - (atmosphere.rayleigh_scattering.r / atmosphere.mie_scattering.r) * - (atmosphere.mie_scattering / atmosphere.rayleigh_scattering); -} -#endif // COMBINED_SCATTERING_TEXTURES - -IrradianceSpectrum GetCombinedScattering( - const AtmosphereParameters atmosphere, - const ReducedScatteringTexture scattering_texture, - const ReducedScatteringTexture single_mie_scattering_texture, - const Length r, const Number mu, const Number mu_s, const Number nu, - const bool ray_r_mu_intersects_ground, - out IrradianceSpectrum single_mie_scattering) { - vec4 uvwz = GetScatteringTextureUvwzFromRMuMuSNu( - atmosphere, r, mu, mu_s, nu, ray_r_mu_intersects_ground); - Number tex_coord_x = uvwz.x * Number(SCATTERING_TEXTURE_NU_SIZE - 1); - Number tex_x = floor(tex_coord_x); - Number lerp = tex_coord_x - tex_x; - vec3 uvw0 = vec3((tex_x + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), - uvwz.z, uvwz.w); - vec3 uvw1 = vec3((tex_x + 1.0 + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), - uvwz.z, uvwz.w); -#ifdef COMBINED_SCATTERING_TEXTURES - vec4 combined_scattering = - texture(scattering_texture, uvw0) * (1.0 - lerp) + - texture(scattering_texture, uvw1) * lerp; - IrradianceSpectrum scattering = IrradianceSpectrum(combined_scattering); - single_mie_scattering = - GetExtrapolatedSingleMieScattering(atmosphere, combined_scattering); -#else // COMBINED_SCATTERING_TEXTURES - IrradianceSpectrum scattering = IrradianceSpectrum( - texture(scattering_texture, uvw0) * (1.0 - lerp) + - texture(scattering_texture, uvw1) * lerp); - single_mie_scattering = IrradianceSpectrum( - texture(single_mie_scattering_texture, uvw0) * (1.0 - lerp) + - texture(single_mie_scattering_texture, uvw1) * lerp); -#endif // COMBINED_SCATTERING_TEXTURES - return scattering; -} - -// @shotamatsuda: Added for reading higher-order scattering texture. -#ifdef HAS_HIGHER_ORDER_SCATTERING_TEXTURE -IrradianceSpectrum GetScattering( - const AtmosphereParameters atmosphere, - const ReducedScatteringTexture scattering_texture, - const Length r, const Number mu, const Number mu_s, const Number nu, - const bool ray_r_mu_intersects_ground) { - vec4 uvwz = GetScatteringTextureUvwzFromRMuMuSNu( - atmosphere, r, mu, mu_s, nu, ray_r_mu_intersects_ground); - Number tex_coord_x = uvwz.x * Number(SCATTERING_TEXTURE_NU_SIZE - 1); - Number tex_x = floor(tex_coord_x); - Number lerp = tex_coord_x - tex_x; - vec3 uvw0 = vec3((tex_x + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), - uvwz.z, uvwz.w); - vec3 uvw1 = vec3((tex_x + 1.0 + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), - uvwz.z, uvwz.w); - IrradianceSpectrum scattering = IrradianceSpectrum( - texture(scattering_texture, uvw0) * (1.0 - lerp) + - texture(scattering_texture, uvw1) * lerp); - return scattering; -} -#endif // HAS_HIGHER_ORDER_SCATTERING_TEXTURE - -RadianceSpectrum GetSkyRadiance( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const ReducedScatteringTexture scattering_texture, - const ReducedScatteringTexture single_mie_scattering_texture, - Position camera, const Direction view_ray, const Length shadow_length, - const Direction sun_direction, - out DimensionlessSpectrum transmittance) { - // Compute the distance to the top atmosphere boundary along the view ray, - // assuming the viewer is in space (or NaN if the view ray does not intersect - // the atmosphere). - Length r = length(camera); - Length rmu = dot(camera, view_ray); - // @shotamatsuda: Use SafeSqrt instead. - // See: https://github.com/takram-design-engineering/three-geospatial/pull/26 - Length distance_to_top_atmosphere_boundary = -rmu - - SafeSqrt(rmu * rmu - r * r + - atmosphere.top_radius * atmosphere.top_radius); - // If the viewer is in space and the view ray intersects the atmosphere, move - // the viewer to the top atmosphere boundary (along the view ray): - if (distance_to_top_atmosphere_boundary > 0.0 * m) { - camera = camera + view_ray * distance_to_top_atmosphere_boundary; - r = atmosphere.top_radius; - rmu += distance_to_top_atmosphere_boundary; - } else if (r > atmosphere.top_radius) { - // If the view ray does not intersect the atmosphere, simply return 0. - transmittance = DimensionlessSpectrum(1.0); - return RadianceSpectrum(0.0 * watt_per_square_meter_per_sr_per_nm); - } - // Compute the r, mu, mu_s and nu parameters needed for the texture lookups. - Number mu = rmu / r; - Number mu_s = dot(camera, sun_direction) / r; - Number nu = dot(view_ray, sun_direction); - - // @shotamatsuda: For rendering points below the bottom atmosphere. - #ifdef GROUND - bool ray_r_mu_intersects_ground = RayIntersectsGround(atmosphere, r, mu); - #else // GROUND - bool ray_r_mu_intersects_ground = false; - #endif // GROUND - - transmittance = ray_r_mu_intersects_ground ? DimensionlessSpectrum(0.0) : - GetTransmittanceToTopAtmosphereBoundary( - atmosphere, transmittance_texture, r, mu); - IrradianceSpectrum single_mie_scattering; - IrradianceSpectrum scattering; - if (shadow_length == 0.0 * m) { - scattering = GetCombinedScattering( - atmosphere, scattering_texture, single_mie_scattering_texture, - r, mu, mu_s, nu, ray_r_mu_intersects_ground, - single_mie_scattering); - } else { - // Case of light shafts (shadow_length is the total length noted l in our - // paper): we omit the scattering between the camera and the point at - // distance l, by implementing Eq. (18) of the paper (shadow_transmittance - // is the T(x,x_s) term, scattering is the S|x_s=x+lv term). - Length d = shadow_length; - Length r_p = - ClampRadius(atmosphere, sqrt(d * d + 2.0 * r * mu * d + r * r)); - Number mu_p = (r * mu + d) / r_p; - Number mu_s_p = (r * mu_s + d * nu) / r_p; - - scattering = GetCombinedScattering( - atmosphere, scattering_texture, single_mie_scattering_texture, - r_p, mu_p, mu_s_p, nu, ray_r_mu_intersects_ground, - single_mie_scattering); - DimensionlessSpectrum shadow_transmittance = - GetTransmittance(atmosphere, transmittance_texture, - r, mu, shadow_length, ray_r_mu_intersects_ground); - // @shotamatsuda: Occlude only single Rayleigh scattering by the shadow. -#ifdef HAS_HIGHER_ORDER_SCATTERING_TEXTURE - IrradianceSpectrum higher_order_scattering = GetScattering( - atmosphere, higher_order_scattering_texture, - r_p, mu_p, mu_s_p, nu, ray_r_mu_intersects_ground); - IrradianceSpectrum single_scattering = scattering - higher_order_scattering; - scattering = single_scattering * shadow_transmittance + higher_order_scattering; -#else // HAS_HIGHER_ORDER_SCATTERING_TEXTURE - scattering = scattering * shadow_transmittance; -#endif // HAS_HIGHER_ORDER_SCATTERING_TEXTURE - single_mie_scattering = single_mie_scattering * shadow_transmittance; - } - return scattering * RayleighPhaseFunction(nu) + single_mie_scattering * - MiePhaseFunction(atmosphere.mie_phase_function_g, nu); -} - -// @shotamatsuda: Returns the point on the ray closest to the origin. -vec3 ClosestPointOnRay(const Position camera, const Position point) { - Position ray = point - camera; - Number t = clamp(-dot(camera, ray) / dot(ray, ray), 0.0, 1.0); - return camera + t * ray; -} - -vec2 RaySphereIntersections( - const Position camera, const Direction direction, const Length radius) { - float b = 2.0 * dot(direction, camera); - float c = dot(camera, camera) - radius * radius; - float discriminant = b * b - 4.0 * c; - float Q = sqrt(discriminant); - return vec2(-b - Q, -b + Q) * 0.5; -} - -// @shotamatsuda: Clip the view ray at the bottom atmosphere boundary. -bool ClipAtBottomAtmosphere( - const AtmosphereParameters atmosphere, - const Direction view_ray, inout Position camera, inout Position point) { - const Length eps = 0.0; - Length bottom_radius = atmosphere.bottom_radius + eps; - Length r_camera = length(camera); - Length r_point = length(point); - bool camera_below = r_camera < bottom_radius; - bool point_below = r_point < bottom_radius; - - vec2 t = RaySphereIntersections(camera, view_ray, bottom_radius); - Position intersection = camera + view_ray * (camera_below ? t.y : t.x); - camera = camera_below ? intersection : camera; - point = point_below ? intersection : point; - - return camera_below && point_below; -} - -RadianceSpectrum GetSkyRadianceToPoint( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const ReducedScatteringTexture scattering_texture, - const ReducedScatteringTexture single_mie_scattering_texture, - Position camera, Position point, const Length shadow_length, - const Direction sun_direction, out DimensionlessSpectrum transmittance) { - // @shotamatsuda: Avoid artifacts when the ray does not intersect the top - // atmosphere boundary. - if (length(ClosestPointOnRay(camera, point)) > atmosphere.top_radius) { - transmittance = vec3(1.0); - return vec3(0.0); - } - - Direction view_ray = normalize(point - camera); - if (ClipAtBottomAtmosphere(atmosphere, view_ray, camera, point)) { - transmittance = vec3(1.0); - return vec3(0.0); - } - - // Compute the distance to the top atmosphere boundary along the view ray, - // assuming the viewer is in space (or NaN if the view ray does not intersect - // the atmosphere). - Length r = length(camera); - Length rmu = dot(camera, view_ray); - // @shotamatsuda: Use SafeSqrt instead. - // See: https://github.com/takram-design-engineering/three-geospatial/pull/26 - Length distance_to_top_atmosphere_boundary = -rmu - - SafeSqrt(rmu * rmu - r * r + - atmosphere.top_radius * atmosphere.top_radius); - // If the viewer is in space and the view ray intersects the atmosphere, move - // the viewer to the top atmosphere boundary (along the view ray): - if (distance_to_top_atmosphere_boundary > 0.0 * m) { - camera = camera + view_ray * distance_to_top_atmosphere_boundary; - r = atmosphere.top_radius; - rmu += distance_to_top_atmosphere_boundary; - } - - // Compute the r, mu, mu_s and nu parameters for the first texture lookup. - Number mu = rmu / r; - Number mu_s = dot(camera, sun_direction) / r; - Number nu = dot(view_ray, sun_direction); - Length d = length(point - camera); - bool ray_r_mu_intersects_ground = RayIntersectsGround(atmosphere, r, mu); - - // @shotamatsuda: Hack to avoid rendering artifacts near the horizon, due to - // finite atmosphere texture resolution and finite floating point precision. - // See: https://github.com/ebruneton/precomputed_atmospheric_scattering/pull/32 - if (!ray_r_mu_intersects_ground) { - Number mu_horizon = -SafeSqrt(1.0 - - (atmosphere.bottom_radius * atmosphere.bottom_radius) / (r * r)); - const Number eps = 0.004; - mu = max(mu, mu_horizon + eps); - } - - transmittance = GetTransmittance(atmosphere, transmittance_texture, - r, mu, d, ray_r_mu_intersects_ground); - - IrradianceSpectrum single_mie_scattering; - IrradianceSpectrum scattering = GetCombinedScattering( - atmosphere, scattering_texture, single_mie_scattering_texture, - r, mu, mu_s, nu, ray_r_mu_intersects_ground, - single_mie_scattering); - - // Compute the r, mu, mu_s and nu parameters for the second texture lookup. - // If shadow_length is not 0 (case of light shafts), we want to ignore the - // scattering along the last shadow_length meters of the view ray, which we - // do by subtracting shadow_length from d (this way scattering_p is equal to - // the S|x_s=x_0-lv term in Eq. (17) of our paper). - d = max(d - shadow_length, 0.0 * m); - Length r_p = ClampRadius(atmosphere, sqrt(d * d + 2.0 * r * mu * d + r * r)); - Number mu_p = (r * mu + d) / r_p; - Number mu_s_p = (r * mu_s + d * nu) / r_p; - - IrradianceSpectrum single_mie_scattering_p; - IrradianceSpectrum scattering_p = GetCombinedScattering( - atmosphere, scattering_texture, single_mie_scattering_texture, - r_p, mu_p, mu_s_p, nu, ray_r_mu_intersects_ground, - single_mie_scattering_p); - - // Combine the lookup results to get the scattering between camera and point. - DimensionlessSpectrum shadow_transmittance = transmittance; - if (shadow_length > 0.0 * m) { - // This is the T(x,x_s) term in Eq. (17) of our paper, for light shafts. - shadow_transmittance = GetTransmittance(atmosphere, transmittance_texture, - r, mu, d, ray_r_mu_intersects_ground); - } - // @shotamatsuda: Occlude only single Rayleigh scattering by the shadow. -#ifdef HAS_HIGHER_ORDER_SCATTERING_TEXTURE - IrradianceSpectrum higher_order_scattering = GetScattering( - atmosphere, higher_order_scattering_texture, - r, mu, mu_s, nu, ray_r_mu_intersects_ground); - IrradianceSpectrum single_scattering = scattering - higher_order_scattering; - IrradianceSpectrum higher_order_scattering_p = GetScattering( - atmosphere, higher_order_scattering_texture, - r_p, mu_p, mu_s_p, nu, ray_r_mu_intersects_ground); - IrradianceSpectrum single_scattering_p = - scattering_p - higher_order_scattering_p; - scattering = - single_scattering - shadow_transmittance * single_scattering_p + - higher_order_scattering - transmittance * higher_order_scattering_p; -#else // HAS_HIGHER_ORDER_SCATTERING_TEXTURE - scattering = scattering - shadow_transmittance * scattering_p; -#endif // HAS_HIGHER_ORDER_SCATTERING_TEXTURE - - single_mie_scattering = - single_mie_scattering - shadow_transmittance * single_mie_scattering_p; -#ifdef COMBINED_SCATTERING_TEXTURES - single_mie_scattering = GetExtrapolatedSingleMieScattering( - atmosphere, vec4(scattering, single_mie_scattering.r)); -#endif // COMBINED_SCATTERING_TEXTURES - - // Hack to avoid rendering artifacts when the sun is below the horizon. - single_mie_scattering = single_mie_scattering * - smoothstep(Number(0.0), Number(0.01), mu_s); - - return scattering * RayleighPhaseFunction(nu) + single_mie_scattering * - MiePhaseFunction(atmosphere.mie_phase_function_g, nu); -} - -IrradianceSpectrum GetSunAndSkyIrradiance( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const IrradianceTexture irradiance_texture, - const Position point, const Direction normal, const Direction sun_direction, - out IrradianceSpectrum sky_irradiance) { - Length r = length(point); - Number mu_s = dot(point, sun_direction) / r; - - // Indirect irradiance (approximated if the surface is not horizontal). - sky_irradiance = GetIrradiance(atmosphere, irradiance_texture, r, mu_s) * - (1.0 + dot(normal, point) / r) * 0.5; - - // Direct irradiance. - return atmosphere.solar_irradiance * - GetTransmittanceToSun( - atmosphere, transmittance_texture, r, mu_s) * - max(dot(normal, sun_direction), 0.0); -} - -// @shotamatsuda: Added for the clouds. -IrradianceSpectrum GetSunAndSkyScalarIrradiance( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const IrradianceTexture irradiance_texture, - const Position point, const Direction sun_direction, - out IrradianceSpectrum sky_irradiance) { - Length r = length(point); - Number mu_s = dot(point, sun_direction) / r; - - // Indirect irradiance. Integral over sphere yields 2π. - sky_irradiance = GetIrradiance(atmosphere, irradiance_texture, r, mu_s) * - 2.0 * PI; - - // Direct irradiance. Omit the cosine term. - return atmosphere.solar_irradiance * - GetTransmittanceToSun(atmosphere, transmittance_texture, r, mu_s); -} - -Luminance3 GetSolarLuminance() { - return ATMOSPHERE.solar_irradiance / - (PI * ATMOSPHERE.sun_angular_radius * ATMOSPHERE.sun_angular_radius) * - SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; -} - -Luminance3 GetSkyLuminance( - const Position camera, Direction view_ray, const Length shadow_length, - const Direction sun_direction, out DimensionlessSpectrum transmittance) { - return GetSkyRadiance(ATMOSPHERE, transmittance_texture, - scattering_texture, single_mie_scattering_texture, - camera, view_ray, shadow_length, sun_direction, - transmittance) * SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; -} - -Luminance3 GetSkyLuminanceToPoint( - const Position camera, const Position point, const Length shadow_length, - const Direction sun_direction, out DimensionlessSpectrum transmittance) { - return GetSkyRadianceToPoint(ATMOSPHERE, transmittance_texture, - scattering_texture, single_mie_scattering_texture, - camera, point, shadow_length, sun_direction, transmittance) * - SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; -} - -Illuminance3 GetSunAndSkyIlluminance( - const Position p, const Direction normal, const Direction sun_direction, - out IrradianceSpectrum sky_irradiance) { - IrradianceSpectrum sun_irradiance = GetSunAndSkyIrradiance( - ATMOSPHERE, transmittance_texture, irradiance_texture, p, normal, - sun_direction, sky_irradiance); - sky_irradiance *= SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; - return sun_irradiance * SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; -} - -// @shotamatsuda: Added for the clouds. -Illuminance3 GetSunAndSkyScalarIlluminance( - const Position p, const Direction sun_direction, - out IrradianceSpectrum sky_irradiance) { - IrradianceSpectrum sun_irradiance = GetSunAndSkyScalarIrradiance( - ATMOSPHERE, transmittance_texture, irradiance_texture, p, - sun_direction, sky_irradiance); - sky_irradiance *= SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; - return sun_irradiance * SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; -} - -#define GetSolarRadiance GetSolarLuminance -#define GetSkyRadiance GetSkyLuminance -#define GetSkyRadianceToPoint GetSkyLuminanceToPoint -#define GetSunAndSkyIrradiance GetSunAndSkyIlluminance -#define GetSunAndSkyScalarIrradiance GetSunAndSkyScalarIlluminance -`,yf=`// Based on: https://github.com/ebruneton/precomputed_atmospheric_scattering/blob/master/atmosphere/functions.glsl - -/** - * Copyright (c) 2017 Eric Bruneton - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - * - * Precomputed Atmospheric Scattering - * Copyright (c) 2008 INRIA - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -Number GetLayerDensity(const DensityProfileLayer layer, const Length altitude) { - Number density = layer.exp_term * exp(layer.exp_scale * altitude) + - layer.linear_term * altitude + layer.constant_term; - return clamp(density, Number(0.0), Number(1.0)); -} - -Number GetProfileDensity(const DensityProfile profile, const Length altitude) { - DensityProfileLayer layers[2] = profile.layers; - return altitude < layers[0].width - ? GetLayerDensity(layers[0], altitude) - : GetLayerDensity(layers[1], altitude); -} - -Length ComputeOpticalLengthToTopAtmosphereBoundary( - const AtmosphereParameters atmosphere, const DensityProfile profile, - const Length r, const Number mu) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu >= -1.0 && mu <= 1.0); - // Number of intervals for the numerical integration. - const int SAMPLE_COUNT = 500; - // The integration step, i.e. the length of each integration interval. - Length dx = - DistanceToTopAtmosphereBoundary(atmosphere, r, mu) / Number(SAMPLE_COUNT); - // Integration loop. - Length result = 0.0 * m; - for (int i = 0; i <= SAMPLE_COUNT; ++i) { - Length d_i = Number(i) * dx; - // Distance between the current sample point and the planet center. - Length r_i = sqrt(d_i * d_i + 2.0 * r * mu * d_i + r * r); - // Number density at the current sample point (divided by the number density - // at the bottom of the atmosphere, yielding a dimensionless number). - Number y_i = GetProfileDensity(profile, r_i - atmosphere.bottom_radius); - // Sample weight (from the trapezoidal rule). - Number weight_i = i == 0 || i == SAMPLE_COUNT ? 0.5 : 1.0; - result += y_i * weight_i * dx; - } - return result; -} - -DimensionlessSpectrum ComputeTransmittanceToTopAtmosphereBoundary( - const AtmosphereParameters atmosphere, const Length r, const Number mu) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu >= -1.0 && mu <= 1.0); - vec3 optical_depth = ( - atmosphere.rayleigh_scattering * - ComputeOpticalLengthToTopAtmosphereBoundary( - atmosphere, atmosphere.rayleigh_density, r, mu) + - atmosphere.mie_extinction * - ComputeOpticalLengthToTopAtmosphereBoundary( - atmosphere, atmosphere.mie_density, r, mu) + - atmosphere.absorption_extinction * - ComputeOpticalLengthToTopAtmosphereBoundary( - atmosphere, atmosphere.absorption_density, r, mu)); - // @shotamatsuda: Added for the precomputation stage in half-float precision. - #ifdef TRANSMITTANCE_PRECISION_LOG - return optical_depth; - #else // TRANSMITTANCE_PRECISION_LOG - return exp(-optical_depth); - #endif // TRANSMITTANCE_PRECISION_LOG -} - -Number GetUnitRangeFromTextureCoord(const Number u, const int texture_size) { - return (u - 0.5 / Number(texture_size)) / (1.0 - 1.0 / Number(texture_size)); -} - -void GetRMuFromTransmittanceTextureUv(const AtmosphereParameters atmosphere, - const vec2 uv, out Length r, out Number mu) { - assert(uv.x >= 0.0 && uv.x <= 1.0); - assert(uv.y >= 0.0 && uv.y <= 1.0); - Number x_mu = GetUnitRangeFromTextureCoord(uv.x, TRANSMITTANCE_TEXTURE_WIDTH); - Number x_r = GetUnitRangeFromTextureCoord(uv.y, TRANSMITTANCE_TEXTURE_HEIGHT); - // Distance to top atmosphere boundary for a horizontal ray at ground level. - Length H = sqrt(atmosphere.top_radius * atmosphere.top_radius - - atmosphere.bottom_radius * atmosphere.bottom_radius); - // Distance to the horizon, from which we can compute r: - Length rho = H * x_r; - r = sqrt(rho * rho + atmosphere.bottom_radius * atmosphere.bottom_radius); - // Distance to the top atmosphere boundary for the ray (r,mu), and its minimum - // and maximum values over all mu - obtained for (r,1) and (r,mu_horizon) - - // from which we can recover mu: - Length d_min = atmosphere.top_radius - r; - Length d_max = rho + H; - Length d = d_min + x_mu * (d_max - d_min); - mu = d == 0.0 * m ? Number(1.0) : (H * H - rho * rho - d * d) / (2.0 * r * d); - mu = ClampCosine(mu); -} - -DimensionlessSpectrum ComputeTransmittanceToTopAtmosphereBoundaryTexture( - const AtmosphereParameters atmosphere, const vec2 frag_coord) { - const vec2 TRANSMITTANCE_TEXTURE_SIZE = - vec2(TRANSMITTANCE_TEXTURE_WIDTH, TRANSMITTANCE_TEXTURE_HEIGHT); - Length r; - Number mu; - GetRMuFromTransmittanceTextureUv( - atmosphere, frag_coord / TRANSMITTANCE_TEXTURE_SIZE, r, mu); - return ComputeTransmittanceToTopAtmosphereBoundary(atmosphere, r, mu); -} - -void ComputeSingleScatteringIntegrand( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const Length r, const Number mu, const Number mu_s, const Number nu, - const Length d, const bool ray_r_mu_intersects_ground, - out DimensionlessSpectrum rayleigh, out DimensionlessSpectrum mie) { - Length r_d = ClampRadius(atmosphere, sqrt(d * d + 2.0 * r * mu * d + r * r)); - Number mu_s_d = ClampCosine((r * mu_s + d * nu) / r_d); - DimensionlessSpectrum transmittance = - GetTransmittance( - atmosphere, transmittance_texture, r, mu, d, - ray_r_mu_intersects_ground) * - GetTransmittanceToSun( - atmosphere, transmittance_texture, r_d, mu_s_d); - rayleigh = transmittance * GetProfileDensity( - atmosphere.rayleigh_density, r_d - atmosphere.bottom_radius); - mie = transmittance * GetProfileDensity( - atmosphere.mie_density, r_d - atmosphere.bottom_radius); -} - -Length DistanceToNearestAtmosphereBoundary(const AtmosphereParameters atmosphere, - Length r, Number mu, bool ray_r_mu_intersects_ground) { - if (ray_r_mu_intersects_ground) { - return DistanceToBottomAtmosphereBoundary(atmosphere, r, mu); - } else { - return DistanceToTopAtmosphereBoundary(atmosphere, r, mu); - } -} - -void ComputeSingleScattering( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const Length r, const Number mu, const Number mu_s, const Number nu, - const bool ray_r_mu_intersects_ground, - out IrradianceSpectrum rayleigh, out IrradianceSpectrum mie) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu >= -1.0 && mu <= 1.0); - assert(mu_s >= -1.0 && mu_s <= 1.0); - assert(nu >= -1.0 && nu <= 1.0); - - // Number of intervals for the numerical integration. - const int SAMPLE_COUNT = 50; - // The integration step, i.e. the length of each integration interval. - Length dx = - DistanceToNearestAtmosphereBoundary(atmosphere, r, mu, - ray_r_mu_intersects_ground) / Number(SAMPLE_COUNT); - // Integration loop. - DimensionlessSpectrum rayleigh_sum = DimensionlessSpectrum(0.0); - DimensionlessSpectrum mie_sum = DimensionlessSpectrum(0.0); - for (int i = 0; i <= SAMPLE_COUNT; ++i) { - Length d_i = Number(i) * dx; - // The Rayleigh and Mie single scattering at the current sample point. - DimensionlessSpectrum rayleigh_i; - DimensionlessSpectrum mie_i; - ComputeSingleScatteringIntegrand(atmosphere, transmittance_texture, - r, mu, mu_s, nu, d_i, ray_r_mu_intersects_ground, rayleigh_i, mie_i); - // Sample weight (from the trapezoidal rule). - Number weight_i = (i == 0 || i == SAMPLE_COUNT) ? 0.5 : 1.0; - rayleigh_sum += rayleigh_i * weight_i; - mie_sum += mie_i * weight_i; - } - rayleigh = rayleigh_sum * dx * atmosphere.solar_irradiance * - atmosphere.rayleigh_scattering; - mie = mie_sum * dx * atmosphere.solar_irradiance * atmosphere.mie_scattering; -} - -void GetRMuMuSNuFromScatteringTextureUvwz(const AtmosphereParameters atmosphere, - const vec4 uvwz, out Length r, out Number mu, out Number mu_s, - out Number nu, out bool ray_r_mu_intersects_ground) { - assert(uvwz.x >= 0.0 && uvwz.x <= 1.0); - assert(uvwz.y >= 0.0 && uvwz.y <= 1.0); - assert(uvwz.z >= 0.0 && uvwz.z <= 1.0); - assert(uvwz.w >= 0.0 && uvwz.w <= 1.0); - - // Distance to top atmosphere boundary for a horizontal ray at ground level. - Length H = sqrt(atmosphere.top_radius * atmosphere.top_radius - - atmosphere.bottom_radius * atmosphere.bottom_radius); - // Distance to the horizon. - Length rho = - H * GetUnitRangeFromTextureCoord(uvwz.w, SCATTERING_TEXTURE_R_SIZE); - r = sqrt(rho * rho + atmosphere.bottom_radius * atmosphere.bottom_radius); - - if (uvwz.z < 0.5) { - // Distance to the ground for the ray (r,mu), and its minimum and maximum - // values over all mu - obtained for (r,-1) and (r,mu_horizon) - from which - // we can recover mu: - Length d_min = r - atmosphere.bottom_radius; - Length d_max = rho; - Length d = d_min + (d_max - d_min) * GetUnitRangeFromTextureCoord( - 1.0 - 2.0 * uvwz.z, SCATTERING_TEXTURE_MU_SIZE / 2); - mu = d == 0.0 * m ? Number(-1.0) : - ClampCosine(-(rho * rho + d * d) / (2.0 * r * d)); - ray_r_mu_intersects_ground = true; - } else { - // Distance to the top atmosphere boundary for the ray (r,mu), and its - // minimum and maximum values over all mu - obtained for (r,1) and - // (r,mu_horizon) - from which we can recover mu: - Length d_min = atmosphere.top_radius - r; - Length d_max = rho + H; - Length d = d_min + (d_max - d_min) * GetUnitRangeFromTextureCoord( - 2.0 * uvwz.z - 1.0, SCATTERING_TEXTURE_MU_SIZE / 2); - mu = d == 0.0 * m ? Number(1.0) : - ClampCosine((H * H - rho * rho - d * d) / (2.0 * r * d)); - ray_r_mu_intersects_ground = false; - } - - Number x_mu_s = - GetUnitRangeFromTextureCoord(uvwz.y, SCATTERING_TEXTURE_MU_S_SIZE); - Length d_min = atmosphere.top_radius - atmosphere.bottom_radius; - Length d_max = H; - Length D = DistanceToTopAtmosphereBoundary( - atmosphere, atmosphere.bottom_radius, atmosphere.mu_s_min); - Number A = (D - d_min) / (d_max - d_min); - Number a = (A - x_mu_s * A) / (1.0 + x_mu_s * A); - Length d = d_min + min(a, A) * (d_max - d_min); - mu_s = d == 0.0 * m ? Number(1.0) : - ClampCosine((H * H - d * d) / (2.0 * atmosphere.bottom_radius * d)); - - nu = ClampCosine(uvwz.x * 2.0 - 1.0); -} - -void GetRMuMuSNuFromScatteringTextureFragCoord( - const AtmosphereParameters atmosphere, const vec3 frag_coord, - out Length r, out Number mu, out Number mu_s, out Number nu, - out bool ray_r_mu_intersects_ground) { - const vec4 SCATTERING_TEXTURE_SIZE = vec4( - SCATTERING_TEXTURE_NU_SIZE - 1, - SCATTERING_TEXTURE_MU_S_SIZE, - SCATTERING_TEXTURE_MU_SIZE, - SCATTERING_TEXTURE_R_SIZE); - Number frag_coord_nu = - floor(frag_coord.x / Number(SCATTERING_TEXTURE_MU_S_SIZE)); - Number frag_coord_mu_s = - mod(frag_coord.x, Number(SCATTERING_TEXTURE_MU_S_SIZE)); - vec4 uvwz = - vec4(frag_coord_nu, frag_coord_mu_s, frag_coord.y, frag_coord.z) / - SCATTERING_TEXTURE_SIZE; - GetRMuMuSNuFromScatteringTextureUvwz( - atmosphere, uvwz, r, mu, mu_s, nu, ray_r_mu_intersects_ground); - // Clamp nu to its valid range of values, given mu and mu_s. - nu = clamp(nu, mu * mu_s - sqrt((1.0 - mu * mu) * (1.0 - mu_s * mu_s)), - mu * mu_s + sqrt((1.0 - mu * mu) * (1.0 - mu_s * mu_s))); -} - -void ComputeSingleScatteringTexture(const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, const vec3 frag_coord, - out IrradianceSpectrum rayleigh, out IrradianceSpectrum mie) { - Length r; - Number mu; - Number mu_s; - Number nu; - bool ray_r_mu_intersects_ground; - GetRMuMuSNuFromScatteringTextureFragCoord(atmosphere, frag_coord, - r, mu, mu_s, nu, ray_r_mu_intersects_ground); - ComputeSingleScattering(atmosphere, transmittance_texture, - r, mu, mu_s, nu, ray_r_mu_intersects_ground, rayleigh, mie); -} - -AbstractSpectrum GetScattering( - const AtmosphereParameters atmosphere, - const AbstractScatteringTexture scattering_texture, - const Length r, const Number mu, const Number mu_s, const Number nu, - const bool ray_r_mu_intersects_ground) { - vec4 uvwz = GetScatteringTextureUvwzFromRMuMuSNu( - atmosphere, r, mu, mu_s, nu, ray_r_mu_intersects_ground); - Number tex_coord_x = uvwz.x * Number(SCATTERING_TEXTURE_NU_SIZE - 1); - Number tex_x = floor(tex_coord_x); - Number lerp = tex_coord_x - tex_x; - vec3 uvw0 = vec3((tex_x + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), - uvwz.z, uvwz.w); - vec3 uvw1 = vec3((tex_x + 1.0 + uvwz.y) / Number(SCATTERING_TEXTURE_NU_SIZE), - uvwz.z, uvwz.w); - return AbstractSpectrum(texture(scattering_texture, uvw0) * (1.0 - lerp) + - texture(scattering_texture, uvw1) * lerp); -} - -RadianceSpectrum GetScattering( - const AtmosphereParameters atmosphere, - const ReducedScatteringTexture single_rayleigh_scattering_texture, - const ReducedScatteringTexture single_mie_scattering_texture, - const ScatteringTexture multiple_scattering_texture, - const Length r, const Number mu, const Number mu_s, const Number nu, - const bool ray_r_mu_intersects_ground, - const int scattering_order) { - if (scattering_order == 1) { - IrradianceSpectrum rayleigh = GetScattering( - atmosphere, single_rayleigh_scattering_texture, r, mu, mu_s, nu, - ray_r_mu_intersects_ground); - IrradianceSpectrum mie = GetScattering( - atmosphere, single_mie_scattering_texture, r, mu, mu_s, nu, - ray_r_mu_intersects_ground); - return rayleigh * RayleighPhaseFunction(nu) + - mie * MiePhaseFunction(atmosphere.mie_phase_function_g, nu); - } else { - return GetScattering( - atmosphere, multiple_scattering_texture, r, mu, mu_s, nu, - ray_r_mu_intersects_ground); - } -} - -IrradianceSpectrum GetIrradiance( - const AtmosphereParameters atmosphere, - const IrradianceTexture irradiance_texture, - const Length r, const Number mu_s); - -RadianceDensitySpectrum ComputeScatteringDensity( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const ReducedScatteringTexture single_rayleigh_scattering_texture, - const ReducedScatteringTexture single_mie_scattering_texture, - const ScatteringTexture multiple_scattering_texture, - const IrradianceTexture irradiance_texture, - const Length r, const Number mu, const Number mu_s, const Number nu, - const int scattering_order) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu >= -1.0 && mu <= 1.0); - assert(mu_s >= -1.0 && mu_s <= 1.0); - assert(nu >= -1.0 && nu <= 1.0); - assert(scattering_order >= 2); - - // Compute unit direction vectors for the zenith, the view direction omega and - // and the sun direction omega_s, such that the cosine of the view-zenith - // angle is mu, the cosine of the sun-zenith angle is mu_s, and the cosine of - // the view-sun angle is nu. The goal is to simplify computations below. - vec3 zenith_direction = vec3(0.0, 0.0, 1.0); - vec3 omega = vec3(sqrt(1.0 - mu * mu), 0.0, mu); - Number sun_dir_x = omega.x == 0.0 ? 0.0 : (nu - mu * mu_s) / omega.x; - Number sun_dir_y = sqrt(max(1.0 - sun_dir_x * sun_dir_x - mu_s * mu_s, 0.0)); - vec3 omega_s = vec3(sun_dir_x, sun_dir_y, mu_s); - - const int SAMPLE_COUNT = 16; - const Angle dphi = pi / Number(SAMPLE_COUNT); - const Angle dtheta = pi / Number(SAMPLE_COUNT); - RadianceDensitySpectrum rayleigh_mie = - RadianceDensitySpectrum(0.0 * watt_per_cubic_meter_per_sr_per_nm); - - // Nested loops for the integral over all the incident directions omega_i. - for (int l = 0; l < SAMPLE_COUNT; ++l) { - Angle theta = (Number(l) + 0.5) * dtheta; - Number cos_theta = cos(theta); - Number sin_theta = sin(theta); - bool ray_r_theta_intersects_ground = - RayIntersectsGround(atmosphere, r, cos_theta); - - // The distance and transmittance to the ground only depend on theta, so we - // can compute them in the outer loop for efficiency. - Length distance_to_ground = 0.0 * m; - DimensionlessSpectrum transmittance_to_ground = DimensionlessSpectrum(0.0); - DimensionlessSpectrum ground_albedo = DimensionlessSpectrum(0.0); - if (ray_r_theta_intersects_ground) { - distance_to_ground = - DistanceToBottomAtmosphereBoundary(atmosphere, r, cos_theta); - transmittance_to_ground = - GetTransmittance(atmosphere, transmittance_texture, r, cos_theta, - distance_to_ground, true /* ray_intersects_ground */); - ground_albedo = atmosphere.ground_albedo; - } - - for (int m = 0; m < 2 * SAMPLE_COUNT; ++m) { - Angle phi = (Number(m) + 0.5) * dphi; - vec3 omega_i = - vec3(cos(phi) * sin_theta, sin(phi) * sin_theta, cos_theta); - SolidAngle domega_i = (dtheta / rad) * (dphi / rad) * sin(theta) * sr; - - // The radiance L_i arriving from direction omega_i after n-1 bounces is - // the sum of a term given by the precomputed scattering texture for the - // (n-1)-th order: - Number nu1 = dot(omega_s, omega_i); - RadianceSpectrum incident_radiance = GetScattering(atmosphere, - single_rayleigh_scattering_texture, single_mie_scattering_texture, - multiple_scattering_texture, r, omega_i.z, mu_s, nu1, - ray_r_theta_intersects_ground, scattering_order - 1); - - // and of the contribution from the light paths with n-1 bounces and whose - // last bounce is on the ground. This contribution is the product of the - // transmittance to the ground, the ground albedo, the ground BRDF, and - // the irradiance received on the ground after n-2 bounces. - vec3 ground_normal = - normalize(zenith_direction * r + omega_i * distance_to_ground); - IrradianceSpectrum ground_irradiance = GetIrradiance( - atmosphere, irradiance_texture, atmosphere.bottom_radius, - dot(ground_normal, omega_s)); - incident_radiance += transmittance_to_ground * - ground_albedo * (1.0 / (PI * sr)) * ground_irradiance; - - // The radiance finally scattered from direction omega_i towards direction - // -omega is the product of the incident radiance, the scattering - // coefficient, and the phase function for directions omega and omega_i - // (all this summed over all particle types, i.e. Rayleigh and Mie). - Number nu2 = dot(omega, omega_i); - Number rayleigh_density = GetProfileDensity( - atmosphere.rayleigh_density, r - atmosphere.bottom_radius); - Number mie_density = GetProfileDensity( - atmosphere.mie_density, r - atmosphere.bottom_radius); - rayleigh_mie += incident_radiance * ( - atmosphere.rayleigh_scattering * rayleigh_density * - RayleighPhaseFunction(nu2) + - atmosphere.mie_scattering * mie_density * - MiePhaseFunction(atmosphere.mie_phase_function_g, nu2)) * - domega_i; - } - } - return rayleigh_mie; -} - -RadianceSpectrum ComputeMultipleScattering( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const ScatteringDensityTexture scattering_density_texture, - const Length r, const Number mu, const Number mu_s, const Number nu, - const bool ray_r_mu_intersects_ground) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu >= -1.0 && mu <= 1.0); - assert(mu_s >= -1.0 && mu_s <= 1.0); - assert(nu >= -1.0 && nu <= 1.0); - - // Number of intervals for the numerical integration. - const int SAMPLE_COUNT = 50; - // The integration step, i.e. the length of each integration interval. - Length dx = - DistanceToNearestAtmosphereBoundary( - atmosphere, r, mu, ray_r_mu_intersects_ground) / - Number(SAMPLE_COUNT); - // Integration loop. - RadianceSpectrum rayleigh_mie_sum = - RadianceSpectrum(0.0 * watt_per_square_meter_per_sr_per_nm); - for (int i = 0; i <= SAMPLE_COUNT; ++i) { - Length d_i = Number(i) * dx; - - // The r, mu and mu_s parameters at the current integration point (see the - // single scattering section for a detailed explanation). - Length r_i = - ClampRadius(atmosphere, sqrt(d_i * d_i + 2.0 * r * mu * d_i + r * r)); - Number mu_i = ClampCosine((r * mu + d_i) / r_i); - Number mu_s_i = ClampCosine((r * mu_s + d_i * nu) / r_i); - - // The Rayleigh and Mie multiple scattering at the current sample point. - RadianceSpectrum rayleigh_mie_i = - GetScattering( - atmosphere, scattering_density_texture, r_i, mu_i, mu_s_i, nu, - ray_r_mu_intersects_ground) * - GetTransmittance( - atmosphere, transmittance_texture, r, mu, d_i, - ray_r_mu_intersects_ground) * - dx; - // Sample weight (from the trapezoidal rule). - Number weight_i = (i == 0 || i == SAMPLE_COUNT) ? 0.5 : 1.0; - rayleigh_mie_sum += rayleigh_mie_i * weight_i; - } - return rayleigh_mie_sum; -} - -RadianceDensitySpectrum ComputeScatteringDensityTexture( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const ReducedScatteringTexture single_rayleigh_scattering_texture, - const ReducedScatteringTexture single_mie_scattering_texture, - const ScatteringTexture multiple_scattering_texture, - const IrradianceTexture irradiance_texture, - const vec3 frag_coord, const int scattering_order) { - Length r; - Number mu; - Number mu_s; - Number nu; - bool ray_r_mu_intersects_ground; - GetRMuMuSNuFromScatteringTextureFragCoord(atmosphere, frag_coord, - r, mu, mu_s, nu, ray_r_mu_intersects_ground); - return ComputeScatteringDensity(atmosphere, transmittance_texture, - single_rayleigh_scattering_texture, single_mie_scattering_texture, - multiple_scattering_texture, irradiance_texture, r, mu, mu_s, nu, - scattering_order); -} - -RadianceSpectrum ComputeMultipleScatteringTexture( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const ScatteringDensityTexture scattering_density_texture, - const vec3 frag_coord, out Number nu) { - Length r; - Number mu; - Number mu_s; - bool ray_r_mu_intersects_ground; - GetRMuMuSNuFromScatteringTextureFragCoord(atmosphere, frag_coord, - r, mu, mu_s, nu, ray_r_mu_intersects_ground); - return ComputeMultipleScattering(atmosphere, transmittance_texture, - scattering_density_texture, r, mu, mu_s, nu, - ray_r_mu_intersects_ground); -} - -IrradianceSpectrum ComputeDirectIrradiance( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const Length r, const Number mu_s) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu_s >= -1.0 && mu_s <= 1.0); - - Number alpha_s = atmosphere.sun_angular_radius / rad; - // Approximate average of the cosine factor mu_s over the visible fraction of - // the Sun disc. - Number average_cosine_factor = - mu_s < -alpha_s ? 0.0 : (mu_s > alpha_s ? mu_s : - (mu_s + alpha_s) * (mu_s + alpha_s) / (4.0 * alpha_s)); - - return atmosphere.solar_irradiance * - GetTransmittanceToTopAtmosphereBoundary( - atmosphere, transmittance_texture, r, mu_s) * average_cosine_factor; - -} - -IrradianceSpectrum ComputeIndirectIrradiance( - const AtmosphereParameters atmosphere, - const ReducedScatteringTexture single_rayleigh_scattering_texture, - const ReducedScatteringTexture single_mie_scattering_texture, - const ScatteringTexture multiple_scattering_texture, - const Length r, const Number mu_s, const int scattering_order) { - assert(r >= atmosphere.bottom_radius && r <= atmosphere.top_radius); - assert(mu_s >= -1.0 && mu_s <= 1.0); - assert(scattering_order >= 1); - - const int SAMPLE_COUNT = 32; - const Angle dphi = pi / Number(SAMPLE_COUNT); - const Angle dtheta = pi / Number(SAMPLE_COUNT); - - IrradianceSpectrum result = - IrradianceSpectrum(0.0 * watt_per_square_meter_per_nm); - vec3 omega_s = vec3(sqrt(1.0 - mu_s * mu_s), 0.0, mu_s); - for (int j = 0; j < SAMPLE_COUNT / 2; ++j) { - Angle theta = (Number(j) + 0.5) * dtheta; - for (int i = 0; i < 2 * SAMPLE_COUNT; ++i) { - Angle phi = (Number(i) + 0.5) * dphi; - vec3 omega = - vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); - SolidAngle domega = (dtheta / rad) * (dphi / rad) * sin(theta) * sr; - - Number nu = dot(omega, omega_s); - result += GetScattering(atmosphere, single_rayleigh_scattering_texture, - single_mie_scattering_texture, multiple_scattering_texture, - r, omega.z, mu_s, nu, false /* ray_r_theta_intersects_ground */, - scattering_order) * - omega.z * domega; - } - } - return result; -} - -void GetRMuSFromIrradianceTextureUv(const AtmosphereParameters atmosphere, - const vec2 uv, out Length r, out Number mu_s) { - assert(uv.x >= 0.0 && uv.x <= 1.0); - assert(uv.y >= 0.0 && uv.y <= 1.0); - Number x_mu_s = GetUnitRangeFromTextureCoord(uv.x, IRRADIANCE_TEXTURE_WIDTH); - Number x_r = GetUnitRangeFromTextureCoord(uv.y, IRRADIANCE_TEXTURE_HEIGHT); - r = atmosphere.bottom_radius + - x_r * (atmosphere.top_radius - atmosphere.bottom_radius); - mu_s = ClampCosine(2.0 * x_mu_s - 1.0); -} - -const vec2 IRRADIANCE_TEXTURE_SIZE = - vec2(IRRADIANCE_TEXTURE_WIDTH, IRRADIANCE_TEXTURE_HEIGHT); - -IrradianceSpectrum ComputeDirectIrradianceTexture( - const AtmosphereParameters atmosphere, - const TransmittanceTexture transmittance_texture, - const vec2 frag_coord) { - Length r; - Number mu_s; - GetRMuSFromIrradianceTextureUv( - atmosphere, frag_coord / IRRADIANCE_TEXTURE_SIZE, r, mu_s); - return ComputeDirectIrradiance(atmosphere, transmittance_texture, r, mu_s); -} - -IrradianceSpectrum ComputeIndirectIrradianceTexture( - const AtmosphereParameters atmosphere, - const ReducedScatteringTexture single_rayleigh_scattering_texture, - const ReducedScatteringTexture single_mie_scattering_texture, - const ScatteringTexture multiple_scattering_texture, - const vec2 frag_coord, const int scattering_order) { - Length r; - Number mu_s; - GetRMuSFromIrradianceTextureUv( - atmosphere, frag_coord / IRRADIANCE_TEXTURE_SIZE, r, mu_s); - return ComputeIndirectIrradiance(atmosphere, - single_rayleigh_scattering_texture, single_mie_scattering_texture, - multiple_scattering_texture, r, mu_s, scattering_order); -} -`,rne=new L(.2126,.7152,.0722),sne=["solarIrradiance","sunAngularRadius","bottomRadius","topRadius","rayleighDensity","rayleighScattering","mieDensity","mieScattering","mieExtinction","miePhaseFunctionG","absorptionDensity","absorptionExtinction","groundAlbedo","muSMin","skyRadianceToLuminance","sunRadianceToLuminance"];function one(n,e){if(e!=null)for(const t of sne){const i=e[t];i!=null&&(n[t]instanceof L?n[t].copy(i):n[t]=i)}}class Sf{constructor(e,t,i,a,r){this.width=e,this.expTerm=t,this.expScale=i,this.linearTerm=a,this.constantTerm=r}toUniform(){return new J({width:this.width,exp_term:this.expTerm,exp_scale:this.expScale,linear_term:this.linearTerm,constant_term:this.constantTerm})}}const XE=class{constructor(e){this.solarIrradiance=new L(1.474,1.8504,1.91198),this.sunAngularRadius=.004675,this.bottomRadius=636e4,this.topRadius=642e4,this.rayleighDensity=[new Sf(0,0,0,0,0),new Sf(0,1,-.125,0,0)],this.rayleighScattering=new L(.005802,.013558,.0331),this.mieDensity=[new Sf(0,0,0,0,0),new Sf(0,1,-.833333,0,0)],this.mieScattering=new L(.003996,.003996,.003996),this.mieExtinction=new L(.00444,.00444,.00444),this.miePhaseFunctionG=.8,this.absorptionDensity=[new Sf(25,0,0,1/15,-2/3),new Sf(0,0,0,-1/15,8/3)],this.absorptionExtinction=new L(65e-5,.001881,85e-6),this.groundAlbedo=new je().setScalar(.1),this.muSMin=Math.cos(Ute(120)),this.sunRadianceToLuminance=new L(98242.786222,69954.398112,66475.012354),this.skyRadianceToLuminance=new L(114974.916437,71305.954816,65310.548555),this.sunRadianceToRelativeLuminance=new L,this.skyRadianceToRelativeLuminance=new L,one(this,e);const t=rne.dot(this.sunRadianceToLuminance);this.sunRadianceToRelativeLuminance.copy(this.sunRadianceToLuminance).divideScalar(t),this.skyRadianceToRelativeLuminance.copy(this.skyRadianceToLuminance).divideScalar(t)}toUniform(){return new J({solar_irradiance:this.solarIrradiance,sun_angular_radius:this.sunAngularRadius,bottom_radius:this.bottomRadius*a1,top_radius:this.topRadius*a1,rayleigh_density:{layers:this.rayleighDensity.map(e=>e.toUniform().value)},rayleigh_scattering:this.rayleighScattering,mie_density:{layers:this.mieDensity.map(e=>e.toUniform().value)},mie_scattering:this.mieScattering,mie_extinction:this.mieExtinction,mie_phase_function_g:this.miePhaseFunctionG,absorption_density:{layers:this.absorptionDensity.map(e=>e.toUniform().value)},absorption_extinction:this.absorptionExtinction,ground_albedo:this.groundAlbedo,mu_s_min:this.muSMin})}};XE.DEFAULT=new XE;let j0=XE;const lne=`precision highp sampler2DArray; - -#include "core/depth" -#include "core/math" -#include "core/packing" -#include "core/transform" -#ifdef HAS_SHADOW -#include "core/raySphereIntersection" -#include "core/cascadedShadowMaps" -#include "core/interleavedGradientNoise" -#include "core/vogelDisk" -#endif // HAS_SHADOW - -#include "bruneton/definitions" - -uniform AtmosphereParameters ATMOSPHERE; -uniform vec3 SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; -uniform vec3 SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; - -uniform sampler2D transmittance_texture; -uniform sampler3D scattering_texture; -uniform sampler2D irradiance_texture; -uniform sampler3D single_mie_scattering_texture; -uniform sampler3D higher_order_scattering_texture; - -#include "bruneton/common" -#include "bruneton/runtime" - -#include "sky" - -uniform sampler2D normalBuffer; - -uniform mat4 projectionMatrix; -uniform mat4 viewMatrix; -uniform mat4 inverseProjectionMatrix; -uniform mat4 inverseViewMatrix; -uniform float bottomRadius; -uniform mat4 worldToECEFMatrix; -uniform float geometricErrorCorrectionAmount; -uniform vec3 sunDirection; -uniform vec3 moonDirection; -uniform float moonAngularRadius; -uniform float lunarRadianceScale; -uniform float albedoScale; - -#ifdef HAS_LIGHTING_MASK -uniform sampler2D lightingMaskBuffer; -#endif // HAS_LIGHTING_MASK - -// prettier-ignore -#define LIGHTING_MASK_CHANNEL_ LIGHTING_MASK_CHANNEL - -#ifdef HAS_OVERLAY -uniform sampler2D overlayBuffer; -#endif // HAS_OVERLAY - -#ifdef HAS_SHADOW -uniform sampler2DArray shadowBuffer; -uniform vec2 shadowIntervals[SHADOW_CASCADE_COUNT]; -uniform mat4 shadowMatrices[SHADOW_CASCADE_COUNT]; -uniform mat4 inverseShadowMatrices[SHADOW_CASCADE_COUNT]; -uniform float shadowFar; -uniform float shadowTopHeight; -uniform float shadowRadius; -uniform sampler3D stbnTexture; -uniform int frame; -#endif // HAS_SHADOW - -#ifdef HAS_SHADOW_LENGTH -uniform sampler2D shadowLengthBuffer; -#endif // HAS_SHADOW_LENGTH - -varying vec3 vCameraPosition; -varying vec3 vRayDirection; -varying vec3 vGeometryAltitudeCorrection; -varying vec3 vEllipsoidRadiiSquared; - -vec3 readNormal(const vec2 uv) { - #ifdef OCT_ENCODED_NORMAL - return unpackVec2ToNormal(texture(normalBuffer, uv).xy); - #else // OCT_ENCODED_NORMAL - return 2.0 * texture(normalBuffer, uv).xyz - 1.0; - #endif // OCT_ENCODED_NORMAL -} - -void correctGeometricError(inout vec3 positionECEF, inout vec3 normalECEF) { - // TODO: The error is pronounced at the edge of the ellipsoid due to the - // large difference between the sphere position and the unprojected position - // at the current fragment. Calculating the sphere position from the fragment - // UV may resolve this. - - // Correct way is slerp, but this will be small-angle interpolation anyways. - vec3 sphereNormal = normalize(positionECEF / vEllipsoidRadiiSquared); - vec3 spherePosition = ATMOSPHERE.bottom_radius * sphereNormal; - normalECEF = mix(normalECEF, sphereNormal, geometricErrorCorrectionAmount); - positionECEF = mix(positionECEF, spherePosition, geometricErrorCorrectionAmount); -} - -#if defined(SUN_LIGHT) || defined(SKY_LIGHT) - -vec3 getSunSkyIrradiance( - const vec3 positionECEF, - const vec3 normal, - const vec3 inputColor, - const float sunTransmittance -) { - // Assume lambertian BRDF. If both SUN_LIGHT and SKY_LIGHT are not defined, - // regard the inputColor as radiance at the texel. - vec3 diffuse = inputColor * albedoScale * RECIPROCAL_PI; - vec3 skyIrradiance; - vec3 sunIrradiance = GetSunAndSkyIrradiance(positionECEF, normal, sunDirection, skyIrradiance); - - #ifdef HAS_SHADOW - sunIrradiance *= sunTransmittance; - #endif // HAS_SHADOW - - #if defined(SUN_LIGHT) && defined(SKY_LIGHT) - return diffuse * (sunIrradiance + skyIrradiance); - #elif defined(SUN_LIGHT) - return diffuse * sunIrradiance; - #elif defined(SKY_LIGHT) - return diffuse * skyIrradiance; - #endif // defined(SUN_LIGHT) && defined(SKY_LIGHT) -} - -#endif // defined(SUN_LIGHT) || defined(SKY_LIGHT) - -#if defined(TRANSMITTANCE) || defined(INSCATTER) - -void applyTransmittanceInscatter(const vec3 positionECEF, float shadowLength, inout vec3 radiance) { - vec3 transmittance; - vec3 inscatter = GetSkyRadianceToPoint( - vCameraPosition, - positionECEF, - shadowLength, - sunDirection, - transmittance - ); - #ifdef TRANSMITTANCE - radiance = radiance * transmittance; - #endif // TRANSMITTANCE - #ifdef INSCATTER - radiance = radiance + inscatter; - #endif // INSCATTER -} - -#endif // defined(TRANSMITTANCE) || defined(INSCATTER) - -#ifdef HAS_SHADOW - -float getSTBN() { - ivec3 size = textureSize(stbnTexture, 0); - vec3 scale = 1.0 / vec3(size); - return texture(stbnTexture, vec3(gl_FragCoord.xy, float(frame % size.z)) * scale).r; -} - -vec2 getShadowUv(const vec3 worldPosition, const int cascadeIndex) { - vec4 clip = shadowMatrices[cascadeIndex] * vec4(worldPosition, 1.0); - clip /= clip.w; - return clip.xy * 0.5 + 0.5; -} - -float getDistanceToShadowTop(const vec3 positionECEF) { - // Distance to the top of the shadows along the sun direction, which matches - // the ray origin of BSM. - return raySphereSecondIntersection( - positionECEF / METER_TO_LENGTH_UNIT, // TODO: Make units consistent - sunDirection, - vec3(0.0), - bottomRadius + shadowTopHeight - ); -} - -float readShadowOpticalDepth(const vec2 uv, const float distanceToTop, const int cascadeIndex) { - // r: frontDepth, g: meanExtinction, b: maxOpticalDepth, a: maxOpticalDepthTail - vec4 shadow = texture(shadowBuffer, vec3(uv, float(cascadeIndex))); - // Omit adding maxOpticalDepthTail to avoid pronounced aliasing. Ground - // shadow will be attenuated by inscatter anyways. - return min(shadow.b, shadow.g * max(0.0, distanceToTop - shadow.r)); -} - -float sampleShadowOpticalDepthPCF( - const vec3 worldPosition, - const float distanceToTop, - const float radius, - const int cascadeIndex -) { - vec2 uv = getShadowUv(worldPosition, cascadeIndex); - if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { - return 0.0; - } - - vec2 texelSize = vec2(1.0) / vec2(textureSize(shadowBuffer, 0).xy); - float sum = 0.0; - vec2 offset; - #pragma unroll_loop_start - for (int i = 0; i < 16; ++i) { - #if UNROLLED_LOOP_INDEX < SHADOW_SAMPLE_COUNT - offset = vogelDisk( - UNROLLED_LOOP_INDEX, - SHADOW_SAMPLE_COUNT, - interleavedGradientNoise(gl_FragCoord.xy) * PI2 - ); - sum += readShadowOpticalDepth(uv + offset * radius * texelSize, distanceToTop, cascadeIndex); - #endif // UNROLLED_LOOP_INDEX < SHADOW_SAMPLE_COUNT - } - #pragma unroll_loop_end - return sum / float(SHADOW_SAMPLE_COUNT); -} - -float sampleShadowOpticalDepth( - const vec3 worldPosition, - const vec3 positionECEF, - const float radius, - const float jitter -) { - float distanceToTop = getDistanceToShadowTop(positionECEF); - if (distanceToTop <= 0.0) { - return 0.0; - } - int cascadeIndex = getFadedCascadeIndex( - viewMatrix, - worldPosition, - shadowIntervals, - cameraNear, - shadowFar, - jitter - ); - return cascadeIndex >= 0 - ? sampleShadowOpticalDepthPCF(worldPosition, distanceToTop, radius, cascadeIndex) - : 0.0; -} - -float getShadowRadius(const vec3 worldPosition) { - vec4 clip = shadowMatrices[0] * vec4(worldPosition, 1.0); - clip /= clip.w; - - // Offset by 1px in each direction in shadow's clip coordinates. - vec2 shadowSize = vec2(textureSize(shadowBuffer, 0)); - vec3 offset = vec3(2.0 / shadowSize, 0.0); - vec4 clipX = clip + offset.xzzz; - vec4 clipY = clip + offset.zyzz; - - // Convert back to world space. - vec4 worldX = inverseShadowMatrices[0] * clipX; - vec4 worldY = inverseShadowMatrices[0] * clipY; - - // Project into the main camera's clip space. - mat4 viewProjectionMatrix = projectionMatrix * viewMatrix; - vec4 projected = viewProjectionMatrix * vec4(worldPosition, 1.0); - vec4 projectedX = viewProjectionMatrix * worldX; - vec4 projectedY = viewProjectionMatrix * worldY; - projected /= projected.w; - projectedX /= projectedX.w; - projectedY /= projectedY.w; - - // Take the mean of pixel sizes. - vec2 center = (projected.xy * 0.5 + 0.5) * resolution; - vec2 offsetX = (projectedX.xy * 0.5 + 0.5) * resolution; - vec2 offsetY = (projectedY.xy * 0.5 + 0.5) * resolution; - float size = max(length(offsetX - center), length(offsetY - center)); - - return remapClamped(size, 10.0, 50.0, 0.0, shadowRadius); -} - -#endif // HAS_SHADOW - -void mainImage(const vec4 inputColor, const vec2 uv, out vec4 outputColor) { - #if defined(HAS_LIGHTING_MASK) && defined(DEBUG_SHOW_LIGHTING_MASK) - outputColor.rgb = vec3(texture(lightingMaskBuffer, uv).LIGHTING_MASK_CHANNEL_); - outputColor.a = 1.0; - return; - #endif // defined(HAS_LIGHTING_MASK) && defined(DEBUG_SHOW_LIGHTING_MASK) - - float shadowLength = 0.0; - #ifdef HAS_SHADOW_LENGTH - shadowLength = texture(shadowLengthBuffer, uv).r; - #endif // HAS_SHADOW_LENGTH - - #ifdef HAS_OVERLAY - vec4 overlay = texture(overlayBuffer, uv); - if (overlay.a == 1.0) { - outputColor = overlay; - return; - } - #endif // HAS_OVERLAY - - float depth = readDepth(uv); - if (depth >= 1.0 - 1e-8) { - #ifdef SKY - vec3 rayDirection = normalize(vRayDirection); - outputColor.rgb = getSkyRadiance( - vCameraPosition, - rayDirection, - shadowLength, - sunDirection, - moonDirection, - moonAngularRadius, - lunarRadianceScale - ); - outputColor.a = 1.0; - #else // SKY - outputColor = inputColor; - #endif // SKY - - #ifdef HAS_OVERLAY - outputColor.rgb = outputColor.rgb * (1.0 - overlay.a) + overlay.rgb; - #endif // HAS_OVERLAY - return; - } - depth = reverseLogDepth(depth, cameraNear, cameraFar); - - // Reconstruct position and normal in world space. - vec3 viewPosition = screenToView( - uv, - depth, - getViewZ(depth), - projectionMatrix, - inverseProjectionMatrix - ); - vec3 viewNormal; - #ifdef RECONSTRUCT_NORMAL - vec3 dx = dFdx(viewPosition); - vec3 dy = dFdy(viewPosition); - viewNormal = normalize(cross(dx, dy)); - #else // RECONSTRUCT_NORMAL - viewNormal = readNormal(uv); - #endif // RECONSTRUCT_NORMAL - - vec3 worldPosition = (inverseViewMatrix * vec4(viewPosition, 1.0)).xyz; - vec3 worldNormal = (inverseViewMatrix * vec4(viewNormal, 0.0)).xyz; - vec3 positionECEF = (worldToECEFMatrix * vec4(worldPosition, 1.0)).xyz; - positionECEF = positionECEF * METER_TO_LENGTH_UNIT + vGeometryAltitudeCorrection; - vec3 normalECEF = (worldToECEFMatrix * vec4(worldNormal, 0.0)).xyz; - - #ifdef CORRECT_GEOMETRIC_ERROR - correctGeometricError(positionECEF, normalECEF); - #endif // CORRECT_GEOMETRIC_ERROR - - #ifdef HAS_SHADOW - float stbn = getSTBN(); - float radius = getShadowRadius(worldPosition); - float opticalDepth = sampleShadowOpticalDepth(worldPosition, positionECEF, radius, stbn); - float sunTransmittance = exp(-opticalDepth); - #else // HAS_SHADOW - float sunTransmittance = 1.0; - #endif // HAS_SHADOW - - vec3 radiance; - #if defined(SUN_LIGHT) || defined(SKY_LIGHT) - radiance = getSunSkyIrradiance(positionECEF, normalECEF, inputColor.rgb, sunTransmittance); - #ifdef HAS_LIGHTING_MASK - float lightingMask = texture(lightingMaskBuffer, uv).LIGHTING_MASK_CHANNEL_; - radiance = mix(inputColor.rgb, radiance, lightingMask); - #endif // HAS_LIGHTING_MASK - #else // defined(SUN_LIGHT) || defined(SKY_LIGHT) - radiance = inputColor.rgb; - #endif // defined(SUN_LIGHT) || defined(SKY_LIGHT) - - #if defined(TRANSMITTANCE) || defined(INSCATTER) - applyTransmittanceInscatter(positionECEF, shadowLength, radiance); - #endif // defined(TRANSMITTANCE) || defined(INSCATTER) - - outputColor = vec4(radiance, inputColor.a); - - #ifdef HAS_OVERLAY - outputColor.rgb = outputColor.rgb * (1.0 - overlay.a) + overlay.rgb; - #endif // HAS_OVERLAY -} -`,cne=`uniform mat4 inverseViewMatrix; -uniform mat4 inverseProjectionMatrix; -uniform vec3 cameraPosition; -uniform mat4 worldToECEFMatrix; -uniform vec3 altitudeCorrection; -uniform float geometricErrorCorrectionAmount; -uniform vec3 ellipsoidRadii; - -varying vec3 vCameraPosition; -varying vec3 vRayDirection; -varying vec3 vGeometryAltitudeCorrection; -varying vec3 vEllipsoidRadiiSquared; - -void getCameraRay(out vec3 origin, out vec3 direction) { - bool isPerspective = inverseProjectionMatrix[2][3] != 0.0; // 4th entry in the 3rd column - - if (isPerspective) { - // Calculate the camera ray for a perspective camera. - vec4 viewPosition = inverseProjectionMatrix * vec4(position, 1.0); - vec4 worldDirection = inverseViewMatrix * vec4(viewPosition.xyz, 0.0); - origin = cameraPosition; - direction = worldDirection.xyz; - } else { - // Unprojected points to calculate direction. - vec4 nearPoint = inverseProjectionMatrix * vec4(position.xy, -1.0, 1.0); - vec4 farPoint = inverseProjectionMatrix * vec4(position.xy, -0.9, 1.0); - nearPoint /= nearPoint.w; - farPoint /= farPoint.w; - - // Calculate world values. - vec4 worldDirection = inverseViewMatrix * vec4(farPoint.xyz - nearPoint.xyz, 0.0); - vec4 worldOrigin = inverseViewMatrix * nearPoint; - - // Outputs - direction = worldDirection.xyz; - origin = worldOrigin.xyz; - } -} - -void mainSupport() { - vec3 direction, origin; - getCameraRay(origin, direction); - - vec3 cameraPositionECEF = (worldToECEFMatrix * vec4(origin, 1.0)).xyz; - vCameraPosition = (cameraPositionECEF + altitudeCorrection) * METER_TO_LENGTH_UNIT; - vRayDirection = (worldToECEFMatrix * vec4(direction, 0.0)).xyz; - - vGeometryAltitudeCorrection = altitudeCorrection * METER_TO_LENGTH_UNIT; - // Gradually turn off the altitude correction on geometries as the geometric - // error correction takes effect, because that on the ideal sphere will be - // over corrected. - // See: https://github.com/takram-design-engineering/three-geospatial/pull/23#issuecomment-2542914656 - #ifdef CORRECT_GEOMETRIC_ERROR - vGeometryAltitudeCorrection *= 1.0 - geometricErrorCorrectionAmount; - #endif // CORRECT_GEOMETRIC_ERROR - - vec3 radii = ellipsoidRadii * METER_TO_LENGTH_UNIT; - vEllipsoidRadiiSquared = radii * radii; -} -`,PP=`vec3 getLunarRadiance(const float moonAngularRadius) { - // Not a physical number but the order of 10^-6 relative to the sun may fit. - vec3 radiance = - ATMOSPHERE.solar_irradiance * - 0.000002 / - (PI * moonAngularRadius * moonAngularRadius) * - SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; - return radiance; -} - -float intersectSphere(const vec3 ray, const vec3 point, const float radius) { - vec3 P = -point; - float PoR = dot(P, ray); - float D = dot(P, P) - radius * radius; - return -PoR - sqrt(PoR * PoR - D); -} - -float orenNayarDiffuse(const vec3 L, const vec3 V, const vec3 N) { - float NoL = dot(N, L); - float NoV = dot(N, V); - float s = dot(L, V) - NoL * NoV; - float t = mix(1.0, max(NoL, NoV), step(0.0, s)); - return max(0.0, NoL) * (0.62406015 + 0.41284404 * s / t); -} - -vec3 getSkyRadiance( - const vec3 cameraPosition, - const vec3 rayDirection, - const float shadowLength, - const vec3 sunDirection, - const vec3 moonDirection, - const float moonAngularRadius, - const float lunarRadianceScale -) { - vec3 transmittance; - vec3 radiance = GetSkyRadiance( - cameraPosition, - rayDirection, - shadowLength, - sunDirection, - transmittance - ); - - // Rendering celestial objects without perspective doesn't make sense. - #ifdef PERSPECTIVE_CAMERA - - #if defined(SUN) || defined(MOON) - vec3 ddx = dFdx(rayDirection); - vec3 ddy = dFdy(rayDirection); - float fragmentAngle = length(ddx + ddy) / length(rayDirection); - #endif // defined(SUN) || defined(MOON) - - #ifdef SUN - float viewDotSun = dot(rayDirection, sunDirection); - if (viewDotSun > cos(ATMOSPHERE.sun_angular_radius)) { - float angle = acos(clamp(viewDotSun, -1.0, 1.0)); - float antialias = smoothstep( - ATMOSPHERE.sun_angular_radius, - ATMOSPHERE.sun_angular_radius - fragmentAngle, - angle - ); - radiance += transmittance * GetSolarRadiance() * antialias; - } - #endif // SUN - - #ifdef MOON - float intersection = intersectSphere(rayDirection, moonDirection, moonAngularRadius); - if (intersection > 0.0) { - vec3 normal = normalize(moonDirection - rayDirection * intersection); - float diffuse = orenNayarDiffuse(-sunDirection, rayDirection, normal); - float viewDotMoon = dot(rayDirection, moonDirection); - float angle = acos(clamp(viewDotMoon, -1.0, 1.0)); - float antialias = smoothstep(moonAngularRadius, moonAngularRadius - fragmentAngle, angle); - radiance += - transmittance * - getLunarRadiance(moonAngularRadius) * - lunarRadianceScale * - diffuse * - antialias; - } - #endif // MOON - - #endif // PERSPECTIVE_CAMERA - - return radiance; -} -`;var une=Object.defineProperty,ar=(n,e,t,i)=>{for(var a=void 0,r=n.length-1,s;r>=0;r--)(s=n[r])&&(a=s(e,t,a)||a);return a&&une(e,t,a),a};const hne=new L,fne=new L,dne=new Z8,zP={blendFunction:ln.NORMAL,octEncodedNormal:!1,reconstructNormal:!1,ellipsoid:_0.WGS84,correctAltitude:!0,correctGeometricError:!0,sunLight:!1,skyLight:!1,transmittance:!0,inscatter:!0,albedoScale:1,sky:!1,sun:!0,moon:!0,moonAngularRadius:.0045,lunarRadianceScale:1,ground:!0};let Ba=class extends v0{constructor(e=new bc,t,i=j0.DEFAULT){const{blendFunction:a,normalBuffer:r=null,octEncodedNormal:s,reconstructNormal:o,irradianceTexture:c=null,scatteringTexture:h=null,transmittanceTexture:f=null,singleMieScatteringTexture:d=null,higherOrderScatteringTexture:m=null,ellipsoid:g,correctAltitude:x,correctGeometricError:T,sunDirection:y,sunIrradiance:v,sunLight:S,skyIrradiance:E,skyLight:b,transmittance:D,inscatter:C,irradianceScale:I,albedoScale:P,sky:O,sun:w,moon:B,moonDirection:j,moonAngularRadius:ee,lunarRadianceScale:se,ground:re}={...zP,...t};super("AerialPerspectiveEffect",q0(Na(lne,{core:{depth:OP,packing:ene,math:_A,transform:tne,raySphereIntersection:my,cascadedShadowMaps:DP,interleavedGradientNoise:LP,vogelDisk:UP},bruneton:{common:Ks,definitions:Qs,runtime:yy},sky:PP})),{blendFunction:a,vertexShader:cne,attributes:$o.DEPTH,uniforms:new Map(Object.entries({normalBuffer:new J(r),projectionMatrix:new J(new ke),viewMatrix:new J(new ke),inverseProjectionMatrix:new J(new ke),inverseViewMatrix:new J(new ke),cameraPosition:new J(new L),bottomRadius:new J(i.bottomRadius),ellipsoidRadii:new J(new L),worldToECEFMatrix:new J(new ke),altitudeCorrection:new J(new L),geometricErrorCorrectionAmount:new J(0),sunDirection:new J((y==null?void 0:y.clone())??new L),albedoScale:new J(I??P),moonDirection:new J((j==null?void 0:j.clone())??new L),moonAngularRadius:new J(ee),lunarRadianceScale:new J(se),overlayBuffer:new J(null),shadowBuffer:new J(null),shadowMapSize:new J(new de),shadowIntervals:new J([]),shadowMatrices:new J([]),inverseShadowMatrices:new J([]),shadowFar:new J(0),shadowTopHeight:new J(0),shadowRadius:new J(3),stbnTexture:new J(null),frame:new J(0),shadowLengthBuffer:new J(null),lightingMaskBuffer:new J(null),ATMOSPHERE:i.toUniform(),SUN_SPECTRAL_RADIANCE_TO_LUMINANCE:new J(i.sunRadianceToRelativeLuminance),SKY_SPECTRAL_RADIANCE_TO_LUMINANCE:new J(i.skyRadianceToRelativeLuminance),irradiance_texture:new J(c),scattering_texture:new J(h),transmittance_texture:new J(f),single_mie_scattering_texture:new J(null),higher_order_scattering_texture:new J(null)})),defines:new Map([["TRANSMITTANCE_TEXTURE_WIDTH",ep.toFixed(0)],["TRANSMITTANCE_TEXTURE_HEIGHT",tp.toFixed(0)],["SCATTERING_TEXTURE_R_SIZE",gy.toFixed(0)],["SCATTERING_TEXTURE_MU_SIZE",vy.toFixed(0)],["SCATTERING_TEXTURE_MU_S_SIZE",_y.toFixed(0)],["SCATTERING_TEXTURE_NU_SIZE",xy.toFixed(0)],["IRRADIANCE_TEXTURE_WIDTH",Jd.toFixed(0)],["IRRADIANCE_TEXTURE_HEIGHT",$d.toFixed(0)],["METER_TO_LENGTH_UNIT",a1.toFixed(7)]])}),this.camera=e,this.atmosphere=i,this.overlay=null,this.shadow=null,this.shadowLength=null,this.lightingMask=null,this.combinedScatteringTextures=!1,this.hasHigherOrderScatteringTexture=!1,this.shadowSampleCount=8,this.octEncodedNormal=s,this.reconstructNormal=o,this.singleMieScatteringTexture=d,this.higherOrderScatteringTexture=m,this.ellipsoid=g,this.correctAltitude=x,this.correctGeometricError=T,this.sunLight=v??S,this.skyLight=E??b,this.transmittance=D,this.inscatter=C,this.sky=O,this.sun=w,this.moon=B,this.ground=re}get mainCamera(){return this.camera}set mainCamera(e){this.camera=e}copyCameraSettings(e){const{projectionMatrix:t,matrixWorldInverse:i,projectionMatrixInverse:a,matrixWorld:r}=e,s=this.uniforms;s.get("projectionMatrix").value.copy(t),s.get("viewMatrix").value.copy(i),s.get("inverseProjectionMatrix").value.copy(a),s.get("inverseViewMatrix").value.copy(r);const o=e.getWorldPosition(s.get("cameraPosition").value),c=s.get("worldToECEFMatrix").value,h=hne.copy(o).applyMatrix4(c);try{const d=dne.setFromECEF(h).height,m=fne.set(0,this.ellipsoid.maximumRadius,-Math.max(0,d)).applyMatrix4(t);s.get("geometricErrorCorrectionAmount").value=zte(Pte(m.y,41.5,13.8,0,1))}catch{return}const f=s.get("altitudeCorrection");this.correctAltitude?xA(h,this.atmosphere.bottomRadius,this.ellipsoid,f.value):f.value.setScalar(0)}updateOverlay(){let e=!1;const{uniforms:t,defines:i,overlay:a}=this,r=i.has("HAS_OVERLAY"),s=a!=null;return s!==r&&(s?i.set("HAS_OVERLAY","1"):(i.delete("HAS_OVERLAY"),t.get("overlayBuffer").value=null),e=!0),s&&(t.get("overlayBuffer").value=a.map),e}updateShadow(){let e=!1;const{uniforms:t,defines:i,shadow:a}=this,r=i.has("HAS_SHADOW"),s=a!=null;if(s!==r&&(s?i.set("HAS_SHADOW","1"):(i.delete("HAS_SHADOW"),t.get("shadowBuffer").value=null),e=!0),s){const o=i.get("SHADOW_CASCADE_COUNT"),c=`${a.cascadeCount}`;o!==c&&(i.set("SHADOW_CASCADE_COUNT",a.cascadeCount.toFixed(0)),e=!0),t.get("shadowBuffer").value=a.map,t.get("shadowMapSize").value=a.mapSize,t.get("shadowIntervals").value=a.intervals,t.get("shadowMatrices").value=a.matrices,t.get("inverseShadowMatrices").value=a.inverseMatrices,t.get("shadowFar").value=a.far,t.get("shadowTopHeight").value=a.topHeight}return e}updateShadowLength(){let e=!1;const{uniforms:t,defines:i,shadowLength:a}=this,r=i.has("HAS_SHADOW_LENGTH"),s=a!=null;return s!==r&&(s?i.set("HAS_SHADOW_LENGTH","1"):(i.delete("HAS_SHADOW_LENGTH"),t.get("shadowLengthBuffer").value=null),e=!0),s&&(t.get("shadowLengthBuffer").value=a.map),e}updateLightingMask(){let e=!1;const{uniforms:t,defines:i,lightingMask:a}=this,r=i.has("HAS_LIGHTING_MASK"),s=a!=null;if(s!==r&&(s?i.set("HAS_LIGHTING_MASK","1"):(i.delete("HAS_LIGHTING_MASK"),t.get("lightingMaskBuffer").value=null),e=!0),s){t.get("lightingMaskBuffer").value=a.map;const o=i.get("LIGHTING_MASK_CHANNEL"),c=a.channel;c!==o&&(/^[rgba]$/.test(c)?(i.set("LIGHTING_MASK_CHANNEL",c),e=!0):console.error(`Expression validation failed: ${c}`))}return e}update(e,t,i){this.copyCameraSettings(this.camera);let a=!1;a||(a=this.updateOverlay()),a||(a=this.updateShadow()),a||(a=this.updateShadowLength()),a||(a=this.updateLightingMask()),a&&this.setChanged(),++this.uniforms.get("frame").value}get normalBuffer(){return this.uniforms.get("normalBuffer").value}set normalBuffer(e){this.uniforms.get("normalBuffer").value=e}get irradianceTexture(){return this.uniforms.get("irradiance_texture").value}set irradianceTexture(e){this.uniforms.get("irradiance_texture").value=e}get scatteringTexture(){return this.uniforms.get("scattering_texture").value}set scatteringTexture(e){this.uniforms.get("scattering_texture").value=e}get transmittanceTexture(){return this.uniforms.get("transmittance_texture").value}set transmittanceTexture(e){this.uniforms.get("transmittance_texture").value=e}get singleMieScatteringTexture(){return this.uniforms.get("single_mie_scattering_texture").value}set singleMieScatteringTexture(e){this.uniforms.get("single_mie_scattering_texture").value=e,this.combinedScatteringTextures=e==null}get higherOrderScatteringTexture(){return this.uniforms.get("higher_order_scattering_texture").value}set higherOrderScatteringTexture(e){this.uniforms.get("higher_order_scattering_texture").value=e,this.hasHigherOrderScatteringTexture=e!=null}get ellipsoid(){return this._ellipsoid}set ellipsoid(e){this._ellipsoid=e,this.uniforms.get("ellipsoidRadii").value.copy(e.radii)}get worldToECEFMatrix(){return this.uniforms.get("worldToECEFMatrix").value}get sunDirection(){return this.uniforms.get("sunDirection").value}get sunIrradiance(){return this.sunLight}set sunIrradiance(e){this.sunLight=e}get skyIrradiance(){return this.skyLight}set skyIrradiance(e){this.skyLight=e}get irradianceScale(){return this.albedoScale}set irradianceScale(e){this.albedoScale=e}get albedoScale(){return this.uniforms.get("albedoScale").value}set albedoScale(e){this.uniforms.get("albedoScale").value=e}get moonDirection(){return this.uniforms.get("moonDirection").value}get moonAngularRadius(){return this.uniforms.get("moonAngularRadius").value}set moonAngularRadius(e){this.uniforms.get("moonAngularRadius").value=e}get lunarRadianceScale(){return this.uniforms.get("lunarRadianceScale").value}set lunarRadianceScale(e){this.uniforms.get("lunarRadianceScale").value=e}get stbnTexture(){return this.uniforms.get("stbnTexture").value}set stbnTexture(e){this.uniforms.get("stbnTexture").value=e}get shadowRadius(){return this.uniforms.get("shadowRadius").value}set shadowRadius(e){this.uniforms.get("shadowRadius").value=e}};ar([dn("OCT_ENCODED_NORMAL")],Ba.prototype,"octEncodedNormal");ar([dn("RECONSTRUCT_NORMAL")],Ba.prototype,"reconstructNormal");ar([dn("COMBINED_SCATTERING_TEXTURES")],Ba.prototype,"combinedScatteringTextures");ar([dn("HAS_HIGHER_ORDER_SCATTERING_TEXTURE")],Ba.prototype,"hasHigherOrderScatteringTexture");ar([dn("CORRECT_GEOMETRIC_ERROR")],Ba.prototype,"correctGeometricError");ar([dn("SUN_LIGHT")],Ba.prototype,"sunLight");ar([dn("SKY_LIGHT")],Ba.prototype,"skyLight");ar([dn("TRANSMITTANCE")],Ba.prototype,"transmittance");ar([dn("INSCATTER")],Ba.prototype,"inscatter");ar([dn("SKY")],Ba.prototype,"sky");ar([dn("SUN")],Ba.prototype,"sun");ar([dn("MOON")],Ba.prototype,"moon");ar([dn("GROUND")],Ba.prototype,"ground");ar([mh("SHADOW_SAMPLE_COUNT",{min:1,max:16})],Ba.prototype,"shadowSampleCount");var pne=Object.defineProperty,BP=(n,e,t,i)=>{for(var a=void 0,r=n.length-1,s;r>=0;r--)(s=n[r])&&(a=s(e,t,a)||a);return a&&pne(e,t,a),a};const mne=new L;function gne(n,e){let t="",i="";for(let a=1;a",t).replace("#include ",i)}const yA={ellipsoid:_0.WGS84,correctAltitude:!0,renderTargetCount:1};class Z0 extends hh{constructor(e,t=j0.DEFAULT){const{irradianceTexture:i=null,scatteringTexture:a=null,transmittanceTexture:r=null,singleMieScatteringTexture:s=null,higherOrderScatteringTexture:o=null,ellipsoid:c,correctAltitude:h,sunDirection:f,sunAngularRadius:d,renderTargetCount:m,...g}={...yA,...e};super({toneMapped:!1,depthWrite:!1,depthTest:!1,...g,uniforms:{cameraPosition:new J(new L),worldToECEFMatrix:new J(new ke),altitudeCorrection:new J(new L),sunDirection:new J((f==null?void 0:f.clone())??new L),ATMOSPHERE:t.toUniform(),SUN_SPECTRAL_RADIANCE_TO_LUMINANCE:new J(t.sunRadianceToRelativeLuminance),SKY_SPECTRAL_RADIANCE_TO_LUMINANCE:new J(t.skyRadianceToRelativeLuminance),irradiance_texture:new J(i),scattering_texture:new J(a),transmittance_texture:new J(r),single_mie_scattering_texture:new J(null),higher_order_scattering_texture:new J(null),...g.uniforms},defines:{PI:`${Math.PI}`,TRANSMITTANCE_TEXTURE_WIDTH:ep.toFixed(0),TRANSMITTANCE_TEXTURE_HEIGHT:tp.toFixed(0),SCATTERING_TEXTURE_R_SIZE:gy.toFixed(0),SCATTERING_TEXTURE_MU_SIZE:vy.toFixed(0),SCATTERING_TEXTURE_MU_S_SIZE:_y.toFixed(0),SCATTERING_TEXTURE_NU_SIZE:xy.toFixed(0),IRRADIANCE_TEXTURE_WIDTH:Jd.toFixed(0),IRRADIANCE_TEXTURE_HEIGHT:$d.toFixed(0),METER_TO_LENGTH_UNIT:a1.toFixed(7),...g.defines}}),this.atmosphere=t,this.combinedScatteringTextures=!1,this.hasHigherOrderScatteringTexture=!1,this.singleMieScatteringTexture=s,this.higherOrderScatteringTexture=o,this.ellipsoid=c,this.correctAltitude=h,d!=null&&(this.sunAngularRadius=d),this.renderTargetCount=m}copyCameraSettings(e){const t=this.uniforms,i=e.getWorldPosition(t.cameraPosition.value),a=mne.copy(i).applyMatrix4(t.worldToECEFMatrix.value),r=t.altitudeCorrection.value;this.correctAltitude?xA(a,this.atmosphere.bottomRadius,this.ellipsoid,r):r.setScalar(0)}onBeforeCompile(e,t){e.fragmentShader=gne(e.fragmentShader,this.renderTargetCount)}onBeforeRender(e,t,i,a,r,s){this.copyCameraSettings(i)}get irradianceTexture(){return this.uniforms.irradiance_texture.value}set irradianceTexture(e){this.uniforms.irradiance_texture.value=e}get scatteringTexture(){return this.uniforms.scattering_texture.value}set scatteringTexture(e){this.uniforms.scattering_texture.value=e}get transmittanceTexture(){return this.uniforms.transmittance_texture.value}set transmittanceTexture(e){this.uniforms.transmittance_texture.value=e}get singleMieScatteringTexture(){return this.uniforms.single_mie_scattering_texture.value}set singleMieScatteringTexture(e){this.uniforms.single_mie_scattering_texture.value=e,this.combinedScatteringTextures=e==null}get higherOrderScatteringTexture(){return this.uniforms.higher_order_scattering_texture.value}set higherOrderScatteringTexture(e){this.uniforms.higher_order_scattering_texture.value=e,this.hasHigherOrderScatteringTexture=e!=null}get worldToECEFMatrix(){return this.uniforms.worldToECEFMatrix.value}get sunDirection(){return this.uniforms.sunDirection.value}get sunAngularRadius(){return this.uniforms.ATMOSPHERE.value.sun_angular_radius}set sunAngularRadius(e){this.uniforms.ATMOSPHERE.value.sun_angular_radius=e}get renderTargetCount(){return this._renderTargetCount}set renderTargetCount(e){e!==this.renderTargetCount&&(this._renderTargetCount=e,this.needsUpdate=!0)}}BP([dn("COMBINED_SCATTERING_TEXTURES")],Z0.prototype,"combinedScatteringTextures");BP([dn("HAS_HIGHER_ORDER_SCATTERING_TEXTURE")],Z0.prototype,"hasHigherOrderScatteringTexture");/** - @preserve - - Astronomy library for JavaScript (browser and Node.js). - https://github.com/cosinekitty/astronomy - - MIT License - - Copyright (c) 2019-2023 Don Cross - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*//** - * @fileoverview Astronomy calculation library for browser scripting and Node.js. - * @author Don Cross - * @license MIT - */const vne=173.1446326846693,_ne=14959787069098932e-8,th=.017453292519943295,xne=365.24217,EO=new Date("2000-01-01T12:00:00Z"),Bo=2*Math.PI,Bl=3600*(180/Math.PI),qf=484813681109536e-20,yne=10800*60,Sne=2*yne,Tne=6378.1366,Ene=Tne/_ne,Mne=81.30056,SA=.0002959122082855911,YE=2825345909524226e-22,qE=8459715185680659e-23,jE=1292024916781969e-23,ZE=1524358900784276e-23;function T_(n){if(!Number.isFinite(n))throw console.trace(),`Value is not a finite number: ${n}`;return n}function Tf(n){return n-Math.floor(n)}var zn;(function(n){n.Sun="Sun",n.Moon="Moon",n.Mercury="Mercury",n.Venus="Venus",n.Earth="Earth",n.Mars="Mars",n.Jupiter="Jupiter",n.Saturn="Saturn",n.Uranus="Uranus",n.Neptune="Neptune",n.Pluto="Pluto",n.SSB="SSB",n.EMB="EMB",n.Star1="Star1",n.Star2="Star2",n.Star3="Star3",n.Star4="Star4",n.Star5="Star5",n.Star6="Star6",n.Star7="Star7",n.Star8="Star8"})(zn||(zn={}));const bne=[zn.Star1,zn.Star2,zn.Star3,zn.Star4,zn.Star5,zn.Star6,zn.Star7,zn.Star8],Ane=[{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0}];function wne(n){const e=bne.indexOf(n);return e>=0?Ane[e]:null}function HP(n){const e=wne(n);return e&&e.dist>0?e:null}var sl;(function(n){n[n.From2000=0]="From2000",n[n.Into2000=1]="Into2000"})(sl||(sl={}));const jf={Mercury:[[[[4.40250710144,0,0],[.40989414977,1.48302034195,26087.9031415742],[.050462942,4.47785489551,52175.8062831484],[.00855346844,1.16520322459,78263.70942472259],[.00165590362,4.11969163423,104351.61256629678],[.00034561897,.77930768443,130439.51570787099],[7583476e-11,3.71348404924,156527.41884944518]],[[26087.90313685529,0,0],[.01131199811,6.21874197797,26087.9031415742],[.00292242298,3.04449355541,52175.8062831484],[.00075775081,6.08568821653,78263.70942472259],[.00019676525,2.80965111777,104351.61256629678]]],[[[.11737528961,1.98357498767,26087.9031415742],[.02388076996,5.03738959686,52175.8062831484],[.01222839532,3.14159265359,0],[.0054325181,1.79644363964,78263.70942472259],[.0012977877,4.83232503958,104351.61256629678],[.00031866927,1.58088495658,130439.51570787099],[7963301e-11,4.60972126127,156527.41884944518]],[[.00274646065,3.95008450011,26087.9031415742],[.00099737713,3.14159265359,0]]],[[[.39528271651,0,0],[.07834131818,6.19233722598,26087.9031415742],[.00795525558,2.95989690104,52175.8062831484],[.00121281764,6.01064153797,78263.70942472259],[.00021921969,2.77820093972,104351.61256629678],[4354065e-11,5.82894543774,130439.51570787099]],[[.0021734774,4.65617158665,26087.9031415742],[.00044141826,1.42385544001,52175.8062831484]]]],Venus:[[[[3.17614666774,0,0],[.01353968419,5.59313319619,10213.285546211],[.00089891645,5.30650047764,20426.571092422],[5477194e-11,4.41630661466,7860.4193924392],[3455741e-11,2.6996444782,11790.6290886588],[2372061e-11,2.99377542079,3930.2096962196],[1317168e-11,5.18668228402,26.2983197998],[1664146e-11,4.25018630147,1577.3435424478],[1438387e-11,4.15745084182,9683.5945811164],[1200521e-11,6.15357116043,30639.856638633]],[[10213.28554621638,0,0],[.00095617813,2.4640651111,10213.285546211],[7787201e-11,.6247848222,20426.571092422]]],[[[.05923638472,.26702775812,10213.285546211],[.00040107978,1.14737178112,20426.571092422],[.00032814918,3.14159265359,0]],[[.00287821243,1.88964962838,10213.285546211]]],[[[.72334820891,0,0],[.00489824182,4.02151831717,10213.285546211],[1658058e-11,4.90206728031,20426.571092422],[1378043e-11,1.12846591367,11790.6290886588],[1632096e-11,2.84548795207,7860.4193924392],[498395e-11,2.58682193892,9683.5945811164],[221985e-11,2.01346696541,19367.1891622328],[237454e-11,2.55136053886,15720.8387848784]],[[.00034551041,.89198706276,10213.285546211]]]],Earth:[[[[1.75347045673,0,0],[.03341656453,4.66925680415,6283.0758499914],[.00034894275,4.62610242189,12566.1516999828],[3417572e-11,2.82886579754,3.523118349],[3497056e-11,2.74411783405,5753.3848848968],[3135899e-11,3.62767041756,77713.7714681205],[2676218e-11,4.41808345438,7860.4193924392],[2342691e-11,6.13516214446,3930.2096962196],[1273165e-11,2.03709657878,529.6909650946],[1324294e-11,.74246341673,11506.7697697936],[901854e-11,2.04505446477,26.2983197998],[1199167e-11,1.10962946234,1577.3435424478],[857223e-11,3.50849152283,398.1490034082],[779786e-11,1.17882681962,5223.6939198022],[99025e-10,5.23268072088,5884.9268465832],[753141e-11,2.53339052847,5507.5532386674],[505267e-11,4.58292599973,18849.2275499742],[492392e-11,4.20505711826,775.522611324],[356672e-11,2.91954114478,.0673103028],[284125e-11,1.89869240932,796.2980068164],[242879e-11,.34481445893,5486.777843175],[317087e-11,5.84901948512,11790.6290886588],[271112e-11,.31486255375,10977.078804699],[206217e-11,4.80646631478,2544.3144198834],[205478e-11,1.86953770281,5573.1428014331],[202318e-11,2.45767790232,6069.7767545534],[126225e-11,1.08295459501,20.7753954924],[155516e-11,.83306084617,213.299095438]],[[6283.0758499914,0,0],[.00206058863,2.67823455808,6283.0758499914],[4303419e-11,2.63512233481,12566.1516999828]],[[8721859e-11,1.07253635559,6283.0758499914]]],[[],[[.00227777722,3.4137662053,6283.0758499914],[3805678e-11,3.37063423795,12566.1516999828]]],[[[1.00013988784,0,0],[.01670699632,3.09846350258,6283.0758499914],[.00013956024,3.05524609456,12566.1516999828],[308372e-10,5.19846674381,77713.7714681205],[1628463e-11,1.17387558054,5753.3848848968],[1575572e-11,2.84685214877,7860.4193924392],[924799e-11,5.45292236722,11506.7697697936],[542439e-11,4.56409151453,3930.2096962196],[47211e-10,3.66100022149,5884.9268465832],[85831e-11,1.27079125277,161000.6857376741],[57056e-11,2.01374292245,83996.84731811189],[55736e-11,5.2415979917,71430.69561812909],[174844e-11,3.01193636733,18849.2275499742],[243181e-11,4.2734953079,11790.6290886588]],[[.00103018607,1.10748968172,6283.0758499914],[1721238e-11,1.06442300386,12566.1516999828]],[[4359385e-11,5.78455133808,6283.0758499914]]]],Mars:[[[[6.20347711581,0,0],[.18656368093,5.0503710027,3340.6124266998],[.01108216816,5.40099836344,6681.2248533996],[.00091798406,5.75478744667,10021.8372800994],[.00027744987,5.97049513147,3.523118349],[.00010610235,2.93958560338,2281.2304965106],[.00012315897,.84956094002,2810.9214616052],[8926784e-11,4.15697846427,.0172536522],[8715691e-11,6.11005153139,13362.4497067992],[6797556e-11,.36462229657,398.1490034082],[7774872e-11,3.33968761376,5621.8429232104],[3575078e-11,1.6618650571,2544.3144198834],[4161108e-11,.22814971327,2942.4634232916],[3075252e-11,.85696614132,191.4482661116],[2628117e-11,.64806124465,3337.0893083508],[2937546e-11,6.07893711402,.0673103028],[2389414e-11,5.03896442664,796.2980068164],[2579844e-11,.02996736156,3344.1355450488],[1528141e-11,1.14979301996,6151.533888305],[1798806e-11,.65634057445,529.6909650946],[1264357e-11,3.62275122593,5092.1519581158],[1286228e-11,3.06796065034,2146.1654164752],[1546404e-11,2.91579701718,1751.539531416],[1024902e-11,3.69334099279,8962.4553499102],[891566e-11,.18293837498,16703.062133499],[858759e-11,2.4009381194,2914.0142358238],[832715e-11,2.46418619474,3340.5951730476],[83272e-10,4.49495782139,3340.629680352],[712902e-11,3.66335473479,1059.3819301892],[748723e-11,3.82248614017,155.4203994342],[723861e-11,.67497311481,3738.761430108],[635548e-11,2.92182225127,8432.7643848156],[655162e-11,.48864064125,3127.3133312618],[550474e-11,3.81001042328,.9803210682],[55275e-10,4.47479317037,1748.016413067],[425966e-11,.55364317304,6283.0758499914],[415131e-11,.49662285038,213.299095438],[472167e-11,3.62547124025,1194.4470102246],[306551e-11,.38052848348,6684.7479717486],[312141e-11,.99853944405,6677.7017350506],[293198e-11,4.22131299634,20.7753954924],[302375e-11,4.48618007156,3532.0606928114],[274027e-11,.54222167059,3340.545116397],[281079e-11,5.88163521788,1349.8674096588],[231183e-11,1.28242156993,3870.3033917944],[283602e-11,5.7688543494,3149.1641605882],[236117e-11,5.75503217933,3333.498879699],[274033e-11,.13372524985,3340.6797370026],[299395e-11,2.78323740866,6254.6266625236]],[[3340.61242700512,0,0],[.01457554523,3.60433733236,3340.6124266998],[.00168414711,3.92318567804,6681.2248533996],[.00020622975,4.26108844583,10021.8372800994],[3452392e-11,4.7321039319,3.523118349],[2586332e-11,4.60670058555,13362.4497067992],[841535e-11,4.45864030426,2281.2304965106]],[[.00058152577,2.04961712429,3340.6124266998],[.00013459579,2.45738706163,6681.2248533996]]],[[[.03197134986,3.76832042431,3340.6124266998],[.00298033234,4.10616996305,6681.2248533996],[.00289104742,0,0],[.00031365539,4.4465105309,10021.8372800994],[34841e-9,4.7881254926,13362.4497067992]],[[.00217310991,6.04472194776,3340.6124266998],[.00020976948,3.14159265359,0],[.00012834709,1.60810667915,6681.2248533996]]],[[[1.53033488271,0,0],[.1418495316,3.47971283528,3340.6124266998],[.00660776362,3.81783443019,6681.2248533996],[.00046179117,4.15595316782,10021.8372800994],[8109733e-11,5.55958416318,2810.9214616052],[7485318e-11,1.77239078402,5621.8429232104],[5523191e-11,1.3643630377,2281.2304965106],[382516e-10,4.49407183687,13362.4497067992],[2306537e-11,.09081579001,2544.3144198834],[1999396e-11,5.36059617709,3337.0893083508],[2484394e-11,4.9254563992,2942.4634232916],[1960195e-11,4.74249437639,3344.1355450488],[1167119e-11,2.11260868341,5092.1519581158],[1102816e-11,5.00908403998,398.1490034082],[899066e-11,4.40791133207,529.6909650946],[992252e-11,5.83861961952,6151.533888305],[807354e-11,2.10217065501,1059.3819301892],[797915e-11,3.44839203899,796.2980068164],[740975e-11,1.49906336885,2146.1654164752]],[[.01107433345,2.03250524857,3340.6124266998],[.00103175887,2.37071847807,6681.2248533996],[128772e-9,0,0],[.0001081588,2.70888095665,10021.8372800994]],[[.00044242249,.47930604954,3340.6124266998],[8138042e-11,.86998389204,6681.2248533996]]]],Jupiter:[[[[.59954691494,0,0],[.09695898719,5.06191793158,529.6909650946],[.00573610142,1.44406205629,7.1135470008],[.00306389205,5.41734730184,1059.3819301892],[.00097178296,4.14264726552,632.7837393132],[.00072903078,3.64042916389,522.5774180938],[.00064263975,3.41145165351,103.0927742186],[.00039806064,2.29376740788,419.4846438752],[.00038857767,1.27231755835,316.3918696566],[.00027964629,1.7845459182,536.8045120954],[.0001358973,5.7748104079,1589.0728952838],[8246349e-11,3.5822792584,206.1855484372],[8768704e-11,3.63000308199,949.1756089698],[7368042e-11,5.0810119427,735.8765135318],[626315e-10,.02497628807,213.299095438],[6114062e-11,4.51319998626,1162.4747044078],[4905396e-11,1.32084470588,110.2063212194],[5305285e-11,1.30671216791,14.2270940016],[5305441e-11,4.18625634012,1052.2683831884],[4647248e-11,4.69958103684,3.9321532631],[3045023e-11,4.31676431084,426.598190876],[2609999e-11,1.56667394063,846.0828347512],[2028191e-11,1.06376530715,3.1813937377],[1764763e-11,2.14148655117,1066.49547719],[1722972e-11,3.88036268267,1265.5674786264],[1920945e-11,.97168196472,639.897286314],[1633223e-11,3.58201833555,515.463871093],[1431999e-11,4.29685556046,625.6701923124],[973272e-11,4.09764549134,95.9792272178]],[[529.69096508814,0,0],[.00489503243,4.2208293947,529.6909650946],[.00228917222,6.02646855621,7.1135470008],[.00030099479,4.54540782858,1059.3819301892],[.0002072092,5.45943156902,522.5774180938],[.00012103653,.16994816098,536.8045120954],[6067987e-11,4.42422292017,103.0927742186],[5433968e-11,3.98480737746,419.4846438752],[4237744e-11,5.89008707199,14.2270940016]],[[.00047233601,4.32148536482,7.1135470008],[.00030649436,2.929777887,529.6909650946],[.00014837605,3.14159265359,0]]],[[[.02268615702,3.55852606721,529.6909650946],[.00109971634,3.90809347197,1059.3819301892],[.00110090358,0,0],[8101428e-11,3.60509572885,522.5774180938],[6043996e-11,4.25883108339,1589.0728952838],[6437782e-11,.30627119215,536.8045120954]],[[.00078203446,1.52377859742,529.6909650946]]],[[[5.20887429326,0,0],[.25209327119,3.49108639871,529.6909650946],[.00610599976,3.84115365948,1059.3819301892],[.00282029458,2.57419881293,632.7837393132],[.00187647346,2.07590383214,522.5774180938],[.00086792905,.71001145545,419.4846438752],[.00072062974,.21465724607,536.8045120954],[.00065517248,5.9799588479,316.3918696566],[.00029134542,1.67759379655,103.0927742186],[.00030135335,2.16132003734,949.1756089698],[.00023453271,3.54023522184,735.8765135318],[.00022283743,4.19362594399,1589.0728952838],[.00023947298,.2745803748,7.1135470008],[.00013032614,2.96042965363,1162.4747044078],[970336e-10,1.90669633585,206.1855484372],[.00012749023,2.71550286592,1052.2683831884],[7057931e-11,2.18184839926,1265.5674786264],[6137703e-11,6.26418240033,846.0828347512],[2616976e-11,2.00994012876,1581.959348283]],[[.0127180152,2.64937512894,529.6909650946],[.00061661816,3.00076460387,1059.3819301892],[.00053443713,3.89717383175,522.5774180938],[.00031185171,4.88276958012,536.8045120954],[.00041390269,0,0]]]],Saturn:[[[[.87401354025,0,0],[.11107659762,3.96205090159,213.299095438],[.01414150957,4.58581516874,7.1135470008],[.00398379389,.52112032699,206.1855484372],[.00350769243,3.30329907896,426.598190876],[.00206816305,.24658372002,103.0927742186],[792713e-9,3.84007056878,220.4126424388],[.00023990355,4.66976924553,110.2063212194],[.00016573588,.43719228296,419.4846438752],[.00014906995,5.76903183869,316.3918696566],[.0001582029,.93809155235,632.7837393132],[.00014609559,1.56518472,3.9321532631],[.00013160301,4.44891291899,14.2270940016],[.00015053543,2.71669915667,639.897286314],[.00013005299,5.98119023644,11.0457002639],[.00010725067,3.12939523827,202.2533951741],[5863206e-11,.23656938524,529.6909650946],[5227757e-11,4.20783365759,3.1813937377],[6126317e-11,1.76328667907,277.0349937414],[5019687e-11,3.17787728405,433.7117378768],[459255e-10,.61977744975,199.0720014364],[4005867e-11,2.24479718502,63.7358983034],[2953796e-11,.98280366998,95.9792272178],[387367e-10,3.22283226966,138.5174968707],[2461186e-11,2.03163875071,735.8765135318],[3269484e-11,.77492638211,949.1756089698],[1758145e-11,3.2658010994,522.5774180938],[1640172e-11,5.5050445305,846.0828347512],[1391327e-11,4.02333150505,323.5054166574],[1580648e-11,4.37265307169,309.2783226558],[1123498e-11,2.83726798446,415.5524906121],[1017275e-11,3.71700135395,227.5261894396],[848642e-11,3.1915017083,209.3669421749]],[[213.2990952169,0,0],[.01297370862,1.82834923978,213.299095438],[.00564345393,2.88499717272,7.1135470008],[.00093734369,1.06311793502,426.598190876],[.00107674962,2.27769131009,206.1855484372],[.00040244455,2.04108104671,220.4126424388],[.00019941774,1.2795439047,103.0927742186],[.00010511678,2.7488034213,14.2270940016],[6416106e-11,.38238295041,639.897286314],[4848994e-11,2.43037610229,419.4846438752],[4056892e-11,2.92133209468,110.2063212194],[3768635e-11,3.6496533078,3.9321532631]],[[.0011644133,1.17988132879,7.1135470008],[.00091841837,.0732519584,213.299095438],[.00036661728,0,0],[.00015274496,4.06493179167,206.1855484372]]],[[[.04330678039,3.60284428399,213.299095438],[.00240348302,2.85238489373,426.598190876],[.00084745939,0,0],[.00030863357,3.48441504555,220.4126424388],[.00034116062,.57297307557,206.1855484372],[.0001473407,2.11846596715,639.897286314],[9916667e-11,5.79003188904,419.4846438752],[6993564e-11,4.7360468972,7.1135470008],[4807588e-11,5.43305312061,316.3918696566]],[[.00198927992,4.93901017903,213.299095438],[.00036947916,3.14159265359,0],[.00017966989,.5197943111,426.598190876]]],[[[9.55758135486,0,0],[.52921382865,2.39226219573,213.299095438],[.01873679867,5.2354960466,206.1855484372],[.01464663929,1.64763042902,426.598190876],[.00821891141,5.93520042303,316.3918696566],[.00547506923,5.0153261898,103.0927742186],[.0037168465,2.27114821115,220.4126424388],[.00361778765,3.13904301847,7.1135470008],[.00140617506,5.70406606781,632.7837393132],[.00108974848,3.29313390175,110.2063212194],[.00069006962,5.94099540992,419.4846438752],[.00061053367,.94037691801,639.897286314],[.00048913294,1.55733638681,202.2533951741],[.00034143772,.19519102597,277.0349937414],[.00032401773,5.47084567016,949.1756089698],[.00020936596,.46349251129,735.8765135318],[9796004e-11,5.20477537945,1265.5674786264],[.00011993338,5.98050967385,846.0828347512],[208393e-9,1.52102476129,433.7117378768],[.00015298404,3.0594381494,529.6909650946],[6465823e-11,.17732249942,1052.2683831884],[.00011380257,1.7310542704,522.5774180938],[3419618e-11,4.94550542171,1581.959348283]],[[.0618298134,.2584351148,213.299095438],[.00506577242,.71114625261,206.1855484372],[.00341394029,5.79635741658,426.598190876],[.00188491195,.47215589652,220.4126424388],[.00186261486,3.14159265359,0],[.00143891146,1.40744822888,7.1135470008]],[[.00436902572,4.78671677509,213.299095438]]]],Uranus:[[[[5.48129294297,0,0],[.09260408234,.89106421507,74.7815985673],[.01504247898,3.6271926092,1.4844727083],[.00365981674,1.89962179044,73.297125859],[.00272328168,3.35823706307,149.5631971346],[.00070328461,5.39254450063,63.7358983034],[.00068892678,6.09292483287,76.2660712756],[.00061998615,2.26952066061,2.9689454166],[.00061950719,2.85098872691,11.0457002639],[.0002646877,3.14152083966,71.8126531507],[.00025710476,6.11379840493,454.9093665273],[.0002107885,4.36059339067,148.0787244263],[.00017818647,1.74436930289,36.6485629295],[.00014613507,4.73732166022,3.9321532631],[.00011162509,5.8268179635,224.3447957019],[.0001099791,.48865004018,138.5174968707],[9527478e-11,2.95516862826,35.1640902212],[7545601e-11,5.236265824,109.9456887885],[4220241e-11,3.23328220918,70.8494453042],[40519e-9,2.277550173,151.0476698429],[3354596e-11,1.0654900738,4.4534181249],[2926718e-11,4.62903718891,9.5612275556],[349034e-10,5.48306144511,146.594251718],[3144069e-11,4.75199570434,77.7505439839],[2922333e-11,5.35235361027,85.8272988312],[2272788e-11,4.36600400036,70.3281804424],[2051219e-11,1.51773566586,.1118745846],[2148602e-11,.60745949945,38.1330356378],[1991643e-11,4.92437588682,277.0349937414],[1376226e-11,2.04283539351,65.2203710117],[1666902e-11,3.62744066769,380.12776796],[1284107e-11,3.11347961505,202.2533951741],[1150429e-11,.93343589092,3.1813937377],[1533221e-11,2.58594681212,52.6901980395],[1281604e-11,.54271272721,222.8603229936],[1372139e-11,4.19641530878,111.4301614968],[1221029e-11,.1990065003,108.4612160802],[946181e-11,1.19253165736,127.4717966068],[1150989e-11,4.17898916639,33.6796175129]],[[74.7815986091,0,0],[.00154332863,5.24158770553,74.7815985673],[.00024456474,1.71260334156,1.4844727083],[9258442e-11,.4282973235,11.0457002639],[8265977e-11,1.50218091379,63.7358983034],[915016e-10,1.41213765216,149.5631971346]]],[[[.01346277648,2.61877810547,74.7815985673],[623414e-9,5.08111189648,149.5631971346],[.00061601196,3.14159265359,0],[9963722e-11,1.61603805646,76.2660712756],[992616e-10,.57630380333,73.297125859]],[[.00034101978,.01321929936,74.7815985673]]],[[[19.21264847206,0,0],[.88784984413,5.60377527014,74.7815985673],[.03440836062,.32836099706,73.297125859],[.0205565386,1.7829515933,149.5631971346],[.0064932241,4.52247285911,76.2660712756],[.00602247865,3.86003823674,63.7358983034],[.00496404167,1.40139935333,454.9093665273],[.00338525369,1.58002770318,138.5174968707],[.00243509114,1.57086606044,71.8126531507],[.00190522303,1.99809394714,1.4844727083],[.00161858838,2.79137786799,148.0787244263],[.00143706183,1.38368544947,11.0457002639],[.00093192405,.17437220467,36.6485629295],[.00071424548,4.24509236074,224.3447957019],[.00089806014,3.66105364565,109.9456887885],[.00039009723,1.66971401684,70.8494453042],[.00046677296,1.39976401694,35.1640902212],[.00039025624,3.36234773834,277.0349937414],[.00036755274,3.88649278513,146.594251718],[.00030348723,.70100838798,151.0476698429],[.00029156413,3.180563367,77.7505439839],[.00022637073,.72518687029,529.6909650946],[.00011959076,1.7504339214,984.6003316219],[.00025620756,5.25656086672,380.12776796]],[[.01479896629,3.67205697578,74.7815985673]]]],Neptune:[[[[5.31188633046,0,0],[.0179847553,2.9010127389,38.1330356378],[.01019727652,.48580922867,1.4844727083],[.00124531845,4.83008090676,36.6485629295],[.00042064466,5.41054993053,2.9689454166],[.00037714584,6.09221808686,35.1640902212],[.00033784738,1.24488874087,76.2660712756],[.00016482741,7727998e-11,491.5579294568],[9198584e-11,4.93747051954,39.6175083461],[899425e-10,.27462171806,175.1660598002]],[[38.13303563957,0,0],[.00016604172,4.86323329249,1.4844727083],[.00015744045,2.27887427527,38.1330356378]]],[[[.03088622933,1.44104372644,38.1330356378],[.00027780087,5.91271884599,76.2660712756],[.00027623609,0,0],[.00015355489,2.52123799551,36.6485629295],[.00015448133,3.50877079215,39.6175083461]]],[[[30.07013205828,0,0],[.27062259632,1.32999459377,38.1330356378],[.01691764014,3.25186135653,36.6485629295],[.00807830553,5.18592878704,1.4844727083],[.0053776051,4.52113935896,35.1640902212],[.00495725141,1.5710564165,491.5579294568],[.00274571975,1.84552258866,175.1660598002],[.0001201232,1.92059384991,1021.2488945514],[.00121801746,5.79754470298,76.2660712756],[.00100896068,.3770272493,73.297125859],[.00135134092,3.37220609835,39.6175083461],[7571796e-11,1.07149207335,388.4651552382]]]]};function Rne(n){var e,t,i,a,r,s,o;const c=2e3+(n-14)/xne;return c<-500?(e=(c-1820)/100,-20+32*e*e):c<500?(e=c/100,t=e*e,i=e*t,a=t*t,r=t*i,s=i*i,10583.6-1014.41*e+33.78311*t-5.952053*i-.1798452*a+.022174192*r+.0090316521*s):c<1600?(e=(c-1e3)/100,t=e*e,i=e*t,a=t*t,r=t*i,s=i*i,1574.2-556.01*e+71.23472*t+.319781*i-.8503463*a-.005050998*r+.0083572073*s):c<1700?(e=c-1600,t=e*e,i=e*t,120-.9808*e-.01532*t+i/7129):c<1800?(e=c-1700,t=e*e,i=e*t,a=t*t,8.83+.1603*e-.0059285*t+13336e-8*i-a/1174e3):c<1860?(e=c-1800,t=e*e,i=e*t,a=t*t,r=t*i,s=i*i,o=i*a,13.72-.332447*e+.0068612*t+.0041116*i-37436e-8*a+121272e-10*r-1699e-10*s+875e-12*o):c<1900?(e=c-1860,t=e*e,i=e*t,a=t*t,r=t*i,7.62+.5737*e-.251754*t+.01680668*i-.0004473624*a+r/233174):c<1920?(e=c-1900,t=e*e,i=e*t,a=t*t,-2.79+1.494119*e-.0598939*t+.0061966*i-197e-6*a):c<1941?(e=c-1920,t=e*e,i=e*t,21.2+.84493*e-.0761*t+.0020936*i):c<1961?(e=c-1950,t=e*e,i=e*t,29.07+.407*e-t/233+i/2547):c<1986?(e=c-1975,t=e*e,i=e*t,45.45+1.067*e-t/260-i/718):c<2005?(e=c-2e3,t=e*e,i=e*t,a=t*t,r=t*i,63.86+.3345*e-.060374*t+.0017275*i+651814e-9*a+2373599e-11*r):c<2050?(e=c-2e3,62.92+.32217*e+.005589*e*e):c<2150?(e=(c-1820)/100,-20+32*e*e-.5628*(2150-c)):(e=(c-1820)/100,-20+32*e*e)}let Cne=Rne;function MO(n){return n+Cne(n)/86400}class hc{constructor(e){if(e instanceof hc){this.date=e.date,this.ut=e.ut,this.tt=e.tt;return}const t=1e3*3600*24;if(e instanceof Date&&Number.isFinite(e.getTime())){this.date=e,this.ut=(e.getTime()-EO.getTime())/t,this.tt=MO(this.ut);return}if(Number.isFinite(e)){this.date=new Date(EO.getTime()+e*t),this.ut=e,this.tt=MO(this.ut);return}throw"Argument must be a Date object, an AstroTime object, or a numeric UTC Julian date."}static FromTerrestrialTime(e){let t=new hc(e);for(;;){const i=e-t.tt;if(Math.abs(i)<1e-12)return t;t=t.AddDays(i)}}toString(){return this.date.toISOString()}AddDays(e){return new hc(this.ut+e)}}function gh(n){return n instanceof hc?n:new hc(n)}function Nne(n){function e(m){return m%Sne*qf}const t=n.tt/36525,i=e(128710479305e-5+t*1295965810481e-4),a=e(335779.526232+t*17395272628478e-4),r=e(107226070369e-5+t*1602961601209e-3),s=e(450160.398036-t*69628905431e-4);let o=Math.sin(s),c=Math.cos(s),h=(-172064161-174666*t)*o+33386*c,f=(92052331+9086*t)*c+15377*o,d=2*(a-r+s);return o=Math.sin(d),c=Math.cos(d),h+=(-13170906-1675*t)*o-13696*c,f+=(5730336-3015*t)*c-4587*o,d=2*(a+s),o=Math.sin(d),c=Math.cos(d),h+=(-2276413-234*t)*o+2796*c,f+=(978459-485*t)*c+1374*o,d=2*s,o=Math.sin(d),c=Math.cos(d),h+=(2074554+207*t)*o-698*c,f+=(-897492+470*t)*c-291*o,o=Math.sin(i),c=Math.cos(i),h+=(1475877-3633*t)*o+11817*c,f+=(73871-184*t)*c-1924*o,{dpsi:-135e-6+h*1e-7,deps:388e-6+f*1e-7}}function FP(n){var e=n.tt/36525,t=((((-434e-10*e-576e-9)*e+.0020034)*e-1831e-7)*e-46.836769)*e+84381.406;return t/3600}var Zv;function GP(n){if(!Zv||Math.abs(Zv.tt-n.tt)>1e-6){const e=Nne(n),t=FP(n),i=t+e.deps/3600;Zv={tt:n.tt,dpsi:e.dpsi,deps:e.deps,ee:e.dpsi*Math.cos(t*th)/15,mobl:t,tobl:i}}return Zv}function Dne(n,e){const t=n*th,i=Math.cos(t),a=Math.sin(t);return[e[0],e[1]*i-e[2]*a,e[1]*a+e[2]*i]}function One(n,e){return Dne(FP(n),e)}function Lne(n){const e=n.tt/36525;function t(ot,Ke){const Te=[];let G;for(G=0;G<=Ke-ot;++G)Te.push(0);return{min:ot,array:Te}}function i(ot,Ke,Te,G){const be=[];for(let De=0;De<=Ke-ot;++De)be.push(t(Te,G));return{min:ot,array:be}}function a(ot,Ke,Te){const G=ot.array[Ke-ot.min];return G.array[Te-G.min]}function r(ot,Ke,Te,G){const be=ot.array[Ke-ot.min];be.array[Te-be.min]=G}let s,o,c,h,f,d,m,g,x,T,y,v,S,E,b,D,C,I,P,O,w,B,j,ee=i(-6,6,1,4),se=i(-6,6,1,4);function re(ot,Ke){return a(ee,ot,Ke)}function W(ot,Ke){return a(se,ot,Ke)}function te(ot,Ke,Te){return r(ee,ot,Ke,Te)}function K(ot,Ke,Te){return r(se,ot,Ke,Te)}function oe(ot,Ke,Te,G,be){be(ot*Te-Ke*G,Ke*Te+ot*G)}function ie(ot){return Math.sin(Bo*ot)}m=e*e,x=0,j=0,y=0,v=3422.7;var Ce=ie(.19833+.05611*e),Xe=ie(.27869+.04508*e),nt=ie(.16827-.36903*e),tt=ie(.34734-5.37261*e),gt=ie(.10498-5.37899*e),ge=ie(.42681-.41855*e),Ae=ie(.14943-5.37511*e);for(I=.84*Ce+.31*Xe+14.27*nt+7.26*tt+.28*gt+.24*ge,P=2.94*Ce+.31*Xe+14.27*nt+9.34*tt+1.12*gt+.83*ge,O=-6.4*Ce-1.89*ge,w=.21*Ce+.31*Xe+14.27*nt-88.7*tt-15.3*gt+.24*ge-1.86*Ae,B=I-O,g=-3332e-9*ie(.59734-5.37261*e)-539e-9*ie(.35498-5.37899*e)-64e-9*ie(.39943-5.37511*e),S=Bo*Tf(.60643382+1336.85522467*e-313e-8*m)+I/Bl,E=Bo*Tf(.37489701+1325.55240982*e+2565e-8*m)+P/Bl,b=Bo*Tf(.99312619+99.99735956*e-44e-8*m)+O/Bl,D=Bo*Tf(.25909118+1342.2278298*e-892e-8*m)+w/Bl,C=Bo*Tf(.82736186+1236.85308708*e-397e-8*m)+B/Bl,f=1;f<=4;++f){switch(f){case 1:c=E,o=4,h=1.000002208;break;case 2:c=b,o=3,h=.997504612-.002495388*e;break;case 3:c=D,o=4,h=1.000002708+139.978*g;break;case 4:c=C,o=6,h=1;break;default:throw`Internal error: I = ${f}`}for(te(0,f,1),te(1,f,Math.cos(c)*h),K(0,f,0),K(1,f,Math.sin(c)*h),d=2;d<=o;++d)oe(re(d-1,f),W(d-1,f),re(1,f),W(1,f),(ot,Ke)=>(te(d,f,ot),K(d,f,Ke)));for(d=1;d<=o;++d)te(-d,f,re(d,f)),K(-d,f,-W(d,f))}function Ze(ot,Ke,Te,G){for(var be={x:1,y:0},De=[0,ot,Ke,Te,G],Fe=1;Fe<=4;++Fe)De[Fe]!==0&&oe(be.x,be.y,re(De[Fe],Fe),W(De[Fe],Fe),(Be,$e)=>(be.x=Be,be.y=$e));return be}function ue(ot,Ke,Te,G,be,De,Fe,Be){var $e=Ze(be,De,Fe,Be);x+=ot*$e.y,j+=Ke*$e.y,y+=Te*$e.x,v+=G*$e.x}ue(13.902,14.06,-.001,.2607,0,0,0,4),ue(.403,-4.01,.394,.0023,0,0,0,3),ue(2369.912,2373.36,.601,28.2333,0,0,0,2),ue(-125.154,-112.79,-.725,-.9781,0,0,0,1),ue(1.979,6.98,-.445,.0433,1,0,0,4),ue(191.953,192.72,.029,3.0861,1,0,0,2),ue(-8.466,-13.51,.455,-.1093,1,0,0,1),ue(22639.5,22609.07,.079,186.5398,1,0,0,0),ue(18.609,3.59,-.094,.0118,1,0,0,-1),ue(-4586.465,-4578.13,-.077,34.3117,1,0,0,-2),ue(3.215,5.44,.192,-.0386,1,0,0,-3),ue(-38.428,-38.64,.001,.6008,1,0,0,-4),ue(-.393,-1.43,-.092,.0086,1,0,0,-6),ue(-.289,-1.59,.123,-.0053,0,1,0,4),ue(-24.42,-25.1,.04,-.3,0,1,0,2),ue(18.023,17.93,.007,.1494,0,1,0,1),ue(-668.146,-126.98,-1.302,-.3997,0,1,0,0),ue(.56,.32,-.001,-.0037,0,1,0,-1),ue(-165.145,-165.06,.054,1.9178,0,1,0,-2),ue(-1.877,-6.46,-.416,.0339,0,1,0,-4),ue(.213,1.02,-.074,.0054,2,0,0,4),ue(14.387,14.78,-.017,.2833,2,0,0,2),ue(-.586,-1.2,.054,-.01,2,0,0,1),ue(769.016,767.96,.107,10.1657,2,0,0,0),ue(1.75,2.01,-.018,.0155,2,0,0,-1),ue(-211.656,-152.53,5.679,-.3039,2,0,0,-2),ue(1.225,.91,-.03,-.0088,2,0,0,-3),ue(-30.773,-34.07,-.308,.3722,2,0,0,-4),ue(-.57,-1.4,-.074,.0109,2,0,0,-6),ue(-2.921,-11.75,.787,-.0484,1,1,0,2),ue(1.267,1.52,-.022,.0164,1,1,0,1),ue(-109.673,-115.18,.461,-.949,1,1,0,0),ue(-205.962,-182.36,2.056,1.4437,1,1,0,-2),ue(.233,.36,.012,-.0025,1,1,0,-3),ue(-4.391,-9.66,-.471,.0673,1,1,0,-4),ue(.283,1.53,-.111,.006,1,-1,0,4),ue(14.577,31.7,-1.54,.2302,1,-1,0,2),ue(147.687,138.76,.679,1.1528,1,-1,0,0),ue(-1.089,.55,.021,0,1,-1,0,-1),ue(28.475,23.59,-.443,-.2257,1,-1,0,-2),ue(-.276,-.38,-.006,-.0036,1,-1,0,-3),ue(.636,2.27,.146,-.0102,1,-1,0,-4),ue(-.189,-1.68,.131,-.0028,0,2,0,2),ue(-7.486,-.66,-.037,-.0086,0,2,0,0),ue(-8.096,-16.35,-.74,.0918,0,2,0,-2),ue(-5.741,-.04,0,-9e-4,0,0,2,2),ue(.255,0,0,0,0,0,2,1),ue(-411.608,-.2,0,-.0124,0,0,2,0),ue(.584,.84,0,.0071,0,0,2,-1),ue(-55.173,-52.14,0,-.1052,0,0,2,-2),ue(.254,.25,0,-.0017,0,0,2,-3),ue(.025,-1.67,0,.0031,0,0,2,-4),ue(1.06,2.96,-.166,.0243,3,0,0,2),ue(36.124,50.64,-1.3,.6215,3,0,0,0),ue(-13.193,-16.4,.258,-.1187,3,0,0,-2),ue(-1.187,-.74,.042,.0074,3,0,0,-4),ue(-.293,-.31,-.002,.0046,3,0,0,-6),ue(-.29,-1.45,.116,-.0051,2,1,0,2),ue(-7.649,-10.56,.259,-.1038,2,1,0,0),ue(-8.627,-7.59,.078,-.0192,2,1,0,-2),ue(-2.74,-2.54,.022,.0324,2,1,0,-4),ue(1.181,3.32,-.212,.0213,2,-1,0,2),ue(9.703,11.67,-.151,.1268,2,-1,0,0),ue(-.352,-.37,.001,-.0028,2,-1,0,-1),ue(-2.494,-1.17,-.003,-.0017,2,-1,0,-2),ue(.36,.2,-.012,-.0043,2,-1,0,-4),ue(-1.167,-1.25,.008,-.0106,1,2,0,0),ue(-7.412,-6.12,.117,.0484,1,2,0,-2),ue(-.311,-.65,-.032,.0044,1,2,0,-4),ue(.757,1.82,-.105,.0112,1,-2,0,2),ue(2.58,2.32,.027,.0196,1,-2,0,0),ue(2.533,2.4,-.014,-.0212,1,-2,0,-2),ue(-.344,-.57,-.025,.0036,0,3,0,-2),ue(-.992,-.02,0,0,1,0,2,2),ue(-45.099,-.02,0,-.001,1,0,2,0),ue(-.179,-9.52,0,-.0833,1,0,2,-2),ue(-.301,-.33,0,.0014,1,0,2,-4),ue(-6.382,-3.37,0,-.0481,1,0,-2,2),ue(39.528,85.13,0,-.7136,1,0,-2,0),ue(9.366,.71,0,-.0112,1,0,-2,-2),ue(.202,.02,0,0,1,0,-2,-4),ue(.415,.1,0,.0013,0,1,2,0),ue(-2.152,-2.26,0,-.0066,0,1,2,-2),ue(-1.44,-1.3,0,.0014,0,1,-2,2),ue(.384,-.04,0,0,0,1,-2,-2),ue(1.938,3.6,-.145,.0401,4,0,0,0),ue(-.952,-1.58,.052,-.013,4,0,0,-2),ue(-.551,-.94,.032,-.0097,3,1,0,0),ue(-.482,-.57,.005,-.0045,3,1,0,-2),ue(.681,.96,-.026,.0115,3,-1,0,0),ue(-.297,-.27,.002,-9e-4,2,2,0,-2),ue(.254,.21,-.003,0,2,-2,0,-2),ue(-.25,-.22,.004,.0014,1,3,0,-2),ue(-3.996,0,0,4e-4,2,0,2,0),ue(.557,-.75,0,-.009,2,0,2,-2),ue(-.459,-.38,0,-.0053,2,0,-2,2),ue(-1.298,.74,0,4e-4,2,0,-2,0),ue(.538,1.14,0,-.0141,2,0,-2,-2),ue(.263,.02,0,0,1,1,2,0),ue(.426,.07,0,-6e-4,1,1,-2,-2),ue(-.304,.03,0,3e-4,1,-1,2,0),ue(-.372,-.19,0,-.0027,1,-1,-2,2),ue(.418,0,0,0,0,0,4,0),ue(-.33,-.04,0,0,3,0,2,0);function it(ot,Ke,Te,G,be){return ot*Ze(Ke,Te,G,be).y}T=0,T+=it(-526.069,0,0,1,-2),T+=it(-3.352,0,0,1,-4),T+=it(44.297,1,0,1,-2),T+=it(-6,1,0,1,-4),T+=it(20.599,-1,0,1,0),T+=it(-30.598,-1,0,1,-2),T+=it(-24.649,-2,0,1,0),T+=it(-2,-2,0,1,-2),T+=it(-22.571,0,1,1,-2),T+=it(10.985,0,-1,1,-2),x+=.82*ie(.7736-62.5512*e)+.31*ie(.0466-125.1025*e)+.35*ie(.5785-25.1042*e)+.66*ie(.4591+1335.8075*e)+.64*ie(.313-91.568*e)+1.14*ie(.148+1331.2898*e)+.21*ie(.5918+1056.5859*e)+.44*ie(.5784+1322.8595*e)+.24*ie(.2275-5.7374*e)+.28*ie(.2965+2.6929*e)+.33*ie(.3132+6.3368*e),s=D+j/Bl;let Mt=(1.000002708+139.978*g)*(18518.511+1.189+y)*Math.sin(s)-6.24*Math.sin(3*s)+T;return{geo_eclip_lon:Bo*Tf((S+x/Bl)/Bo),geo_eclip_lat:Math.PI/(180*3600)*Mt,distance_au:Bl*Ene/(.999953253*v)}}function Ine(n,e){return[n.rot[0][0]*e[0]+n.rot[1][0]*e[1]+n.rot[2][0]*e[2],n.rot[0][1]*e[0]+n.rot[1][1]*e[1]+n.rot[2][1]*e[2],n.rot[0][2]*e[0]+n.rot[1][2]*e[1]+n.rot[2][2]*e[2]]}function Une(n,e,t){const i=VP(e,t);return Ine(i,n)}function VP(n,e){const t=n.tt/36525;let i=84381.406,a=((((-951e-10*t+132851e-9)*t-.00114045)*t-1.0790069)*t+5038.481507)*t,r=((((3337e-10*t-467e-9)*t-.00772503)*t+.0512623)*t-.025754)*t+i,s=((((-56e-9*t+170663e-9)*t-.00121197)*t-2.3814292)*t+10.556403)*t;i*=qf,a*=qf,r*=qf,s*=qf;const o=Math.sin(i),c=Math.cos(i),h=Math.sin(-a),f=Math.cos(-a),d=Math.sin(-r),m=Math.cos(-r),g=Math.sin(s),x=Math.cos(s),T=x*f-h*g*m,y=x*h*c+g*m*f*c-o*g*d,v=x*h*o+g*m*f*o+c*g*d,S=-g*f-h*x*m,E=-g*h*c+x*m*f*c-o*x*d,b=-g*h*o+x*m*f*o+c*x*d,D=h*d,C=-d*f*c-o*m,I=-d*f*o+m*c;if(e===sl.Into2000)return new Pd([[T,y,v],[S,E,b],[D,C,I]]);if(e===sl.From2000)return new Pd([[T,S,D],[y,E,C],[v,b,I]]);throw"Invalid precess direction"}function Pne(n){const e=.779057273264+.00273781191135448*n.ut,t=n.ut%1;let i=360*((e+t)%1);return i<0&&(i+=360),i}let Kv;function zne(n){if(!Kv||Kv.tt!==n.tt){const e=n.tt/36525;let t=15*GP(n).ee;const i=Pne(n);let a=((t+.014506+((((-368e-10*e-29956e-9)*e-44e-8)*e+1.3915817)*e+4612.156534)*e)/3600+i)%360/15;a<0&&(a+=24),Kv={tt:n.tt,st:a}}return Kv.st}function Bne(n){const e=gh(n);return zne(e)}function Hne(n,e){const t=GP(n),i=t.mobl*th,a=t.tobl*th,r=t.dpsi*qf,s=Math.cos(i),o=Math.sin(i),c=Math.cos(a),h=Math.sin(a),f=Math.cos(r),d=Math.sin(r),m=f,g=-d*s,x=-d*o,T=d*c,y=f*s*c+o*h,v=f*o*c-s*h,S=d*h,E=f*s*h-o*c,b=f*o*h+s*c;if(e===sl.From2000)return new Pd([[m,T,S],[g,y,E],[x,v,b]]);if(e===sl.Into2000)return new Pd([[m,g,x],[T,y,v],[S,E,b]]);throw"Invalid precess direction"}class Rs{constructor(e,t,i,a){this.x=e,this.y=t,this.z=i,this.t=a}Length(){return Math.hypot(this.x,this.y,this.z)}}class Fne{constructor(e,t,i,a,r,s,o){this.x=e,this.y=t,this.z=i,this.vx=a,this.vy=r,this.vz=s,this.t=o}}let Gne=class{constructor(e,t,i){this.lat=T_(e),this.lon=T_(t),this.dist=T_(i)}};class Pd{constructor(e){this.rot=e}}function KE(n){const e=gh(n),t=Lne(e),i=t.distance_au*Math.cos(t.geo_eclip_lat),a=[i*Math.cos(t.geo_eclip_lon),i*Math.sin(t.geo_eclip_lon),t.distance_au*Math.sin(t.geo_eclip_lat)],r=One(e,a),s=Une(r,e,sl.Into2000);return new Rs(s[0],s[1],s[2],e)}function sd(n,e,t){let i=1,a=0;for(let r of n){let s=0;for(let[c,h,f]of r)s+=c*Math.cos(h+e*f);let o=i*s;t&&(o%=Bo),a+=o,i*=e}return a}function t3(n,e){let t=1,i=0,a=0,r=0;for(let s of n){let o=0,c=0;for(let[h,f,d]of s){let m=f+e*d;o+=h*d*Math.sin(m),r>0&&(c+=h*Math.cos(m))}a+=r*i*c-t*o,i=t,t*=e,++r}return a}const gm=365250,QE=0,JE=1,$E=2;function eM(n){return new Sa(n[0]+44036e-11*n[1]-190919e-12*n[2],-479966e-12*n[0]+.917482137087*n[1]-.397776982902*n[2],.397776982902*n[1]+.917482137087*n[2])}function kP(n,e,t){const i=t*Math.cos(e),a=Math.cos(n),r=Math.sin(n);return[i*a,i*r,t*Math.sin(e)]}function E_(n,e){const t=e.tt/gm,i=sd(n[QE],t,!0),a=sd(n[JE],t,!1),r=sd(n[$E],t,!1),s=kP(i,a,r);return eM(s).ToAstroVector(e)}function Vne(n,e){const t=e/gm,i=sd(n[QE],t,!0),a=sd(n[JE],t,!1),r=sd(n[$E],t,!1),s=t3(n[QE],t),o=t3(n[JE],t),c=t3(n[$E],t),h=Math.cos(i),f=Math.sin(i),d=Math.cos(a),m=Math.sin(a),g=+(c*d*h)-r*m*h*o-r*d*f*s,x=+(c*d*f)-r*m*f*o+r*d*h*s,T=+(c*m)+r*d*o,y=kP(i,a,r),v=[g/gm,x/gm,T/gm],S=eM(y),E=eM(v);return new nh(e,S,E)}function Qv(n,e,t,i){const a=i/(i+SA),r=E_(jf[t],e);n.x+=a*r.x,n.y+=a*r.y,n.z+=a*r.z}function kne(n){const e=new Rs(0,0,0,n);return Qv(e,n,zn.Jupiter,YE),Qv(e,n,zn.Saturn,qE),Qv(e,n,zn.Uranus,jE),Qv(e,n,zn.Neptune,ZE),e}const tM=51,Wne=29200,Zf=146,Ho=201,Ru=[[-73e4,[-26.118207232108,-14.376168177825,3.384402515299],[.0016339372163656,-.0027861699588508,-.0013585880229445]],[-700800,[41.974905202127,-.448502952929,-12.770351505989],[.00073458569351457,.0022785014891658,.00048619778602049]],[-671600,[14.706930780744,44.269110540027,9.353698474772],[-.00210001479998,.00022295915939915,.00070143443551414]],[-642400,[-29.441003929957,-6.43016153057,6.858481011305],[.00084495803960544,-.0030783914758711,-.0012106305981192]],[-613200,[39.444396946234,-6.557989760571,-13.913760296463],[.0011480029005873,.0022400006880665,.00035168075922288]],[-584e3,[20.2303809507,43.266966657189,7.382966091923],[-.0019754081700585,.00053457141292226,.00075929169129793]],[-554800,[-30.65832536462,2.093818874552,9.880531138071],[61010603013347e-18,-.0031326500935382,-.00099346125151067]],[-525600,[35.737703251673,-12.587706024764,-14.677847247563],[.0015802939375649,.0021347678412429,.00019074436384343]],[-496400,[25.466295188546,41.367478338417,5.216476873382],[-.0018054401046468,.0008328308359951,.00080260156912107]],[-467200,[-29.847174904071,10.636426313081,12.297904180106],[-.00063257063052907,-.0029969577578221,-.00074476074151596]],[-438e3,[30.774692107687,-18.236637015304,-14.945535879896],[.0020113162005465,.0019353827024189,-20937793168297e-19]],[-408800,[30.243153324028,38.656267888503,2.938501750218],[-.0016052508674468,.0011183495337525,.00083333973416824]],[-379600,[-27.288984772533,18.643162147874,14.023633623329],[-.0011856388898191,-.0027170609282181,-.00049015526126399]],[-350400,[24.519605196774,-23.245756064727,-14.626862367368],[.0024322321483154,.0016062008146048,-.00023369181613312]],[-321200,[34.505274805875,35.125338586954,.557361475637],[-.0013824391637782,.0013833397561817,.00084823598806262]],[-292e3,[-23.275363915119,25.818514298769,15.055381588598],[-.0016062295460975,-.0023395961498533,-.00024377362639479]],[-262800,[17.050384798092,-27.180376290126,-13.608963321694],[.0028175521080578,.0011358749093955,-.00049548725258825]],[-233600,[38.093671910285,30.880588383337,-1.843688067413],[-.0011317697153459,.0016128814698472,.00084177586176055]],[-204400,[-18.197852930878,31.932869934309,15.438294826279],[-.0019117272501813,-.0019146495909842,-19657304369835e-18]],[-175200,[8.528924039997,-29.618422200048,-11.805400994258],[.0031034370787005,.0005139363329243,-.00077293066202546]],[-146e3,[40.94685725864,25.904973592021,-4.256336240499],[-.00083652705194051,.0018129497136404,.0008156422827306]],[-116800,[-12.326958895325,36.881883446292,15.217158258711],[-.0021166103705038,-.001481442003599,.00017401209844705]],[-87600,[-.633258375909,-30.018759794709,-9.17193287495],[.0032016994581737,-.00025279858672148,-.0010411088271861]],[-58400,[42.936048423883,20.344685584452,-6.588027007912],[-.00050525450073192,.0019910074335507,.00077440196540269]],[-29200,[-5.975910552974,40.61180995846,14.470131723673],[-.0022184202156107,-.0010562361130164,.00033652250216211]],[0,[-9.875369580774,-27.978926224737,-5.753711824704],[.0030287533248818,-.0011276087003636,-.0012651326732361]],[29200,[43.958831986165,14.214147973292,-8.808306227163],[-.00014717608981871,.0021404187242141,.00071486567806614]],[58400,[.67813676352,43.094461639362,13.243238780721],[-.0022358226110718,-.00063233636090933,.00047664798895648]],[87600,[-18.282602096834,-23.30503958666,-1.766620508028],[.0025567245263557,-.0019902940754171,-.0013943491701082]],[116800,[43.873338744526,7.700705617215,-10.814273666425],[.00023174803055677,.0022402163127924,.00062988756452032]],[146e3,[7.392949027906,44.382678951534,11.629500214854],[-.002193281545383,-.00021751799585364,.00059556516201114]],[175200,[-24.981690229261,-16.204012851426,2.466457544298],[.001819398914958,-.0026765419531201,-.0013848283502247]],[204400,[42.530187039511,.845935508021,-12.554907527683],[.00065059779150669,.0022725657282262,.00051133743202822]],[233600,[13.999526486822,44.462363044894,9.669418486465],[-.0021079296569252,.00017533423831993,.00069128485798076]],[262800,[-29.184024803031,-7.371243995762,6.493275957928],[.00093581363109681,-.0030610357109184,-.0012364201089345]],[292e3,[39.831980671753,-6.078405766765,-13.909815358656],[.0011117769689167,.0022362097830152,.00036230548231153]],[321200,[20.294955108476,43.417190420251,7.450091985932],[-.0019742157451535,.00053102050468554,.00075938408813008]],[350400,[-30.66999230216,2.318743558955,9.973480913858],[45605107450676e-18,-.0031308219926928,-.00099066533301924]],[379600,[35.626122155983,-12.897647509224,-14.777586508444],[.0016015684949743,.0021171931182284,.00018002516202204]],[408800,[26.133186148561,41.232139187599,5.00640132622],[-.0017857704419579,.00086046232702817,.00080614690298954]],[438e3,[-29.57674022923,11.863535943587,12.631323039872],[-.00072292830060955,-.0029587820140709,-.000708242964503]],[467200,[29.910805787391,-19.159019294,-15.013363865194],[.0020871080437997,.0018848372554514,-38528655083926e-18]],[496400,[31.375957451819,38.050372720763,2.433138343754],[-.0015546055556611,.0011699815465629,.00083565439266001]],[525600,[-26.360071336928,20.662505904952,14.414696258958],[-.0013142373118349,-.0026236647854842,-.00042542017598193]],[554800,[22.599441488648,-24.508879898306,-14.484045731468],[.0025454108304806,.0014917058755191,-.00030243665086079]],[584e3,[35.877864013014,33.894226366071,-.224524636277],[-.0012941245730845,.0014560427668319,.00084762160640137]],[613200,[-21.538149762417,28.204068269761,15.321973799534],[-.001731211740901,-.0021939631314577,-.0001631691327518]],[642400,[13.971521374415,-28.339941764789,-13.083792871886],[.0029334630526035,.00091860931752944,-.00059939422488627]],[671600,[39.526942044143,28.93989736011,-2.872799527539],[-.0010068481658095,.001702113288809,.00083578230511981]],[700800,[-15.576200701394,34.399412961275,15.466033737854],[-.0020098814612884,-.0017191109825989,70414782780416e-18]],[73e4,[4.24325283709,-30.118201690825,-10.707441231349],[.0031725847067411,.0001609846120227,-.00090672150593868]]];class Sa{constructor(e,t,i){this.x=e,this.y=t,this.z=i}clone(){return new Sa(this.x,this.y,this.z)}ToAstroVector(e){return new Rs(this.x,this.y,this.z,e)}static zero(){return new Sa(0,0,0)}quadrature(){return this.x*this.x+this.y*this.y+this.z*this.z}add(e){return new Sa(this.x+e.x,this.y+e.y,this.z+e.z)}sub(e){return new Sa(this.x-e.x,this.y-e.y,this.z-e.z)}incr(e){this.x+=e.x,this.y+=e.y,this.z+=e.z}decr(e){this.x-=e.x,this.y-=e.y,this.z-=e.z}mul(e){return new Sa(e*this.x,e*this.y,e*this.z)}div(e){return new Sa(this.x/e,this.y/e,this.z/e)}mean(e){return new Sa((this.x+e.x)/2,(this.y+e.y)/2,(this.z+e.z)/2)}neg(){return new Sa(-this.x,-this.y,-this.z)}}class nh{constructor(e,t,i){this.tt=e,this.r=t,this.v=i}clone(){return new nh(this.tt,this.r,this.v)}sub(e){return new nh(this.tt,this.r.sub(e.r),this.v.sub(e.v))}}function Xne(n){let[e,[t,i,a],[r,s,o]]=n;return new nh(e,new Sa(t,i,a),new Sa(r,s,o))}function Jv(n,e,t,i){const a=i/(i+SA),r=Vne(jf[t],e);return n.r.incr(r.r.mul(a)),n.v.incr(r.v.mul(a)),r}function tm(n,e,t){const i=t.sub(n),a=i.quadrature();return i.mul(e/(a*Math.sqrt(a)))}class TA{constructor(e){let t=new nh(e,new Sa(0,0,0),new Sa(0,0,0));this.Jupiter=Jv(t,e,zn.Jupiter,YE),this.Saturn=Jv(t,e,zn.Saturn,qE),this.Uranus=Jv(t,e,zn.Uranus,jE),this.Neptune=Jv(t,e,zn.Neptune,ZE),this.Jupiter.r.decr(t.r),this.Jupiter.v.decr(t.v),this.Saturn.r.decr(t.r),this.Saturn.v.decr(t.v),this.Uranus.r.decr(t.r),this.Uranus.v.decr(t.v),this.Neptune.r.decr(t.r),this.Neptune.v.decr(t.v),this.Sun=new nh(e,t.r.mul(-1),t.v.mul(-1))}Acceleration(e){let t=tm(e,SA,this.Sun.r);return t.incr(tm(e,YE,this.Jupiter.r)),t.incr(tm(e,qE,this.Saturn.r)),t.incr(tm(e,jE,this.Uranus.r)),t.incr(tm(e,ZE,this.Neptune.r)),t}}let WP=class XP{constructor(e,t,i,a){this.tt=e,this.r=t,this.v=i,this.a=a}clone(){return new XP(this.tt,this.r.clone(),this.v.clone(),this.a.clone())}},YP=class{constructor(e,t){this.bary=e,this.grav=t}};function r1(n,e,t,i){return new Sa(e.x+n*(t.x+n*i.x/2),e.y+n*(t.y+n*i.y/2),e.z+n*(t.z+n*i.z/2))}function bO(n,e,t){return new Sa(e.x+n*t.x,e.y+n*t.y,e.z+n*t.z)}function nM(n,e){const t=n-e.tt,i=new TA(n),a=r1(t,e.r,e.v,e.a),r=i.Acceleration(a).mean(e.a),s=r1(t,e.r,e.v,r),o=e.v.add(r.mul(t)),c=i.Acceleration(s),h=new WP(n,s,o,c);return new YP(i,h)}const Yne=[];function qP(n,e){const t=Math.floor(n);return t<0?0:t>=e?e-1:t}function iM(n){const e=Xne(n),t=new TA(e.tt),i=e.r.add(t.Sun.r),a=e.v.add(t.Sun.v),r=t.Acceleration(i),s=new WP(e.tt,i,a,r);return new YP(t,s)}function qne(n,e){const t=Ru[0][0];if(eRu[tM-1][0])return null;const i=qP((e-t)/Wne,tM-1);if(!n[i]){const r=n[i]=[];r[0]=iM(Ru[i]).grav,r[Ho-1]=iM(Ru[i+1]).grav;let s,o=r[0].tt;for(s=1;s0;--s)a[s]=nM(o-=Zf,a[s+1]).grav;for(s=Ho-2;s>0;--s){const c=s/(Ho-1);r[s].r=r[s].r.mul(1-c).add(a[s].r.mul(c)),r[s].v=r[s].v.mul(1-c).add(a[s].v.mul(c)),r[s].a=r[s].a.mul(1-c).add(a[s].a.mul(c))}}return n[i]}function AO(n,e,t){let i=iM(n);const a=Math.ceil((e-i.grav.tt)/t);for(let r=0;r1)throw"Object is too distant for light-travel solver.";const o=e.AddDays(-s);if(i=Math.abs(o.tt-t.tt),i<1e-9)return r;t=o}throw`Light-travel time solver did not converge: dt = ${i}`}class Kne{constructor(e,t,i,a){this.observerBody=e,this.targetBody=t,this.aberration=i,this.observerPos=a}Position(e){this.aberration&&(this.observerPos=Wm(this.observerBody,e));const t=Wm(this.targetBody,e);return new Rs(t.x-this.observerPos.x,t.y-this.observerPos.y,t.z-this.observerPos.z,e)}}function Qne(n,e,t,i){const a=gh(n);if(HP(t)){const o=Wm(t,a),c=Wm(e,a);return new Rs(o.x-c.x,o.y-c.y,o.z-c.z,a)}let r;r=Wm(e,a);const s=new Kne(e,t,i,r);return Zne(o=>s.Position(o),a)}function Jne(n,e,t){const i=gh(e);switch(n){case zn.Earth:return new Rs(0,0,0,i);case zn.Moon:return KE(i);default:const a=Qne(i,zn.Earth,n,t);return a.t=i,a}}var wO;(function(n){n[n.Pericenter=0]="Pericenter",n[n.Apocenter=1]="Apocenter"})(wO||(wO={}));function $ne(n,e){return new Pd([[e.rot[0][0]*n.rot[0][0]+e.rot[1][0]*n.rot[0][1]+e.rot[2][0]*n.rot[0][2],e.rot[0][1]*n.rot[0][0]+e.rot[1][1]*n.rot[0][1]+e.rot[2][1]*n.rot[0][2],e.rot[0][2]*n.rot[0][0]+e.rot[1][2]*n.rot[0][1]+e.rot[2][2]*n.rot[0][2]],[e.rot[0][0]*n.rot[1][0]+e.rot[1][0]*n.rot[1][1]+e.rot[2][0]*n.rot[1][2],e.rot[0][1]*n.rot[1][0]+e.rot[1][1]*n.rot[1][1]+e.rot[2][1]*n.rot[1][2],e.rot[0][2]*n.rot[1][0]+e.rot[1][2]*n.rot[1][1]+e.rot[2][2]*n.rot[1][2]],[e.rot[0][0]*n.rot[2][0]+e.rot[1][0]*n.rot[2][1]+e.rot[2][0]*n.rot[2][2],e.rot[0][1]*n.rot[2][0]+e.rot[1][1]*n.rot[2][1]+e.rot[2][1]*n.rot[2][2],e.rot[0][2]*n.rot[2][0]+e.rot[1][2]*n.rot[2][1]+e.rot[2][2]*n.rot[2][2]]])}function eie(n,e,t){const i=T_(t)*th,a=Math.cos(i),r=Math.sin(i),s=(e+1)%3,o=(e+2)%3,c=e;let h=[[0,0,0],[0,0,0],[0,0,0]];return h[s][s]=a*n.rot[s][s]-r*n.rot[s][o],h[s][o]=r*n.rot[s][s]+a*n.rot[s][o],h[s][c]=n.rot[s][c],h[o][s]=a*n.rot[o][s]-r*n.rot[o][o],h[o][o]=r*n.rot[o][s]+a*n.rot[o][o],h[o][c]=n.rot[o][c],h[c][s]=a*n.rot[c][s]-r*n.rot[c][o],h[c][o]=r*n.rot[c][s]+a*n.rot[c][o],h[c][c]=n.rot[c][c],new Pd(h)}function tie(n,e){e=gh(e);const t=n.lat*th,i=n.lon*th,a=n.dist*Math.cos(t);return new Rs(a*Math.cos(i),a*Math.sin(i),n.dist*Math.sin(t),e)}function nie(n){n=gh(n);const e=VP(n,sl.From2000),t=Hne(n,sl.From2000);return $ne(e,t)}var RO;(function(n){n.Penumbral="penumbral",n.Partial="partial",n.Annular="annular",n.Total="total"})(RO||(RO={}));var CO;(function(n){n[n.Invalid=0]="Invalid",n[n.Ascending=1]="Ascending",n[n.Descending=-1]="Descending"})(CO||(CO={}));function EA(n){return n instanceof hc?n:new hc(n instanceof Date?n:new Date(n))}function iie(n,e=new L){const{x:t,y:i,z:a}=n;return e.set(t,i,a)}function aie(n,e=new ke){const[t,i,a]=n.rot;return e.set(t[0],i[0],a[0],0,t[1],i[1],a[1],0,t[2],i[2],a[2],0,0,0,0,1)}function rie(n,e=new ke){const t=EA(n),i=eie(nie(t),2,-15*Bne(t));return aie(i,e)}function jP(n,e,t,i,a){const r=Jne(n,e,!1);return iie(r,t),i!=null,t.normalize()}function sie(n,e=new L,t){return jP(zn.Sun,EA(n),e,t)}function oie(n,e=new L,t){return jP(zn.Moon,EA(n),e,t)}const lie=`precision highp float; -precision highp sampler3D; - -#include "bruneton/definitions" -#include "bruneton/common" -#include "bruneton/precompute" - -uniform AtmosphereParameters ATMOSPHERE; - -uniform sampler2D transmittanceTexture; - -layout(location = 0) out vec4 outputColor; - -void main() { - vec3 deltaIrradiance; - vec3 irradiance; - deltaIrradiance = ComputeDirectIrradianceTexture( - ATMOSPHERE, - transmittanceTexture, - gl_FragCoord.xy - ); - irradiance = vec3(0.0); - outputColor = vec4(OUTPUT, 1.0); -} -`,cie=`precision highp float; -precision highp sampler3D; - -#include "bruneton/definitions" -#include "bruneton/common" -#include "bruneton/precompute" - -uniform AtmosphereParameters ATMOSPHERE; - -uniform mat3 luminanceFromRadiance; -uniform sampler3D singleRayleighScatteringTexture; -uniform sampler3D singleMieScatteringTexture; -uniform sampler3D multipleScatteringTexture; -uniform int scatteringOrder; - -layout(location = 0) out vec4 outputColor; - -void main() { - vec3 deltaIrradiance; - vec3 irradiance; - deltaIrradiance = ComputeIndirectIrradianceTexture( - ATMOSPHERE, - singleRayleighScatteringTexture, - singleMieScatteringTexture, - multipleScatteringTexture, - gl_FragCoord.xy, - scatteringOrder - ); - irradiance = luminanceFromRadiance * deltaIrradiance; - outputColor = vec4(OUTPUT, 1.0); -} -`,uie=`precision highp float; -precision highp sampler3D; - -#include "bruneton/definitions" -#include "bruneton/common" -#include "bruneton/precompute" - -uniform AtmosphereParameters ATMOSPHERE; - -uniform mat3 luminanceFromRadiance; -uniform sampler2D transmittanceTexture; -uniform sampler3D scatteringDensityTexture; -uniform int layer; - -layout(location = 0) out vec4 outputColor; - -void main() { - vec4 deltaMultipleScattering; - vec4 scattering; - float nu; - deltaMultipleScattering.rgb = ComputeMultipleScatteringTexture( - ATMOSPHERE, - transmittanceTexture, - scatteringDensityTexture, - vec3(gl_FragCoord.xy, float(layer) + 0.5), - nu - ); - deltaMultipleScattering.a = 1.0; - scattering = vec4( - luminanceFromRadiance * deltaMultipleScattering.rgb / RayleighPhaseFunction(nu), - 0.0 - ); - outputColor = OUTPUT; -} -`,hie=`precision highp float; -precision highp sampler3D; - -#include "bruneton/definitions" -#include "bruneton/common" -#include "bruneton/precompute" - -uniform AtmosphereParameters ATMOSPHERE; - -uniform sampler2D transmittanceTexture; -uniform sampler3D singleRayleighScatteringTexture; -uniform sampler3D singleMieScatteringTexture; -uniform sampler3D multipleScatteringTexture; -uniform sampler2D irradianceTexture; -uniform int scatteringOrder; -uniform int layer; - -layout(location = 0) out vec4 scatteringDensity; - -void main() { - scatteringDensity.rgb = ComputeScatteringDensityTexture( - ATMOSPHERE, - transmittanceTexture, - singleRayleighScatteringTexture, - singleMieScatteringTexture, - multipleScatteringTexture, - irradianceTexture, - vec3(gl_FragCoord.xy, float(layer) + 0.5), - scatteringOrder - ); - scatteringDensity.a = 1.0; -} -`,fie=`precision highp float; -precision highp sampler3D; - -#include "bruneton/definitions" -#include "bruneton/common" -#include "bruneton/precompute" - -uniform AtmosphereParameters ATMOSPHERE; - -uniform mat3 luminanceFromRadiance; -uniform sampler2D transmittanceTexture; -uniform int layer; - -layout(location = 0) out vec4 outputColor; - -void main() { - vec4 deltaRayleigh; - vec4 deltaMie; - vec4 scattering; - vec4 singleMieScattering; - ComputeSingleScatteringTexture( - ATMOSPHERE, - transmittanceTexture, - vec3(gl_FragCoord.xy, float(layer) + 0.5), - deltaRayleigh.rgb, - deltaMie.rgb - ); - deltaRayleigh.a = 1.0; - deltaMie.a = 1.0; - scattering = vec4( - luminanceFromRadiance * deltaRayleigh.rgb, - (luminanceFromRadiance * deltaMie.rgb).r - ); - singleMieScattering.rgb = luminanceFromRadiance * deltaMie.rgb; - singleMieScattering.a = 1.0; - outputColor = OUTPUT; -} -`,die=`precision highp float; -precision highp sampler3D; - -#include "bruneton/definitions" -#include "bruneton/common" -#include "bruneton/precompute" - -uniform AtmosphereParameters ATMOSPHERE; - -layout(location = 0) out vec4 transmittance; - -void main() { - transmittance.rgb = ComputeTransmittanceToTopAtmosphereBoundaryTexture( - ATMOSPHERE, - gl_FragCoord.xy - ); - transmittance.a = 1.0; -} -`,pie=` - precision highp float; - in vec2 position; - void main() { - gl_Position = vec4(position, 1.0, 1.0); - } -`;function s1(n,e,t){const i=new xi(e,t,{depthBuffer:!1,type:n,format:$n}),a=i.texture;return a.minFilter=Ht,a.magFilter=Ht,a.wrapS=Pi,a.wrapT=Pi,a.colorSpace=Da,i}function od(n,e,t,i){const a=new HU(e,t,i,{depthBuffer:!1,type:n,format:$n}),r=a.texture;return r.minFilter=Ht,r.magFilter=Ht,r.wrapS=Pi,r.wrapT=Pi,r.wrapR=Pi,r.colorSpace=Da,a}function mie(n){const e=n[Symbol.iterator]();return new Promise((t,i)=>{const a=()=>{try{const{value:r,done:s}=e.next();s===!0?t(r):TO(a)}catch(r){i(r instanceof Error?r:new Error)}};TO(a)})}async function NO(n,e,t){const{width:i,height:a}=e,r=t.type===Xn?new Uint16Array(i*a*4):new Float32Array(i*a*4);await n.readRenderTargetPixelsAsync(e,0,0,e.width,e.height,r),t.userData.imageData=r}class gie{constructor(e){this.lambdas=new L,this.luminanceFromRadiance=new Et,e===Xn&&(this.opticalDepth=s1(e,ep,tp)),this.deltaIrradiance=s1(e,Jd,$d),this.deltaRayleighScattering=od(e,zu,Bu,Hu),this.deltaMieScattering=od(e,zu,Bu,Hu),this.deltaScatteringDensity=od(e,zu,Bu,Hu),this.deltaMultipleScattering=this.deltaRayleighScattering}dispose(){var e;(e=this.opticalDepth)==null||e.dispose(),this.deltaIrradiance.dispose(),this.deltaRayleighScattering.dispose(),this.deltaMieScattering.dispose(),this.deltaScatteringDensity.dispose()}}class Ef extends hh{constructor(e){super({glslVersion:ro,vertexShader:pie,...e,defines:{TRANSMITTANCE_TEXTURE_WIDTH:ep.toFixed(0),TRANSMITTANCE_TEXTURE_HEIGHT:tp.toFixed(0),SCATTERING_TEXTURE_R_SIZE:gy.toFixed(0),SCATTERING_TEXTURE_MU_SIZE:vy.toFixed(0),SCATTERING_TEXTURE_MU_S_SIZE:_y.toFixed(0),SCATTERING_TEXTURE_NU_SIZE:xy.toFixed(0),IRRADIANCE_TEXTURE_WIDTH:Jd.toFixed(0),IRRADIANCE_TEXTURE_HEIGHT:$d.toFixed(0),...e.defines}})}set additive(e){this.transparent=e,this.blending=e?ub:Ta,this.blendEquation=Js,this.blendEquationAlpha=Js,this.blendSrc=kf,this.blendDst=kf,this.blendSrcAlpha=kf,this.blendDstAlpha=kf}setUniforms(e){const t=this.uniforms;t.luminanceFromRadiance!=null&&t.luminanceFromRadiance.value.copy(e.luminanceFromRadiance),t.singleRayleighScatteringTexture!=null&&(t.singleRayleighScatteringTexture.value=e.deltaRayleighScattering.texture),t.singleMieScatteringTexture!=null&&(t.singleMieScatteringTexture.value=e.deltaMieScattering.texture),t.multipleScatteringTexture!=null&&(t.multipleScatteringTexture.value=e.deltaMultipleScattering.texture),t.scatteringDensityTexture!=null&&(t.scatteringDensityTexture.value=e.deltaScatteringDensity.texture),t.irradianceTexture!=null&&(t.irradianceTexture.value=e.deltaIrradiance.texture)}}class vie{constructor(e,{type:t=iP(e)?si:Xn,combinedScattering:i=!0,higherOrderScattering:a=!0}={}){var r,s;this.transmittanceMaterial=new Ef({fragmentShader:Na(die,{bruneton:{common:Ks,definitions:Qs,precompute:yf}})}),this.directIrradianceMaterial=new Ef({fragmentShader:Na(lie,{bruneton:{common:Ks,definitions:Qs,precompute:yf}}),uniforms:{transmittanceTexture:new J(null)}}),this.singleScatteringMaterial=new Ef({fragmentShader:Na(fie,{bruneton:{common:Ks,definitions:Qs,precompute:yf}}),uniforms:{luminanceFromRadiance:new J(new Et),transmittanceTexture:new J(null),layer:new J(0)}}),this.scatteringDensityMaterial=new Ef({fragmentShader:Na(hie,{bruneton:{common:Ks,definitions:Qs,precompute:yf}}),uniforms:{transmittanceTexture:new J(null),singleRayleighScatteringTexture:new J(null),singleMieScatteringTexture:new J(null),multipleScatteringTexture:new J(null),irradianceTexture:new J(null),scatteringOrder:new J(0),layer:new J(0)}}),this.indirectIrradianceMaterial=new Ef({fragmentShader:Na(cie,{bruneton:{common:Ks,definitions:Qs,precompute:yf}}),uniforms:{luminanceFromRadiance:new J(new Et),singleRayleighScatteringTexture:new J(null),singleMieScatteringTexture:new J(null),multipleScatteringTexture:new J(null),scatteringOrder:new J(0)}}),this.multipleScatteringMaterial=new Ef({fragmentShader:Na(uie,{bruneton:{common:Ks,definitions:Qs,precompute:yf}}),uniforms:{luminanceFromRadiance:new J(new Et),transmittanceTexture:new J(null),scatteringDensityTexture:new J(null),layer:new J(0)}}),this.mesh=new oi(new uh(2,2)),this.scene=new Rd().add(this.mesh),this.camera=new bc,this.updating=!1,this.renderer=e,this.type=t,this.transmittanceRenderTarget=s1(t,ep,tp),this.scatteringRenderTarget=od(t,zu,Bu,Hu),this.irradianceRenderTarget=s1(t,Jd,$d),i||(this.singleMieScatteringRenderTarget=od(t,zu,Bu,Hu)),a&&(this.higherOrderScatteringRenderTarget=od(t,zu,Bu,Hu)),this.textures={transmittanceTexture:this.transmittanceRenderTarget.texture,scatteringTexture:this.scatteringRenderTarget.texture,irradianceTexture:this.irradianceRenderTarget.texture,singleMieScatteringTexture:(r=this.singleMieScatteringRenderTarget)==null?void 0:r.texture,higherOrderScatteringTexture:(s=this.higherOrderScatteringRenderTarget)==null?void 0:s.texture}}render3DRenderTarget(e,t){for(let i=0;i{this.dispose(e),this.disposeQueue=void 0};return}const{textures:t=!0}=e;t||(this.transmittanceRenderTarget.textures.splice(0,1),this.scatteringRenderTarget.textures.splice(0,1),this.irradianceRenderTarget.textures.splice(0,1),(i=this.singleMieScatteringRenderTarget)==null||i.textures.splice(0,1),(a=this.higherOrderScatteringRenderTarget)==null||a.textures.splice(0,1)),this.transmittanceRenderTarget.dispose(),this.scatteringRenderTarget.dispose(),this.irradianceRenderTarget.dispose(),(r=this.singleMieScatteringRenderTarget)==null||r.dispose(),(s=this.higherOrderScatteringRenderTarget)==null||s.dispose(),this.transmittanceMaterial.dispose(),this.directIrradianceMaterial.dispose(),this.singleScatteringMaterial.dispose(),this.scatteringDensityMaterial.dispose(),this.indirectIrradianceMaterial.dispose(),this.multipleScatteringMaterial.dispose(),this.mesh.geometry.dispose()}}function _ie(n){var e=[];if(n.length===0)return"";if(typeof n[0]!="string")throw new TypeError("Url must be a string. Received "+n[0]);if(n[0].match(/^[^/:]+:\/*$/)&&n.length>1){var t=n.shift();n[0]=t+n[0]}n[0].match(/^file:\/\/\//)?n[0]=n[0].replace(/^([^/:]+):\/*/,"$1:///"):n[0]=n[0].replace(/^([^/:]+):\/*/,"$1://");for(var i=0;i0&&(a=a.replace(/^[\/]+/,"")),i0?"?":"")+s.join("&"),r}function xie(){var n;return typeof arguments[0]=="object"?n=arguments[0]:n=[].slice.call(arguments),_ie(n)}const DO={width:ep,height:tp},Mf={width:zu,height:Bu,depth:Hu},OO={width:Jd,height:$d};class ZP extends Mi{constructor({format:e="exr",type:t=Xn,combinedScattering:i=!0,higherOrderScattering:a=!0}={},r){super(r),this.format=e,this.type=t,this.combinedScattering=i,this.higherOrderScattering=a}setType(e){return this.type=iP(e)?si:Xn,this}setTypeFromRenderer(e){return this.setType(e)}load(e,t,i,a){const r={},s=({key:o,loader:c,path:h})=>(c.setRequestHeader(this.requestHeader),c.setPath(this.path),c.setWithCredentials(this.withCredentials),c.load(xie(e,h),f=>{f.type=this.type,this.type===si&&(f.image.data=new Float32Array(new ul(f.image.data.buffer))),f.minFilter=Ht,f.magFilter=Ht,r[`${o}Texture`]=f,r.irradianceTexture!=null&&r.scatteringTexture!=null&&r.transmittanceTexture!=null&&(this.combinedScattering||r.singleMieScatteringTexture!=null)&&(!this.higherOrderScattering||r.higherOrderScatteringTexture!=null)&&(t==null||t(r))},i,a));return this.format==="exr"?{transmittanceTexture:s({key:"transmittance",loader:new SO(DO,this.manager),path:"transmittance.exr"}),scatteringTexture:s({key:"scattering",loader:new e3(Mf,this.manager),path:"scattering.exr"}),irradianceTexture:s({key:"irradiance",loader:new SO(OO,this.manager),path:"irradiance.exr"}),singleMieScatteringTexture:this.combinedScattering?void 0:s({key:"singleMieScattering",loader:new e3(Mf,this.manager),path:"single_mie_scattering.exr"}),higherOrderScatteringTexture:this.higherOrderScattering?s({key:"higherOrderScattering",loader:new e3(Mf,this.manager),path:"higher_order_scattering.exr"}):void 0}:{transmittanceTexture:s({key:"transmittance",loader:new Su($a,em,DO,this.manager),path:"transmittance.bin"}),scatteringTexture:s({key:"scattering",loader:new Su(as,em,Mf,this.manager),path:"scattering.bin"}),irradianceTexture:s({key:"irradiance",loader:new Su($a,em,OO,this.manager),path:"irradiance.bin"}),singleMieScatteringTexture:this.combinedScattering?void 0:s({key:"singleMieScattering",loader:new Su(as,em,Mf,this.manager),path:"single_mie_scattering.bin"}),higherOrderScatteringTexture:this.higherOrderScattering?s({key:"higherOrderScattering",loader:new Su(as,em,Mf,this.manager),path:"higher_order_scattering.bin"}):void 0}}}const yie=`precision highp float; -precision highp sampler3D; - -#define RECIPROCAL_PI 0.3183098861837907 - -#include "core/raySphereIntersection" - -#include "bruneton/definitions" - -uniform AtmosphereParameters ATMOSPHERE; -uniform vec3 SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; -uniform vec3 SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; - -uniform sampler2D transmittance_texture; -uniform sampler3D scattering_texture; -uniform sampler2D irradiance_texture; -uniform sampler3D single_mie_scattering_texture; -uniform sampler3D higher_order_scattering_texture; - -#include "bruneton/common" -#include "bruneton/runtime" - -#include "sky" - -uniform vec3 sunDirection; -uniform vec3 moonDirection; -uniform float moonAngularRadius; -uniform float lunarRadianceScale; -uniform vec3 groundAlbedo; - -#ifdef HAS_SHADOW_LENGTH -uniform sampler2D shadowLengthBuffer; -#endif // HAS_SHADOW_LENGTH - -in vec2 vUv; -in vec3 vCameraPosition; -in vec3 vRayDirection; - -layout(location = 0) out vec4 outputColor; - -#include - -void main() { - float shadowLength = 0.0; - #ifdef HAS_SHADOW_LENGTH - shadowLength = texture(shadowLengthBuffer, vUv).r; - #endif // HAS_SHADOW_LENGTH - - vec3 cameraPosition = vCameraPosition; - vec3 rayDirection = normalize(vRayDirection); - - #ifdef GROUND_ALBEDO - - float r = length(cameraPosition); - float mu = dot(cameraPosition, rayDirection) / r; - bool intersectsGround = RayIntersectsGround(ATMOSPHERE, r, mu); - if (intersectsGround) { - float distanceToGround = raySphereFirstIntersection( - cameraPosition, - rayDirection, - ATMOSPHERE.bottom_radius - ); - vec3 groundPosition = rayDirection * distanceToGround + cameraPosition; - vec3 surfaceNormal = normalize(groundPosition); - vec3 skyIrradiance; - vec3 sunIrradiance = GetSunAndSkyIrradiance( - cameraPosition, - surfaceNormal, - sunDirection, - skyIrradiance - ); - vec3 transmittance; - vec3 inscatter = GetSkyRadianceToPoint( - cameraPosition, - ATMOSPHERE.bottom_radius * surfaceNormal, - shadowLength, - sunDirection, - transmittance - ); - vec3 radiance = groundAlbedo * RECIPROCAL_PI * (sunIrradiance + skyIrradiance); - outputColor.rgb = radiance * transmittance + inscatter; - } else { - outputColor.rgb = getSkyRadiance( - cameraPosition, - rayDirection, - shadowLength, - sunDirection, - moonDirection, - moonAngularRadius, - lunarRadianceScale - ); - } - - #else // GROUND_ALBEDO - - outputColor.rgb = getSkyRadiance( - cameraPosition, - rayDirection, - shadowLength, - sunDirection, - moonDirection, - moonAngularRadius, - lunarRadianceScale - ); - - #endif // GROUND_ALBEDO - - outputColor.a = 1.0; - - #include -} -`,Sie=`precision highp float; -precision highp sampler3D; - -uniform mat4 inverseProjectionMatrix; -uniform mat4 inverseViewMatrix; -uniform vec3 cameraPosition; -uniform mat4 worldToECEFMatrix; -uniform vec3 altitudeCorrection; - -layout(location = 0) in vec3 position; - -out vec2 vUv; -out vec3 vCameraPosition; -out vec3 vRayDirection; - -void getCameraRay(out vec3 origin, out vec3 direction) { - bool isPerspective = inverseProjectionMatrix[2][3] != 0.0; // 4th entry in the 3rd column - - if (isPerspective) { - // Calculate the camera ray for a perspective camera. - vec4 viewPosition = inverseProjectionMatrix * vec4(position, 1.0); - vec4 worldDirection = inverseViewMatrix * vec4(viewPosition.xyz, 0.0); - origin = cameraPosition; - direction = worldDirection.xyz; - } else { - // Unprojected points to calculate direction. - vec4 nearPoint = inverseProjectionMatrix * vec4(position.xy, -1.0, 1.0); - vec4 farPoint = inverseProjectionMatrix * vec4(position.xy, -0.9, 1.0); - nearPoint /= nearPoint.w; - farPoint /= farPoint.w; - - // Calculate world values - vec4 worldDirection = inverseViewMatrix * vec4(farPoint.xyz - nearPoint.xyz, 0.0); - vec4 worldOrigin = inverseViewMatrix * nearPoint; - - // Outputs - direction = worldDirection.xyz; - origin = worldOrigin.xyz; - } -} - -void main() { - vUv = position.xy * 0.5 + 0.5; - - vec3 direction, origin; - getCameraRay(origin, direction); - - vec3 cameraPositionECEF = (worldToECEFMatrix * vec4(origin, 1.0)).xyz; - vCameraPosition = (cameraPositionECEF + altitudeCorrection) * METER_TO_LENGTH_UNIT; - vRayDirection = (worldToECEFMatrix * vec4(direction, 0.0)).xyz; - - gl_Position = vec4(position.xy, 1.0, 1.0); -} -`;var Tie=Object.defineProperty,MA=(n,e,t,i)=>{for(var a=void 0,r=n.length-1,s;r>=0;r--)(s=n[r])&&(a=s(e,t,a)||a);return a&&Tie(e,t,a),a};const Eie={...yA,sun:!0,moon:!0,moonAngularRadius:.0045,lunarRadianceScale:1,ground:!0,groundAlbedo:new je(0)};class bA extends Z0{constructor(e){const{sun:t,moon:i,moonDirection:a,moonAngularRadius:r,lunarRadianceScale:s,ground:o,groundAlbedo:c,...h}={...Eie,...e};super({name:"SkyMaterial",glslVersion:ro,vertexShader:Sie,fragmentShader:Na(yie,{core:{raySphereIntersection:my},bruneton:{common:Ks,definitions:Qs,runtime:yy},sky:PP}),...h,uniforms:{inverseProjectionMatrix:new J(new ke),inverseViewMatrix:new J(new ke),moonDirection:new J((a==null?void 0:a.clone())??new L),moonAngularRadius:new J(r),lunarRadianceScale:new J(s),groundAlbedo:new J(c.clone()),shadowLengthBuffer:new J(null),...h.uniforms},defines:{PERSPECTIVE_CAMERA:"1"},depthTest:!0}),this.shadowLength=null,this.sun=t,this.moon=i,this.ground=o}onBeforeRender(e,t,i,a,r,s){super.onBeforeRender(e,t,i,a,r,s);const{uniforms:o,defines:c}=this;o.inverseProjectionMatrix.value.copy(i.projectionMatrixInverse),o.inverseViewMatrix.value.copy(i.matrixWorld);const h=c.PERSPECTIVE_CAMERA!=null,f=i.isPerspectiveCamera===!0;f!==h&&(f?c.PERSPECTIVE_CAMERA="1":delete c.PERSPECTIVE_CAMERA,this.needsUpdate=!0);const d=this.groundAlbedo,m=c.GROUND_ALBEDO!=null,g=d.r!==0||d.g!==0||d.b!==0;g!==m&&(g?this.defines.GROUND_ALBEDO="1":delete this.defines.GROUND_ALBEDO,this.needsUpdate=!0);const x=this.shadowLength,T=c.HAS_SHADOW_LENGTH!=null,y=x!=null;y!==T&&(y?c.HAS_SHADOW_LENGTH="1":(delete c.HAS_SHADOW_LENGTH,o.shadowLengthBuffer.value=null),this.needsUpdate=!0),y&&(o.shadowLengthBuffer.value=x.map)}get moonDirection(){return this.uniforms.moonDirection.value}get moonAngularRadius(){return this.uniforms.moonAngularRadius.value}set moonAngularRadius(e){this.uniforms.moonAngularRadius.value=e}get lunarRadianceScale(){return this.uniforms.lunarRadianceScale.value}set lunarRadianceScale(e){this.uniforms.lunarRadianceScale.value=e}get groundAlbedo(){return this.uniforms.groundAlbedo.value}}MA([dn("SUN")],bA.prototype,"sun");MA([dn("MOON")],bA.prototype,"moon");MA([dn("GROUND")],bA.prototype,"ground");const Mie=`precision highp float; -precision highp sampler3D; - -#include "bruneton/definitions" - -uniform AtmosphereParameters ATMOSPHERE; -uniform vec3 SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; -uniform vec3 SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; - -uniform sampler2D transmittance_texture; -uniform sampler3D scattering_texture; -uniform sampler2D irradiance_texture; -uniform sampler3D single_mie_scattering_texture; -uniform sampler3D higher_order_scattering_texture; - -#include "bruneton/common" -#include "bruneton/runtime" - -uniform vec3 sunDirection; - -in vec3 vCameraPosition; -in vec3 vRayDirection; - -layout(location = 0) out vec4 outputColor; - -#include - -in vec3 vColor; - -void main() { - #if !defined(PERSPECTIVE_CAMERA) - outputColor = vec4(0.0); - discard; // Rendering celestial objects without perspective doesn't make sense. - #endif // !defined(PERSPECTIVE_CAMERA) - - #ifdef BACKGROUND - vec3 rayDirection = normalize(vRayDirection); - float r = length(vCameraPosition); - float mu = dot(vCameraPosition, rayDirection) / r; - - if (RayIntersectsGround(ATMOSPHERE, r, mu)) { - discard; - } - - vec3 transmittance; - vec3 radiance = GetSkyRadiance( - vCameraPosition, - normalize(vRayDirection), - 0.0, // Shadow length - sunDirection, - transmittance - ); - radiance += transmittance * vColor; - outputColor = vec4(radiance, 1.0); - #else // BACKGROUND - outputColor = vec4(vColor, 1.0); - #endif // BACKGROUND - - #include -} -`,bie=`precision highp float; -precision highp sampler3D; - -#define saturate(x) clamp(x, 0.0, 1.0) - -uniform mat4 projectionMatrix; -uniform mat4 modelViewMatrix; -uniform mat4 viewMatrix; -uniform mat4 matrixWorld; -uniform vec3 cameraPosition; -uniform float cameraFar; -uniform mat4 worldToECEFMatrix; -uniform vec3 altitudeCorrection; -uniform float pointSize; -uniform vec2 magnitudeRange; -uniform float intensity; - -layout(location = 0) in vec3 position; -layout(location = 1) in float magnitude; -layout(location = 2) in vec3 color; - -out vec3 vCameraPosition; -out vec3 vRayDirection; -out vec3 vEllipsoidCenter; -out vec3 vColor; - -void main() { - // Magnitude is stored between 0 to 1 within the given range. - float m = mix(magnitudeRange.x, magnitudeRange.y, magnitude); - vec3 v = pow(vec3(10.0), -vec3(magnitudeRange, m) / 2.5); - vColor = vec3(intensity * color); - vColor *= saturate((v.z - v.y) / (v.x - v.y)); - - #ifdef BACKGROUND - vec3 worldDirection = normalize(matrixWorld * vec4(position, 1.0)).xyz; - vec3 cameraPositionECEF = (worldToECEFMatrix * vec4(cameraPosition, 1.0)).xyz; - vCameraPosition = (cameraPositionECEF + altitudeCorrection) * METER_TO_LENGTH_UNIT; - vRayDirection = (worldToECEFMatrix * vec4(worldDirection, 0.0)).xyz; - gl_Position = - projectionMatrix * viewMatrix * vec4(cameraPosition + worldDirection * cameraFar, 1.0); - #else // BACKGROUND - gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); - #endif // BACKGROUND - - gl_PointSize = pointSize; -} -`;var Aie=Object.defineProperty,KP=(n,e,t,i)=>{for(var a=void 0,r=n.length-1,s;r>=0;r--)(s=n[r])&&(a=s(e,t,a)||a);return a&&Aie(e,t,a),a};const wie={...yA,pointSize:1,intensity:1,background:!0,ground:!0};let QP=class extends Z0{constructor(e){const{pointSize:t,radianceScale:i,intensity:a,background:r,ground:s,...o}={...wie,...e};super({name:"StarsMaterial",glslVersion:ro,vertexShader:bie,fragmentShader:Na(Mie,{bruneton:{common:Ks,definitions:Qs,runtime:yy}}),...o,uniforms:{projectionMatrix:new J(new ke),modelViewMatrix:new J(new ke),viewMatrix:new J(new ke),matrixWorld:new J(new ke),cameraFar:new J(0),pointSize:new J(0),magnitudeRange:new J(new de(-2,8)),intensity:new J(i??a),...o.uniforms},defines:{PERSPECTIVE_CAMERA:"1"}}),this.pointSize=t,this.background=r,this.ground=s}onBeforeRender(e,t,i,a,r,s){super.onBeforeRender(e,t,i,a,r,s);const o=this.uniforms;o.projectionMatrix.value.copy(i.projectionMatrix),o.modelViewMatrix.value.copy(i.modelViewMatrix),o.viewMatrix.value.copy(i.matrixWorldInverse),o.matrixWorld.value.copy(r.matrixWorld),o.cameraFar.value=i.far,o.pointSize.value=this.pointSize*e.getPixelRatio();const c=i.isPerspectiveCamera===!0;this.defines.PERSPECTIVE_CAMERA!=null!==c&&(c?this.defines.PERSPECTIVE_CAMERA="1":delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0)}get magnitudeRange(){return this.uniforms.magnitudeRange.value}get radianceScale(){return this.intensity}set radianceScale(e){this.intensity=e}get intensity(){return this.uniforms.intensity.value}set intensity(e){this.uniforms.intensity.value=e}};KP([dn("BACKGROUND")],QP.prototype,"background");KP([dn("GROUND")],QP.prototype,"ground");const AA=Me.createContext({}),Rie=({ref:n,textures:e,ellipsoid:t=_0.WGS84,correctAltitude:i=!0,ground:a=!0,date:r,children:s})=>{const o=Me.useRef({sunDirection:new L,moonDirection:new L,worldToECEFMatrix:new ke,inertialToECEFMatrix:new ke,overlay:null,shadow:null,shadowLength:null,lightingMask:null}),c=Oi(({gl:T})=>T),h=Me.useMemo(()=>typeof e=="string"?new ZP().setType(c).load(e):void 0,[e,c]);Me.useEffect(()=>{if(h!=null)return()=>{for(const T of Object.values(h))T==null||T.dispose()}},[h]);const f=Me.useMemo(()=>e==null?new vie(c):void 0,[e,c]);Me.useEffect(()=>{if(f!=null)return f.update().catch(T=>{console.error(T)}),()=>{f.dispose()}},[f]);const d=(f==null?void 0:f.textures)??(typeof e=="string"?h:e),m=Me.useMemo(()=>({textures:d,ellipsoid:t,correctAltitude:i,ground:a,transientStates:o.current}),[d,t,i,a]),g=Me.useMemo(()=>{const{sunDirection:T,moonDirection:y,inertialToECEFMatrix:v}=o.current;return S=>{rie(S,v),sie(S,T).applyMatrix4(v),oie(S,y).applyMatrix4(v)}},[]),x=r!=null&&!isNaN(+r)?+r:void 0;return Me.useEffect(()=>{x!=null&&g(x)},[x,g]),Me.useImperativeHandle(n,()=>({...o.current,textures:d,updateByDate:g}),[d,g]),Rt.jsx(AA.Provider,{value:m,children:s})};function JP(n){const{irradianceTexture:e,scatteringTexture:t,transmittanceTexture:i,singleMieScatteringTexture:a,higherOrderScatteringTexture:r,ellipsoid:s,correctAltitude:o,sunDirection:c,sunAngularRadius:h,ground:f,renderTargetCount:d,...m}=n;return[{irradianceTexture:e,scatteringTexture:t,transmittanceTexture:i,singleMieScatteringTexture:a,higherOrderScatteringTexture:r,ellipsoid:s,correctAltitude:o,sunDirection:c,sunAngularRadius:h,ground:f,renderTargetCount:d},m]}function Cie(n){const e=Me.useMemo(()=>typeof n=="string"?new NP().load(n):void 0,[n]);return Me.useEffect(()=>{if(e!=null)return()=>{e.dispose()}},[e]),(typeof n=="string"?e:n)??null}const Nie=({ref:n,stbnTexture:e=aP,...t})=>{const{textures:i,transientStates:a,...r}=Me.useContext(AA),[s,{blendFunction:o,...c}]=JP({...zP,...r,...i,...t}),h=Me.useContext(lA),{normalPass:f,camera:d}=h,m="geometryPass"in h&&h.geometryPass instanceof oA&&"geometryTexture"in h.geometryPass&&h.geometryPass.geometryTexture instanceof Nn?h.geometryPass.geometryTexture:void 0,g=Me.useMemo(()=>new Ba(void 0,{blendFunction:o}),[o]);Me.useEffect(()=>()=>{g.dispose()},[g]);const[x,T]=Me.useState(!1);cl(()=>{a!=null&&(g.sunDirection.copy(a.sunDirection),g.moonDirection.copy(a.moonDirection),g.worldToECEFMatrix.copy(a.worldToECEFMatrix),g.overlay=a.overlay,g.shadow=a.shadow,g.shadowLength=a.shadowLength,g.lightingMask=a.lightingMask,!x&&g.shadow!=null&&T(!0))});const y=Cie(x?e:void 0);return Rt.jsx("primitive",{ref:n,object:g,mainCamera:d,normalBuffer:m??(f==null?void 0:f.texture)??null,...s,...c,stbnTexture:y,octEncodedNormal:m!=null})};function Die(n){return e=>{for(const t of n)aM(t,e)}}function Oie(n){return e=>{const t=[];for(const i of n){const a=aM(i,e),r=typeof a=="function";t.push(r?a:()=>aM(i,null))}return()=>{for(const i of t)i()}}}function aM(n,e){if(typeof n=="function")return n(e);n&&(n.current=e)}parseInt(Me.version.split(".")[0],10)>=19;new ZP;const LO=yy,IO=Ks,UO=Qs;class Sy{constructor(e=0,t=0,i=0,a=0){this.expTerm=e,this.exponent=t,this.linearTerm=i,this.constantTerm=a}set(e=0,t=0,i=0,a=0){return this.expTerm=e,this.exponent=t,this.linearTerm=i,this.constantTerm=a,this}clone(){return new Sy(this.expTerm,this.exponent,this.linearTerm,this.constantTerm)}copy(e){return this.expTerm=e.expTerm,this.exponent=e.exponent,this.linearTerm=e.linearTerm,this.constantTerm=e.constantTerm,this}}const Lie=["channel","altitude","height","densityScale","shapeAmount","shapeDetailAmount","weatherExponent","shapeAlteringBias","coverageFilterWidth","shadow","densityProfile"];function Iie(n,e){if(e!=null)for(const t of Lie){const i=e[t];i!=null&&(n[t]instanceof Sy?n[t].copy(i):n[t]=i)}}const rM=class $P{constructor(e){this.channel="r",this.altitude=0,this.height=0,this.densityScale=.2,this.shapeAmount=1,this.shapeDetailAmount=1,this.weatherExponent=1,this.shapeAlteringBias=.35,this.coverageFilterWidth=.6,this.densityProfile=new Sy(0,0,.75,.25),this.shadow=!1,this.set(e)}set(e){return Iie(this,e),this}clone(){return new $P(this)}copy(e){return this.channel=e.channel,this.altitude=e.altitude,this.height=e.height,this.densityScale=e.densityScale,this.shapeAmount=e.shapeAmount,this.shapeDetailAmount=e.shapeDetailAmount,this.weatherExponent=e.weatherExponent,this.shapeAlteringBias=e.shapeAlteringBias,this.coverageFilterWidth=e.coverageFilterWidth,this.densityProfile.copy(e.densityProfile),this.shadow=e.shadow,this}};rM.DEFAULT=new rM;let Es=rM;const bf=Array.from({length:8},()=>({value:0,flag:0})),nm=Array.from({length:3},()=>({min:0,max:0}));function Uie(n,e){return n.value!==e.value?n.value-e.value:n.flag-e.flag}const sM=class e9 extends Array{constructor(e){super(new Es(e==null?void 0:e[0]),new Es(e==null?void 0:e[1]),new Es(e==null?void 0:e[2]),new Es(e==null?void 0:e[3]))}set(e){return this[0].set(e==null?void 0:e[0]),this[1].set(e==null?void 0:e[1]),this[2].set(e==null?void 0:e[2]),this[3].set(e==null?void 0:e[3]),this}reset(){return this[0].copy(Es.DEFAULT),this[1].copy(Es.DEFAULT),this[2].copy(Es.DEFAULT),this[3].copy(Es.DEFAULT),this}clone(){return new e9(this)}copy(e){return this[0].copy(e[0]),this[1].copy(e[1]),this[2].copy(e[2]),this[3].copy(e[3]),this}get localWeatherChannels(){return this[0].channel+this[1].channel+this[2].channel+this[3].channel}packValues(e,t){return t.set(this[0][e],this[1][e],this[2][e],this[3][e])}packSums(e,t,i){return i.set(this[0][e]+this[0][t],this[1][e]+this[1][t],this[2][e]+this[2][t],this[3][e]+this[3][t])}packDensityProfiles(e,t){return t.set(this[0].densityProfile[e],this[1].densityProfile[e],this[2].densityProfile[e],this[3].densityProfile[e])}packIntervalHeights(e,t){for(let s=0;s<4;++s){const o=this[s];let c=bf[s];c.value=o.altitude,c.flag=0,c=bf[s+4],c.value=o.altitude+o.height,c.flag=1}bf.sort(Uie);let i=0,a=0;for(let s=0;s0){const h=nm[i++];h.min=bf[s-1].value,h.max=o}a+=c===0?1:-1}for(;i<3;++i){const s=nm[i];s.min=0,s.max=0}let r=nm[0];e.x=r.min,t.x=r.max,r=nm[1],e.y=r.min,t.y=r.max,r=nm[2],e.z=r.min,t.z=r.max}};sM.DEFAULT=new sM([{channel:"r",altitude:750,height:650,densityScale:.2,shapeAmount:1,shapeDetailAmount:1,weatherExponent:1,shapeAlteringBias:.35,coverageFilterWidth:.6,shadow:!0},{channel:"g",altitude:1e3,height:1200,densityScale:.2,shapeAmount:1,shapeDetailAmount:1,weatherExponent:1,shapeAlteringBias:.35,coverageFilterWidth:.6,shadow:!0},{channel:"b",altitude:7500,height:500,densityScale:.003,shapeAmount:.4,shapeDetailAmount:0,weatherExponent:1,shapeAlteringBias:.35,coverageFilterWidth:.5},{channel:"a"}]);let o1=sM;var Pie="Invariant failed";function ec(n,e){if(!n)throw new Error(Pie)}class x0{constructor(e,t){this.near=[new L,new L,new L,new L],this.far=[new L,new L,new L,new L],e!=null&&t!=null&&this.setFromCamera(e,t)}clone(){return new x0().copy(this)}copy(e){for(let t=0;t<4;++t)this.near[t].copy(e.near[t]),this.far[t].copy(e.far[t]);return this}setFromCamera(e,t){const i=e.isOrthographicCamera===!0,a=e.projectionMatrixInverse;this.near[0].set(1,1,-1),this.near[1].set(1,-1,-1),this.near[2].set(-1,-1,-1),this.near[3].set(-1,1,-1);for(let r=0;r<4;++r)this.near[r].applyMatrix4(a);this.far[0].set(1,1,1),this.far[1].set(1,-1,1),this.far[2].set(-1,-1,1),this.far[3].set(-1,1,1);for(let r=0;r<4;++r){const s=this.far[r];s.applyMatrix4(a);const o=Math.abs(s.z);i?s.z*=Math.min(t/o,1):s.multiplyScalar(Math.min(t/o,1))}return this}split(e,t=[]){for(let i=0;i{for(let r=0;r{for(let r=0;r{for(let r=0;r{const i=new de;for(let a=0;a<16;++a)if(HO[a]===t){i.set((a%4+.5)/4,(Math.floor(a/4)+.5)/4);break}return[...n,i]},[]),Wie={resolutionScale:1,lightShafts:!0,shapeDetail:!0,turbulence:!0,haze:!0,clouds:{multiScatteringOctaves:8,accurateSunSkyLight:!0,accuratePhaseFunction:!1,maxIterationCount:500,minStepSize:50,maxStepSize:1e3,maxRayDistance:2e5,perspectiveStepScale:1.01,minDensity:1e-5,minExtinction:1e-5,minTransmittance:.01,maxIterationCountToGround:3,maxIterationCountToSun:2,minSecondaryStepSize:100,secondaryStepScale:2,maxShadowLengthIterationCount:500,minShadowLengthStepSize:50,maxShadowLengthRayDistance:2e5},shadow:{cascadeCount:3,mapSize:new de(512,512),maxIterationCount:50,minStepSize:100,maxStepSize:1e3,minDensity:1e-5,minExtinction:1e-5,minTransmittance:1e-4}},It=Wie,Xie={low:{...It,lightShafts:!1,shapeDetail:!1,turbulence:!1,clouds:{...It.clouds,accurateSunSkyLight:!1,maxIterationCount:200,minStepSize:100,maxRayDistance:1e5,minDensity:1e-4,minExtinction:1e-4,minTransmittance:.1,maxIterationCountToGround:0,maxIterationCountToSun:1},shadow:{...It.shadow,maxIterationCount:25,minDensity:1e-4,minExtinction:1e-4,minTransmittance:.01,cascadeCount:2,mapSize:new de(256,256)}},medium:{...It,lightShafts:!1,turbulence:!1,clouds:{...It.clouds,minDensity:1e-4,minExtinction:1e-4,accurateSunSkyLight:!1,maxIterationCountToSun:2,maxIterationCountToGround:1},shadow:{...It.shadow,minDensity:1e-4,minExtinction:1e-4,mapSize:new de(256,256)}},high:It,ultra:{...It,clouds:{...It.clouds,minStepSize:10},shadow:{...It.shadow,mapSize:new de(1024,1024)}}},Yie=`precision highp float; -precision highp sampler3D; -precision highp sampler2DArray; - -#include -#include - -#include "core/depth" -#include "core/math" -#include "core/turbo" -#include "core/generators" -#include "core/raySphereIntersection" -#include "core/cascadedShadowMaps" -#include "core/interleavedGradientNoise" -#include "core/vogelDisk" - -#include "atmosphere/bruneton/definitions" - -uniform AtmosphereParameters ATMOSPHERE; -uniform vec3 SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; -uniform vec3 SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; - -uniform sampler2D transmittance_texture; -uniform sampler3D scattering_texture; -uniform sampler2D irradiance_texture; -uniform sampler3D single_mie_scattering_texture; -uniform sampler3D higher_order_scattering_texture; - -#include "atmosphere/bruneton/common" -#include "atmosphere/bruneton/runtime" - -#include "types" -#include "parameters" -#include "clouds" - -#if !defined(RECIPROCAL_PI4) -#define RECIPROCAL_PI4 0.07957747154594767 -#endif // !defined(RECIPROCAL_PI4) - -uniform sampler2D depthBuffer; -uniform mat4 viewMatrix; -uniform mat4 reprojectionMatrix; -uniform mat4 viewReprojectionMatrix; -uniform float cameraNear; -uniform float cameraFar; -uniform float cameraHeight; -uniform vec2 temporalJitter; -uniform vec2 targetUvScale; -uniform float mipLevelScale; - -// Scattering -const vec2 scatterAnisotropy = vec2(SCATTER_ANISOTROPY_1, SCATTER_ANISOTROPY_2); -const float scatterAnisotropyMix = SCATTER_ANISOTROPY_MIX; -uniform float skyLightScale; -uniform float groundBounceScale; -uniform float powderScale; -uniform float powderExponent; - -// Primary raymarch -uniform int maxIterationCount; -uniform float minStepSize; -uniform float maxStepSize; -uniform float maxRayDistance; -uniform float perspectiveStepScale; - -// Secondary raymarch -uniform int maxIterationCountToSun; -uniform int maxIterationCountToGround; -uniform float minSecondaryStepSize; -uniform float secondaryStepScale; - -// Beer shadow map -uniform sampler2DArray shadowBuffer; -uniform vec2 shadowTexelSize; -uniform vec2 shadowIntervals[SHADOW_CASCADE_COUNT]; -uniform mat4 shadowMatrices[SHADOW_CASCADE_COUNT]; -uniform float shadowFar; -uniform float maxShadowFilterRadius; - -// Shadow length -#ifdef SHADOW_LENGTH -uniform int maxShadowLengthIterationCount; -uniform float minShadowLengthStepSize; -uniform float maxShadowLengthRayDistance; -#endif // SHADOW_LENGTH - -in vec2 vUv; -in vec3 vCameraPosition; -in vec3 vCameraDirection; // Direction to the center of screen -in vec3 vRayDirection; // Direction to the texel -in vec3 vViewPosition; -in GroundIrradiance vGroundIrradiance; -in CloudsIrradiance vCloudsIrradiance; - -layout(location = 0) out vec4 outputColor; -layout(location = 1) out vec3 outputDepthVelocity; -#ifdef SHADOW_LENGTH -layout(location = 2) out float outputShadowLength; -#endif // SHADOW_LENGTH - -float readDepth(const vec2 uv) { - #if DEPTH_PACKING == 3201 - return unpackRGBAToDepth(texture(depthBuffer, uv)); - #else // DEPTH_PACKING == 3201 - return texture(depthBuffer, uv).r; - #endif // DEPTH_PACKING == 3201 -} - -float getViewZ(const float depth) { - #ifdef PERSPECTIVE_CAMERA - return perspectiveDepthToViewZ(depth, cameraNear, cameraFar); - #else // PERSPECTIVE_CAMERA - return orthographicDepthToViewZ(depth, cameraNear, cameraFar); - #endif // PERSPECTIVE_CAMERA -} - -vec3 ecefToWorld(const vec3 positionECEF) { - return (ecefToWorldMatrix * vec4(positionECEF - altitudeCorrection, 1.0)).xyz; -} - -vec2 getShadowUv(const vec3 worldPosition, const int cascadeIndex) { - vec4 clip = shadowMatrices[cascadeIndex] * vec4(worldPosition, 1.0); - clip /= clip.w; - return clip.xy * 0.5 + 0.5; -} - -float getDistanceToShadowTop(const vec3 rayPosition) { - // Distance to the top of the shadows along the sun direction, which matches - // the ray origin of BSM. - return raySphereSecondIntersection( - rayPosition, - sunDirection, - vec3(0.0), - bottomRadius + shadowTopHeight - ); -} - -#ifdef DEBUG_SHOW_CASCADES - -const vec3 cascadeColors[4] = vec3[4]( - vec3(1.0, 0.0, 0.0), - vec3(0.0, 1.0, 0.0), - vec3(0.0, 0.0, 1.0), - vec3(1.0, 1.0, 0.0) -); - -vec3 getCascadeColor(const vec3 rayPosition) { - vec3 worldPosition = ecefToWorld(rayPosition); - int cascadeIndex = getCascadeIndex( - viewMatrix, - worldPosition, - shadowIntervals, - cameraNear, - shadowFar - ); - vec2 uv = getShadowUv(worldPosition, cascadeIndex); - if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { - return vec3(1.0); - } - return cascadeColors[cascadeIndex]; -} - -vec3 getFadedCascadeColor(const vec3 rayPosition, const float jitter) { - vec3 worldPosition = ecefToWorld(rayPosition); - int cascadeIndex = getFadedCascadeIndex( - viewMatrix, - worldPosition, - shadowIntervals, - cameraNear, - shadowFar, - jitter - ); - return cascadeIndex >= 0 - ? cascadeColors[cascadeIndex] - : vec3(1.0); -} - -#endif // DEBUG_SHOW_CASCADES - -float readShadowOpticalDepth( - const vec2 uv, - const float distanceToTop, - const float distanceOffset, - const int cascadeIndex -) { - // r: frontDepth, g: meanExtinction, b: maxOpticalDepth, a: maxOpticalDepthTail - // Also see the discussion here: https://x.com/shotamatsuda/status/1885322308908442106 - vec4 shadow = texture(shadowBuffer, vec3(uv, float(cascadeIndex))); - float distanceToFront = max(0.0, distanceToTop - distanceOffset - shadow.r); - return min(shadow.b + shadow.a, shadow.g * distanceToFront); -} - -float sampleShadowOpticalDepthPCF( - const vec3 worldPosition, - const float distanceToTop, - const float distanceOffset, - const float radius, - const int cascadeIndex -) { - vec2 uv = getShadowUv(worldPosition, cascadeIndex); - if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { - return 0.0; - } - if (radius < 0.1) { - return readShadowOpticalDepth(uv, distanceToTop, distanceOffset, cascadeIndex); - } - float sum = 0.0; - vec2 offset; - #pragma unroll_loop_start - for (int i = 0; i < 16; ++i) { - #if UNROLLED_LOOP_INDEX < SHADOW_SAMPLE_COUNT - offset = vogelDisk( - UNROLLED_LOOP_INDEX, - SHADOW_SAMPLE_COUNT, - interleavedGradientNoise(gl_FragCoord.xy + temporalJitter * resolution) * PI2 - ); - sum += readShadowOpticalDepth( - uv + offset * radius * shadowTexelSize, - distanceToTop, - distanceOffset, - cascadeIndex - ); - #endif // UNROLLED_LOOP_INDEX < SHADOW_SAMPLE_COUNT - } - #pragma unroll_loop_end - return sum / float(SHADOW_SAMPLE_COUNT); -} - -float sampleShadowOpticalDepth( - const vec3 rayPosition, - const float distanceOffset, - const float radius, - const float jitter -) { - float distanceToTop = getDistanceToShadowTop(rayPosition); - if (distanceToTop <= 0.0) { - return 0.0; - } - vec3 worldPosition = ecefToWorld(rayPosition); - int cascadeIndex = getFadedCascadeIndex( - viewMatrix, - worldPosition, - shadowIntervals, - cameraNear, - shadowFar, - jitter - ); - return cascadeIndex >= 0 - ? sampleShadowOpticalDepthPCF( - worldPosition, - distanceToTop, - distanceOffset, - radius, - cascadeIndex - ) - : 0.0; -} - -#ifdef DEBUG_SHOW_SHADOW_MAP -vec4 getCascadedShadowMaps(vec2 uv) { - vec4 coord = vec4(vUv, vUv - 0.5) * 2.0; - vec4 shadow = vec4(0.0); - if (uv.y > 0.5) { - if (uv.x < 0.5) { - shadow = texture(shadowBuffer, vec3(coord.xw, 0.0)); - } else { - #if SHADOW_CASCADE_COUNT > 1 - shadow = texture(shadowBuffer, vec3(coord.zw, 1.0)); - #endif // SHADOW_CASCADE_COUNT > 1 - } - } else { - if (uv.x < 0.5) { - #if SHADOW_CASCADE_COUNT > 2 - shadow = texture(shadowBuffer, vec3(coord.xy, 2.0)); - #endif // SHADOW_CASCADE_COUNT > 2 - } else { - #if SHADOW_CASCADE_COUNT > 3 - shadow = texture(shadowBuffer, vec3(coord.zy, 3.0)); - #endif // SHADOW_CASCADE_COUNT > 3 - } - } - - #if !defined(DEBUG_SHOW_SHADOW_MAP_TYPE) - #define DEBUG_SHOW_SHADOW_MAP_TYPE 0 - #endif // !defined(DEBUG_SHOW_SHADOW_MAP_TYPE - - const float frontDepthScale = 1e-5; - const float meanExtinctionScale = 10.0; - const float maxOpticalDepthScale = 0.01; - vec3 color; - #if DEBUG_SHOW_SHADOW_MAP_TYPE == 1 - color = vec3(shadow.r * frontDepthScale); - #elif DEBUG_SHOW_SHADOW_MAP_TYPE == 2 - color = vec3(shadow.g * meanExtinctionScale); - #elif DEBUG_SHOW_SHADOW_MAP_TYPE == 3 - color = vec3((shadow.b + shadow.a) * maxOpticalDepthScale); - #else // DEBUG_SHOW_SHADOW_MAP_TYPE - color = - (shadow.rgb + vec3(0.0, 0.0, shadow.a)) * - vec3(frontDepthScale, meanExtinctionScale, maxOpticalDepthScale); - #endif // DEBUG_SHOW_SHADOW_MAP_TYPE - return vec4(color, 1.0); -} -#endif // DEBUG_SHOW_SHADOW_MAP - -vec2 henyeyGreenstein(const vec2 g, const float cosTheta) { - vec2 g2 = g * g; - // prettier-ignore - return RECIPROCAL_PI4 * - ((1.0 - g2) / max(vec2(1e-7), pow(1.0 + g2 - 2.0 * g * cosTheta, vec2(1.5)))); -} - -#ifdef ACCURATE_PHASE_FUNCTION - -float draine(float u, float g, float a) { - float g2 = g * g; - // prettier-ignore - return (1.0 - g2) * - (1.0 + a * u * u) / - (4.0 * (1.0 + a * (1.0 + 2.0 * g2) / 3.0) * PI * pow(1.0 + g2 - 2.0 * g * u, 1.5)); -} - -// Numerically-fitted large particles (d=10) phase function It won't be -// plausible without a more precise multiple scattering. -// Reference: https://research.nvidia.com/labs/rtr/approximate-mie/ -float phaseFunction(const float cosTheta, const float attenuation) { - const float gHG = 0.988176691700256; // exp(-0.0990567/(d-1.67154)) - const float gD = 0.5556712547839497; // exp(-2.20679/(d+3.91029) - 0.428934) - const float alpha = 21.995520856274638; // exp(3.62489 - 8.29288/(d+5.52825)) - const float weight = 0.4819554318404214; // exp(-0.599085/(d-0.641583)-0.665888) - return mix( - henyeyGreenstein(vec2(gHG) * attenuation, cosTheta).x, - draine(cosTheta, gD * attenuation, alpha), - weight - ); -} - -#else // ACCURATE_PHASE_FUNCTION - -float phaseFunction(const float cosTheta, const float attenuation) { - const vec2 g = scatterAnisotropy; - const vec2 weights = vec2(1.0 - scatterAnisotropyMix, scatterAnisotropyMix); - // A similar approximation is described in the Frostbite's paper, where phase - // angle is attenuated instead of anisotropy. - return dot(henyeyGreenstein(g * attenuation, cosTheta), weights); -} - -#endif // ACCURATE_PHASE_FUNCTION - -float phaseFunction(const float cosTheta) { - return phaseFunction(cosTheta, 1.0); -} - -float marchOpticalDepth( - const vec3 rayOrigin, - const vec3 rayDirection, - const int maxIterationCount, - const float mipLevel, - const float jitter, - out float rayDistance -) { - int iterationCount = int( - max(0.0, remap(mipLevel, 0.0, 1.0, float(maxIterationCount + 1), 1.0) - jitter) - ); - if (iterationCount == 0) { - // Fudge factor to approximate the mean optical depth. - // TODO: Remove it. - return 0.5; - } - float stepSize = minSecondaryStepSize / float(iterationCount); - float nextDistance = stepSize * jitter; - float opticalDepth = 0.0; - for (int i = 0; i < iterationCount; ++i) { - rayDistance = nextDistance; - vec3 position = rayDistance * rayDirection + rayOrigin; - vec2 uv = getGlobeUv(position); - float height = length(position) - bottomRadius; - WeatherSample weather = sampleWeather(uv, height, mipLevel); - MediaSample media = sampleMedia(weather, position, uv, mipLevel, jitter); - opticalDepth += media.extinction * stepSize; - nextDistance += stepSize; - stepSize *= secondaryStepScale; - } - return opticalDepth; -} - -float marchOpticalDepth( - const vec3 rayOrigin, - const vec3 rayDirection, - const int maxIterationCount, - const float mipLevel, - const float jitter -) { - float rayDistance; - return marchOpticalDepth( - rayOrigin, - rayDirection, - maxIterationCount, - mipLevel, - jitter, - rayDistance - ); -} - -float approximateMultipleScattering(const float opticalDepth, const float cosTheta) { - // Multiple scattering approximation - // See: https://fpsunflower.github.io/ckulla/data/oz_volumes.pdf - // a: attenuation, b: contribution, c: phase attenuation - vec3 coeffs = vec3(1.0); // [a, b, c] - const vec3 attenuation = vec3(0.5, 0.5, 0.5); // Should satisfy a <= b - float scattering = 0.0; - float beerLambert; - #pragma unroll_loop_start - for (int i = 0; i < 12; ++i) { - #if UNROLLED_LOOP_INDEX < MULTI_SCATTERING_OCTAVES - beerLambert = exp(-opticalDepth * coeffs.y); - scattering += coeffs.x * beerLambert * phaseFunction(cosTheta, coeffs.z); - coeffs *= attenuation; - #endif // UNROLLED_LOOP_INDEX < MULTI_SCATTERING_OCTAVES - } - #pragma unroll_loop_end - return scattering; -} - -// TODO: Construct spherical harmonics of degree 2 using 2 sample points -// positioned near the horizon occlusion points on the sun direction plane. -vec3 getGroundSunSkyIrradiance( - const vec3 position, - const vec3 surfaceNormal, - const float height, - out vec3 skyIrradiance -) { - #ifdef ACCURATE_SUN_SKY_LIGHT - return GetSunAndSkyIrradiance( - (position - surfaceNormal * height) * METER_TO_LENGTH_UNIT, - surfaceNormal, - sunDirection, - skyIrradiance - ); - #else // ACCURATE_SUN_SKY_LIGHT - skyIrradiance = vGroundIrradiance.sky; - return vGroundIrradiance.sun; - #endif // ACCURATE_SUN_SKY_LIGHT -} - -vec3 getCloudsSunSkyIrradiance(const vec3 position, const float height, out vec3 skyIrradiance) { - #ifdef ACCURATE_SUN_SKY_LIGHT - return GetSunAndSkyScalarIrradiance(position * METER_TO_LENGTH_UNIT, sunDirection, skyIrradiance); - #else // ACCURATE_SUN_SKY_LIGHT - float alpha = remapClamped(height, minHeight, maxHeight); - skyIrradiance = mix(vCloudsIrradiance.minSky, vCloudsIrradiance.maxSky, alpha); - return mix(vCloudsIrradiance.minSun, vCloudsIrradiance.maxSun, alpha); - #endif // ACCURATE_SUN_SKY_LIGHT -} - -#ifdef GROUND_BOUNCE -vec3 approximateRadianceFromGround( - const vec3 position, - const vec3 surfaceNormal, - const float height, - const float mipLevel, - const float jitter -) { - float opticalDepthToGround = marchOpticalDepth( - position, - -surfaceNormal, - maxIterationCountToGround, - mipLevel, - jitter - ); - vec3 skyIrradiance; - vec3 sunIrradiance = getGroundSunSkyIrradiance(position, surfaceNormal, height, skyIrradiance); - const float groundAlbedo = 0.3; - vec3 groundIrradiance = skyIrradiance + (1.0 - coverage) * sunIrradiance; - vec3 bouncedRadiance = groundAlbedo * RECIPROCAL_PI * groundIrradiance; - return bouncedRadiance * exp(-opticalDepthToGround); -} -#endif // GROUND_BOUNCE - -vec4 marchClouds( - const vec3 rayOrigin, - const vec3 rayDirection, - const vec2 rayNearFar, - const float cosTheta, - const float jitter, - const float rayStartTexelsPerPixel, - out float frontDepth, - out ivec3 sampleCount -) { - vec3 radianceIntegral = vec3(0.0); - float transmittanceIntegral = 1.0; - float weightedDistanceSum = 0.0; - float transmittanceSum = 0.0; - - float maxRayDistance = rayNearFar.y - rayNearFar.x; - float stepSize = minStepSize + (perspectiveStepScale - 1.0) * rayNearFar.x; - // I don't understand why spatial aliasing remains unless doubling the jitter. - float rayDistance = stepSize * jitter * 2.0; - - for (int i = 0; i < maxIterationCount; ++i) { - if (rayDistance > maxRayDistance) { - break; // Termination - } - - vec3 position = rayDistance * rayDirection + rayOrigin; - float height = length(position) - bottomRadius; - float mipLevel = log2(max(1.0, rayStartTexelsPerPixel + rayDistance * 1e-5)); - - #if !defined(DEBUG_MARCH_INTERVALS) - if (insideLayerIntervals(height)) { - stepSize *= perspectiveStepScale; - rayDistance += mix(stepSize, maxStepSize, min(1.0, mipLevel)); - continue; - } - #endif // !defined(DEBUG_MARCH_INTERVALS) - - // Sample rough weather. - vec2 uv = getGlobeUv(position); - WeatherSample weather = sampleWeather(uv, height, mipLevel); - - #ifdef DEBUG_SHOW_SAMPLE_COUNT - ++sampleCount.x; - #endif // DEBUG_SHOW_SAMPLE_COUNT - - if (!any(greaterThan(weather.density, vec4(minDensity)))) { - // Step longer in empty space. - // TODO: This produces banding artifacts. - // Possible improvement: Binary search refinement - stepSize *= perspectiveStepScale; - rayDistance += mix(stepSize, maxStepSize, min(1.0, mipLevel)); - continue; - } - - // Sample detailed participating media. - MediaSample media = sampleMedia(weather, position, uv, mipLevel, jitter, sampleCount); - - if (media.extinction > minExtinction) { - vec3 skyIrradiance; - vec3 sunIrradiance = getCloudsSunSkyIrradiance(position, height, skyIrradiance); - vec3 surfaceNormal = normalize(position); - - // March optical depth to the sun for finer details, which BSM lacks. - float sunRayDistance = 0.0; - float opticalDepth = marchOpticalDepth( - position, - sunDirection, - maxIterationCountToSun, - mipLevel, - jitter, - sunRayDistance - ); - - if (height < shadowTopHeight) { - // Obtain the optical depth from BSM at the ray position. - opticalDepth += sampleShadowOpticalDepth( - position, - // Take account of only positions further than the marched ray - // distance. - sunRayDistance, - // Apply PCF only when the sun is close to the horizon. - maxShadowFilterRadius * remapClamped(dot(sunDirection, surfaceNormal), 0.1, 0.0), - jitter - ); - } - - vec3 radiance = sunIrradiance * approximateMultipleScattering(opticalDepth, cosTheta); - - #ifdef GROUND_BOUNCE - // Fudge factor for the irradiance from ground. - if (height < shadowTopHeight && mipLevel < 0.5) { - vec3 groundRadiance = approximateRadianceFromGround( - position, - surfaceNormal, - height, - mipLevel, - jitter - ); - radiance += groundRadiance * RECIPROCAL_PI4 * groundBounceScale; - } - #endif // GROUND_BOUNCE - - // Crude approximation of sky gradient. Better than none in the shadows. - float skyGradient = dot(weather.heightFraction * 0.5 + 0.5, media.weight); - radiance += skyIrradiance * RECIPROCAL_PI4 * skyGradient * skyLightScale; - - // Finally multiply by scattering. - radiance *= media.scattering; - - #ifdef POWDER - radiance *= 1.0 - powderScale * exp(-media.extinction * powderExponent); - #endif // POWDER - - #ifdef DEBUG_SHOW_CASCADES - if (height < shadowTopHeight) { - radiance = 1e-3 * getFadedCascadeColor(position, jitter); - } - #endif // DEBUG_SHOW_CASCADES - - // Energy-conserving analytical integration of scattered light - // See 5.6.3 in https://media.contentapi.ea.com/content/dam/eacom/frostbite/files/s2016-pbs-frostbite-sky-clouds-new.pdf - float transmittance = exp(-media.extinction * stepSize); - float clampedExtinction = max(media.extinction, 1e-7); - vec3 scatteringIntegral = (radiance - radiance * transmittance) / clampedExtinction; - radianceIntegral += transmittanceIntegral * scatteringIntegral; - transmittanceIntegral *= transmittance; - - // Aerial perspective affecting clouds - // See 5.9.1 in https://media.contentapi.ea.com/content/dam/eacom/frostbite/files/s2016-pbs-frostbite-sky-clouds-new.pdf - weightedDistanceSum += rayDistance * transmittanceIntegral; - transmittanceSum += transmittanceIntegral; - } - - if (transmittanceIntegral <= minTransmittance) { - break; // Early termination - } - - // Take a shorter step because we've already hit the clouds. - stepSize *= perspectiveStepScale; - rayDistance += stepSize; - } - - // The final product of 5.9.1 and we'll evaluate this in aerial perspective. - frontDepth = transmittanceSum > 0.0 ? weightedDistanceSum / transmittanceSum : -1.0; - - return vec4(radianceIntegral, remapClamped(transmittanceIntegral, 1.0, minTransmittance)); -} - -#ifdef SHADOW_LENGTH - -float marchShadowLength( - const vec3 rayOrigin, - const vec3 rayDirection, - const vec2 rayNearFar, - const float jitter -) { - float shadowLength = 0.0; - float maxRayDistance = rayNearFar.y - rayNearFar.x; - float stepSize = minShadowLengthStepSize; - float rayDistance = stepSize * jitter; - const float attenuationFactor = 1.0 - 5e-4; - float attenuation = 1.0; - - // TODO: This march is closed, and sample resolution can be much lower. - // Refining the termination by binary search will make it much more efficient. - for (int i = 0; i < maxShadowLengthIterationCount; ++i) { - if (rayDistance > maxRayDistance) { - break; // Termination - } - vec3 position = rayDistance * rayDirection + rayOrigin; - float opticalDepth = sampleShadowOpticalDepth(position, 0.0, 0.0, jitter); - shadowLength += (1.0 - exp(-opticalDepth)) * stepSize * attenuation; - stepSize *= perspectiveStepScale; - rayDistance += stepSize; - } - return shadowLength; -} - -#endif // SHADOW_LENGTH - -#ifdef HAZE - -vec4 approximateHaze( - const vec3 rayOrigin, - const vec3 rayDirection, - const float maxRayDistance, - const float cosTheta, - const float shadowLength -) { - float modulation = remapClamped(coverage, 0.2, 0.4); - if (cameraHeight * modulation < 0.0) { - return vec4(0.0); - } - float density = modulation * hazeDensityScale * exp(-cameraHeight * hazeExponent); - if (density < 1e-7) { - return vec4(0.0); // Prevent artifact in views from space - } - - // Blend two normals by the difference in angle so that normal near the - // ground becomes that of the origin, and in the sky that of the horizon. - vec3 normalAtOrigin = normalize(rayOrigin); - vec3 normalAtHorizon = (rayOrigin - dot(rayOrigin, rayDirection) * rayDirection) / bottomRadius; - float alpha = remapClamped(dot(normalAtOrigin, normalAtHorizon), 0.9, 1.0); - vec3 normal = mix(normalAtOrigin, normalAtHorizon, alpha); - - // Analytical optical depth where density exponentially decreases with height. - // Based on: https://iquilezles.org/articles/fog/ - float angle = max(dot(normal, rayDirection), 1e-5); - float exponent = angle * hazeExponent; - float linearTerm = density / hazeExponent / angle; - - // Derive the optical depths separately for with and without shadow length. - float expTerm = 1.0 - exp(-maxRayDistance * exponent); - float shadowExpTerm = 1.0 - exp(-min(maxRayDistance, shadowLength) * exponent); - float opticalDepth = expTerm * linearTerm; - float shadowOpticalDepth = max((expTerm - shadowExpTerm) * linearTerm, 0.0); - float transmittance = saturate(1.0 - exp(-opticalDepth)); - float shadowTransmittance = saturate(1.0 - exp(-shadowOpticalDepth)); - - vec3 skyIrradiance = vGroundIrradiance.sky; - vec3 sunIrradiance = vGroundIrradiance.sun; - vec3 inscatter = sunIrradiance * phaseFunction(cosTheta) * shadowTransmittance; - inscatter += skyIrradiance * RECIPROCAL_PI4 * skyLightScale * transmittance; - inscatter *= hazeScatteringCoefficient / (hazeAbsorptionCoefficient + hazeScatteringCoefficient); - return vec4(inscatter, transmittance); -} - -#endif // HAZE - -void applyAerialPerspective( - const vec3 cameraPosition, - const vec3 frontPosition, - const float shadowLength, - inout vec4 color -) { - vec3 transmittance; - vec3 inscatter = GetSkyRadianceToPoint( - cameraPosition * METER_TO_LENGTH_UNIT, - frontPosition * METER_TO_LENGTH_UNIT, - shadowLength * METER_TO_LENGTH_UNIT, - sunDirection, - transmittance - ); - color.rgb = color.rgb * transmittance + inscatter * color.a; -} - -bool rayIntersectsGround(const vec3 cameraPosition, const vec3 rayDirection) { - float r = length(cameraPosition); - float mu = dot(cameraPosition, rayDirection) / r; - return mu < 0.0 && r * r * (mu * mu - 1.0) + bottomRadius * bottomRadius >= 0.0; -} - -struct IntersectionResult { - bool ground; - vec4 first; - vec4 second; -}; - -IntersectionResult getIntersections(const vec3 cameraPosition, const vec3 rayDirection) { - IntersectionResult intersections; - intersections.ground = rayIntersectsGround(cameraPosition, rayDirection); - raySphereIntersections( - cameraPosition, - rayDirection, - bottomRadius + vec4(0.0, minHeight, maxHeight, shadowTopHeight), - intersections.first, - intersections.second - ); - return intersections; -} - -vec2 getRayNearFar(const IntersectionResult intersections) { - vec2 nearFar; - if (cameraHeight < minHeight) { - // View below the clouds - if (intersections.ground) { - nearFar = vec2(-1.0); // No clouds to the ground - } else { - nearFar = vec2(intersections.second.y, intersections.second.z); - nearFar.y = min(nearFar.y, maxRayDistance); - } - } else if (cameraHeight < maxHeight) { - // View inside the total cloud layer - if (intersections.ground) { - nearFar = vec2(cameraNear, intersections.first.y); - } else { - nearFar = vec2(cameraNear, intersections.second.z); - } - } else { - // View above the clouds - nearFar = vec2(intersections.first.z, intersections.second.z); - if (intersections.ground) { - // Clamp the ray at the min height. - nearFar.y = intersections.first.y; - } - } - return nearFar; -} - -#ifdef SHADOW_LENGTH -vec2 getShadowRayNearFar(const IntersectionResult intersections) { - vec2 nearFar; - if (cameraHeight < shadowTopHeight) { - if (intersections.ground) { - nearFar = vec2(cameraNear, intersections.first.x); - } else { - nearFar = vec2(cameraNear, intersections.second.w); - } - } else { - nearFar = vec2(intersections.first.w, intersections.second.w); - if (intersections.ground) { - // Clamp the ray at the ground. - nearFar.y = intersections.first.x; - } - } - nearFar.y = min(nearFar.y, maxShadowLengthRayDistance); - return nearFar; -} -#endif // SHADOW_LENGTH - -#ifdef HAZE -vec2 getHazeRayNearFar(const IntersectionResult intersections) { - vec2 nearFar; - if (cameraHeight < maxHeight) { - if (intersections.ground) { - nearFar = vec2(cameraNear, intersections.first.x); - } else { - nearFar = vec2(cameraNear, intersections.second.z); - } - } else { - nearFar = vec2(cameraNear, intersections.second.z); - if (intersections.ground) { - // Clamp the ray at the ground. - nearFar.y = intersections.first.x; - } - } - return nearFar; -} -#endif // HAZE - -float getRayDistanceToScene(const vec3 rayDirection, out float viewZ) { - float depth = readDepth(vUv * targetUvScale + temporalJitter); - if (depth < 1.0 - 1e-7) { - depth = reverseLogDepth(depth, cameraNear, cameraFar); - viewZ = getViewZ(depth); - return -viewZ / dot(rayDirection, vCameraDirection); - } - viewZ = 0.0; - return 0.0; -} - -void main() { - #ifdef DEBUG_SHOW_SHADOW_MAP - outputColor = getCascadedShadowMaps(vUv); - outputDepthVelocity = vec3(0.0); - #ifdef SHADOW_LENGTH - outputShadowLength = 0.0; - #endif // SHADOW_LENGTH - return; - #endif // DEBUG_SHOW_SHADOW_MAP - - vec3 cameraPosition = vCameraPosition + altitudeCorrection; - vec3 rayDirection = normalize(vRayDirection); - float cosTheta = dot(sunDirection, rayDirection); - - IntersectionResult intersections = getIntersections(cameraPosition, rayDirection); - vec2 rayNearFar = getRayNearFar(intersections); - #ifdef SHADOW_LENGTH - vec2 shadowRayNearFar = getShadowRayNearFar(intersections); - #endif // SHADOW_LENGTH - #ifdef HAZE - vec2 hazeRayNearFar = getHazeRayNearFar(intersections); - #endif // HAZE - - float sceneViewZ; - float rayDistanceToScene = getRayDistanceToScene(rayDirection, sceneViewZ); - if (rayDistanceToScene > 0.0) { - rayNearFar.y = min(rayNearFar.y, rayDistanceToScene); - #ifdef SHADOW_LENGTH - shadowRayNearFar.y = min(shadowRayNearFar.y, rayDistanceToScene); - #endif // SHADOW_LENGTH - #ifdef HAZE - hazeRayNearFar.y = min(hazeRayNearFar.y, rayDistanceToScene); - #endif // HAZE - } - - bool intersectsGround = any(lessThan(rayNearFar, vec2(0.0))); - bool intersectsScene = rayNearFar.y < rayNearFar.x; - - float stbn = getSTBN(); - - vec4 color = vec4(0.0); - float frontDepth = rayNearFar.y; - vec3 depthVelocity = vec3(0.0); - float shadowLength = 0.0; - bool hitClouds = false; - - if (!intersectsGround && !intersectsScene) { - vec3 rayOrigin = rayNearFar.x * rayDirection + cameraPosition; - - vec2 globeUv = getGlobeUv(rayOrigin); - #ifdef DEBUG_SHOW_UV - outputColor = vec4(vec3(checker(globeUv, localWeatherRepeat + localWeatherOffset)), 1.0); - outputDepthVelocity = vec3(0.0); - #ifdef SHADOW_LENGTH - outputShadowLength = 0.0; - #endif // SHADOW_LENGTH - return; - #endif // DEBUG_SHOW_UV - - float mipLevel = getMipLevel(globeUv * localWeatherRepeat) * mipLevelScale; - mipLevel = mix(0.0, mipLevel, min(1.0, 0.2 * cameraHeight / maxHeight)); - - float marchedFrontDepth; - ivec3 sampleCount = ivec3(0); - color = marchClouds( - rayOrigin, - rayDirection, - rayNearFar, - cosTheta, - stbn, - pow(2.0, mipLevel), - marchedFrontDepth, - sampleCount - ); - - #ifdef DEBUG_SHOW_SAMPLE_COUNT - outputColor = vec4(vec3(sampleCount) / vec3(500.0, 5.0, 5.0), 1.0); - outputDepthVelocity = vec3(0.0); - #ifdef SHADOW_LENGTH - outputShadowLength = 0.0; - #endif // SHADOW_LENGTH - return; - #endif // DEBUG_SHOW_SAMPLE_COUNT - - // Front depth will be -1.0 when no samples are accumulated. - hitClouds = marchedFrontDepth >= 0.0; - if (hitClouds) { - frontDepth = rayNearFar.x + marchedFrontDepth; - - #ifdef SHADOW_LENGTH - // Clamp the shadow length ray at the clouds. - shadowRayNearFar.y = mix( - shadowRayNearFar.y, - min(frontDepth, shadowRayNearFar.y), - color.a // Interpolate by the alpha for smoother edges. - ); - - // Shadow length must be computed before applying aerial perspective. - if (all(greaterThanEqual(shadowRayNearFar, vec2(0.0)))) { - shadowLength = marchShadowLength( - shadowRayNearFar.x * rayDirection + cameraPosition, - rayDirection, - shadowRayNearFar, - stbn - ); - } - #endif // SHADOW_LENGTH - - #ifdef HAZE - // Clamp the haze ray at the clouds. - hazeRayNearFar.y = mix( - hazeRayNearFar.y, - min(frontDepth, hazeRayNearFar.y), - color.a // Interpolate by the alpha for smoother edges. - ); - #endif // HAZE - - // Apply aerial perspective. - vec3 frontPosition = cameraPosition + frontDepth * rayDirection; - applyAerialPerspective(cameraPosition, frontPosition, shadowLength, color); - - // Velocity for temporal resolution. - vec3 frontPositionWorld = ecefToWorld(frontPosition); - vec4 prevClip = reprojectionMatrix * vec4(frontPositionWorld, 1.0); - prevClip /= prevClip.w; - vec2 prevUv = prevClip.xy * 0.5 + 0.5; - vec2 velocity = vUv - prevUv; - depthVelocity = vec3(frontDepth, velocity); - } - } - - if (!hitClouds) { - #ifdef SHADOW_LENGTH - if (all(greaterThanEqual(shadowRayNearFar, vec2(0.0)))) { - shadowLength = marchShadowLength( - shadowRayNearFar.x * rayDirection + cameraPosition, - rayDirection, - shadowRayNearFar, - stbn - ); - } - #endif // SHADOW_LENGTH - - // Velocity for temporal resolution. Here reproject in the view space for - // greatly reducing the precision errors. - frontDepth = sceneViewZ < 0.0 ? -sceneViewZ : cameraFar; - vec3 frontView = vViewPosition * frontDepth; - vec4 prevClip = viewReprojectionMatrix * vec4(frontView, 1.0); - prevClip /= prevClip.w; - vec2 prevUv = prevClip.xy * 0.5 + 0.5; - vec2 velocity = vUv - prevUv; - depthVelocity = vec3(frontDepth, velocity); - } - - #ifdef DEBUG_SHOW_FRONT_DEPTH - outputColor = vec4(turbo(frontDepth / maxRayDistance), 1.0); - outputDepthVelocity = vec3(0.0); - #ifdef SHADOW_LENGTH - outputShadowLength = 0.0; - #endif // SHADOW_LENGTH - return; - #endif // DEBUG_SHOW_FRONT_DEPTH - - #ifdef HAZE - vec4 haze = approximateHaze( - cameraNear * rayDirection + cameraPosition, - rayDirection, - hazeRayNearFar.y - hazeRayNearFar.x, - cosTheta, - shadowLength - ); - color.rgb = mix(color.rgb, haze.rgb, haze.a); - color.a = color.a * (1.0 - haze.a) + haze.a; - #endif // HAZE - - outputColor = color; - outputDepthVelocity = depthVelocity; - #ifdef SHADOW_LENGTH - outputShadowLength = shadowLength * METER_TO_LENGTH_UNIT; - #endif // SHADOW_LENGTH -} -`,n9=`float getSTBN() { - ivec3 size = textureSize(stbnTexture, 0); - vec3 scale = 1.0 / vec3(size); - return texture(stbnTexture, vec3(gl_FragCoord.xy, float(frame % size.z)) * scale).r; -} - -// Straightforward spherical mapping -vec2 getSphericalUv(const vec3 position) { - vec2 st = normalize(position.yx); - float phi = atan(st.x, st.y); - float theta = asin(normalize(position).z); - return vec2(phi * RECIPROCAL_PI2 + 0.5, theta * RECIPROCAL_PI + 0.5); -} - -vec2 getCubeSphereUv(const vec3 position) { - // Cube-sphere relaxation by: http://mathproofs.blogspot.com/2005/07/mapping-cube-to-sphere.html - // TODO: Tile and fix seams. - // Possible improvements: - // https://iquilezles.org/articles/texturerepetition/ - // https://gamedev.stackexchange.com/questions/184388/fragment-shader-map-dot-texture-repeatedly-over-the-sphere - // https://github.com/mmikk/hextile-demo - - vec3 n = normalize(position); - vec3 f = abs(n); - vec3 c = n / max(f.x, max(f.y, f.z)); - vec2 m; - if (all(greaterThan(f.yy, f.xz))) { - m = c.y > 0.0 ? vec2(-n.x, n.z) : n.xz; - } else if (all(greaterThan(f.xx, f.yz))) { - m = c.x > 0.0 ? n.yz : vec2(-n.y, n.z); - } else { - m = c.z > 0.0 ? n.xy : vec2(n.x, -n.y); - } - - vec2 m2 = m * m; - float q = dot(m2.xy, vec2(-2.0, 2.0)) - 3.0; - float q2 = q * q; - vec2 uv; - uv.x = sqrt(1.5 + m2.x - m2.y - 0.5 * sqrt(-24.0 * m2.x + q2)) * (m.x > 0.0 ? 1.0 : -1.0); - uv.y = sqrt(6.0 / (3.0 - uv.x * uv.x)) * m.y; - return uv * 0.5 + 0.5; -} - -vec2 getGlobeUv(const vec3 position) { - return getCubeSphereUv(position); -} - -float getMipLevel(const vec2 uv) { - const float mipLevelScale = 0.1; - vec2 coord = uv * resolution; - vec2 ddx = dFdx(coord); - vec2 ddy = dFdy(coord); - float deltaMaxSqr = max(dot(ddx, ddx), dot(ddy, ddy)) * mipLevelScale; - return max(0.0, 0.5 * log2(max(1.0, deltaMaxSqr))); -} - -bool insideLayerIntervals(const float height) { - bvec3 gt = greaterThan(vec3(height), minIntervalHeights); - bvec3 lt = lessThan(vec3(height), maxIntervalHeights); - return any(bvec3(gt.x && lt.x, gt.y && lt.y, gt.z && lt.z)); -} - -struct WeatherSample { - vec4 heightFraction; // Normalized height of each layer - vec4 density; -}; - -vec4 shapeAlteringFunction(const vec4 heightFraction, const vec4 bias) { - // Apply a semi-circle transform to round the clouds towards the top. - vec4 biased = pow(heightFraction, bias); - vec4 x = clamp(biased * 2.0 - 1.0, -1.0, 1.0); - return 1.0 - x * x; -} - -WeatherSample sampleWeather(const vec2 uv, const float height, const float mipLevel) { - WeatherSample weather; - weather.heightFraction = remapClamped(vec4(height), minLayerHeights, maxLayerHeights); - - vec4 localWeather = pow( - textureLod( - localWeatherTexture, - uv * localWeatherRepeat + localWeatherOffset, - mipLevel - ).LOCAL_WEATHER_CHANNELS, - weatherExponents - ); - #ifdef SHADOW - localWeather *= shadowLayerMask; - #endif // SHADOW - - vec4 heightScale = shapeAlteringFunction(weather.heightFraction, shapeAlteringBiases); - - // Modulation to control weather by coverage parameter. - // Reference: https://github.com/Prograda/Skybolt/blob/master/Assets/Core/Shaders/Clouds.h#L63 - vec4 factor = 1.0 - coverage * heightScale; - weather.density = remapClamped( - mix(localWeather, vec4(1.0), coverageFilterWidths), - factor, - factor + coverageFilterWidths - ); - - return weather; -} - -vec4 getLayerDensity(const vec4 heightFraction) { - // prettier-ignore - return densityProfile.expTerms * exp(densityProfile.exponents * heightFraction) + - densityProfile.linearTerms * heightFraction + - densityProfile.constantTerms; -} - -struct MediaSample { - float density; - vec4 weight; - float scattering; - float extinction; -}; - -MediaSample sampleMedia( - const WeatherSample weather, - const vec3 position, - const vec2 uv, - const float mipLevel, - const float jitter, - out ivec3 sampleCount -) { - vec4 density = weather.density; - - // TODO: Define in physical length. - vec3 surfaceNormal = normalize(position); - float localWeatherSpeed = length(localWeatherOffset); - vec3 evolution = -surfaceNormal * localWeatherSpeed * 2e4; - - vec3 turbulence = vec3(0.0); - #ifdef TURBULENCE - vec2 turbulenceUv = uv * localWeatherRepeat * turbulenceRepeat; - turbulence = - turbulenceDisplacement * - (texture(turbulenceTexture, turbulenceUv).rgb * 2.0 - 1.0) * - dot(density, remapClamped(weather.heightFraction, vec4(0.3), vec4(0.0))); - #endif // TURBULENCE - - vec3 shapePosition = (position + evolution + turbulence) * shapeRepeat + shapeOffset; - float shape = texture(shapeTexture, shapePosition).r; - density = remapClamped(density, vec4(1.0 - shape) * shapeAmounts, vec4(1.0)); - - #ifdef DEBUG_SHOW_SAMPLE_COUNT - ++sampleCount.y; - #endif // DEBUG_SHOW_SAMPLE_COUNT - - #ifdef SHAPE_DETAIL - if (mipLevel * 0.5 + (jitter - 0.5) * 0.5 < 0.5) { - vec3 detailPosition = (position + turbulence) * shapeDetailRepeat + shapeDetailOffset; - float detail = texture(shapeDetailTexture, detailPosition).r; - // Fluffy at the top and whippy at the bottom. - vec4 modifier = mix( - vec4(pow(detail, 6.0)), - vec4(1.0 - detail), - remapClamped(weather.heightFraction, vec4(0.2), vec4(0.4)) - ); - modifier = mix(vec4(0.0), modifier, shapeDetailAmounts); - density = remapClamped(density * 2.0, vec4(modifier * 0.5), vec4(1.0)); - - #ifdef DEBUG_SHOW_SAMPLE_COUNT - ++sampleCount.z; - #endif // DEBUG_SHOW_SAMPLE_COUNT - } - #endif // SHAPE_DETAIL - - // Apply the density profiles. - density = saturate(density * densityScales * getLayerDensity(weather.heightFraction)); - - MediaSample media; - float densitySum = density.x + density.y + density.z + density.w; - media.weight = density / densitySum; - media.scattering = densitySum * scatteringCoefficient; - media.extinction = densitySum * absorptionCoefficient + media.scattering; - return media; -} - -MediaSample sampleMedia( - const WeatherSample weather, - const vec3 position, - const vec2 uv, - const float mipLevel, - const float jitter -) { - ivec3 sampleCount; - return sampleMedia(weather, position, uv, mipLevel, jitter, sampleCount); -} -`,qie=`precision highp float; -precision highp sampler3D; - -#include "atmosphere/bruneton/definitions" - -uniform AtmosphereParameters ATMOSPHERE; -uniform vec3 SUN_SPECTRAL_RADIANCE_TO_LUMINANCE; -uniform vec3 SKY_SPECTRAL_RADIANCE_TO_LUMINANCE; - -uniform sampler2D transmittance_texture; -uniform sampler3D scattering_texture; -uniform sampler2D irradiance_texture; -uniform sampler3D single_mie_scattering_texture; -uniform sampler3D higher_order_scattering_texture; - -#include "atmosphere/bruneton/common" -#include "atmosphere/bruneton/runtime" - -#include "types" - -uniform mat4 inverseProjectionMatrix; -uniform mat4 inverseViewMatrix; -uniform vec3 cameraPosition; -uniform mat4 worldToECEFMatrix; -uniform vec3 altitudeCorrection; - -// Atmosphere -uniform float bottomRadius; -uniform vec3 sunDirection; - -// Cloud layers -uniform float minHeight; -uniform float maxHeight; - -layout(location = 0) in vec3 position; - -out vec2 vUv; -out vec3 vCameraPosition; -out vec3 vCameraDirection; // Direction to the center of screen -out vec3 vRayDirection; // Direction to the texel -out vec3 vViewPosition; - -out GroundIrradiance vGroundIrradiance; -out CloudsIrradiance vCloudsIrradiance; - -void sampleSunSkyIrradiance(const vec3 positionECEF) { - vGroundIrradiance.sun = GetSunAndSkyScalarIrradiance( - positionECEF * METER_TO_LENGTH_UNIT, - sunDirection, - vGroundIrradiance.sky - ); - - vec3 surfaceNormal = normalize(positionECEF); - vec2 radii = (bottomRadius + vec2(minHeight, maxHeight)) * METER_TO_LENGTH_UNIT; - vCloudsIrradiance.minSun = GetSunAndSkyScalarIrradiance( - surfaceNormal * radii.x, - sunDirection, - vCloudsIrradiance.minSky - ); - vCloudsIrradiance.maxSun = GetSunAndSkyScalarIrradiance( - surfaceNormal * radii.y, - sunDirection, - vCloudsIrradiance.maxSky - ); -} - -void main() { - vUv = position.xy * 0.5 + 0.5; - - vec3 viewPosition = (inverseProjectionMatrix * vec4(position, 1.0)).xyz; - vec3 worldDirection = (inverseViewMatrix * vec4(viewPosition.xyz, 0.0)).xyz; - vec3 cameraDirection = normalize((inverseViewMatrix * vec4(0.0, 0.0, -1.0, 0.0)).xyz); - vCameraPosition = (worldToECEFMatrix * vec4(cameraPosition, 1.0)).xyz; - vCameraDirection = (worldToECEFMatrix * vec4(cameraDirection, 0.0)).xyz; - vRayDirection = (worldToECEFMatrix * vec4(worldDirection, 0.0)).xyz; - vViewPosition = viewPosition; - - sampleSunSkyIrradiance(vCameraPosition + altitudeCorrection); - - gl_Position = vec4(position.xy, 1.0, 1.0); -} -`,i9=`uniform vec2 resolution; -uniform int frame; -uniform sampler3D stbnTexture; - -// Atmosphere -uniform float bottomRadius; -uniform mat4 worldToECEFMatrix; -uniform mat4 ecefToWorldMatrix; -uniform vec3 altitudeCorrection; -uniform vec3 sunDirection; - -// Participating medium -uniform float scatteringCoefficient; -uniform float absorptionCoefficient; - -// Primary raymarch -uniform float minDensity; -uniform float minExtinction; -uniform float minTransmittance; - -// Shape and weather -uniform sampler2D localWeatherTexture; -uniform vec2 localWeatherRepeat; -uniform vec2 localWeatherOffset; -uniform float coverage; -uniform sampler3D shapeTexture; -uniform vec3 shapeRepeat; -uniform vec3 shapeOffset; - -#ifdef SHAPE_DETAIL -uniform sampler3D shapeDetailTexture; -uniform vec3 shapeDetailRepeat; -uniform vec3 shapeDetailOffset; -#endif // SHAPE_DETAIL - -#ifdef TURBULENCE -uniform sampler2D turbulenceTexture; -uniform vec2 turbulenceRepeat; -uniform float turbulenceDisplacement; -#endif // TURBULENCE - -// Haze -#ifdef HAZE -uniform float hazeDensityScale; -uniform float hazeExponent; -uniform float hazeScatteringCoefficient; -uniform float hazeAbsorptionCoefficient; -#endif // HAZE - -// Cloud layers -uniform vec4 minLayerHeights; -uniform vec4 maxLayerHeights; -uniform vec3 minIntervalHeights; -uniform vec3 maxIntervalHeights; -uniform vec4 densityScales; -uniform vec4 shapeAmounts; -uniform vec4 shapeDetailAmounts; -uniform vec4 weatherExponents; -uniform vec4 shapeAlteringBiases; -uniform vec4 coverageFilterWidths; -uniform float minHeight; -uniform float maxHeight; -uniform float shadowTopHeight; -uniform float shadowBottomHeight; -uniform vec4 shadowLayerMask; -uniform CloudDensityProfile densityProfile; -`,oM=`struct GroundIrradiance { - vec3 sun; - vec3 sky; -}; - -struct CloudsIrradiance { - vec3 minSun; - vec3 minSky; - vec3 maxSun; - vec3 maxSky; -}; - -struct CloudDensityProfile { - vec4 expTerms; - vec4 exponents; - vec4 linearTerms; - vec4 constantTerms; -}; -`;var jie=Object.defineProperty,rr=(n,e,t,i)=>{for(var a=void 0,r=n.length-1,s;r>=0;r--)(s=n[r])&&(a=s(e,t,a)||a);return a&&jie(e,t,a),a};const Zie=new L,Kie=new Z8;let Ha=class extends Z0{constructor({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i},a=j0.DEFAULT){super({name:"CloudsMaterial",glslVersion:ro,vertexShader:Na(qie,{atmosphere:{bruneton:{common:IO,definitions:UO,runtime:LO}},types:oM}),fragmentShader:q0(Na(Yie,{core:{depth:OP,math:_A,turbo:IP,generators:$te,raySphereIntersection:my,cascadedShadowMaps:DP,interleavedGradientNoise:LP,vogelDisk:UP},atmosphere:{bruneton:{common:IO,definitions:UO,runtime:LO}},types:oM,parameters:i9,clouds:n9})),uniforms:{...e,...t,...i,depthBuffer:new J(null),viewMatrix:new J(new ke),inverseProjectionMatrix:new J(new ke),inverseViewMatrix:new J(new ke),reprojectionMatrix:new J(new ke),viewReprojectionMatrix:new J(new ke),resolution:new J(new de),cameraNear:new J(0),cameraFar:new J(0),cameraHeight:new J(0),frame:new J(0),temporalJitter:new J(new de),targetUvScale:new J(new de),mipLevelScale:new J(1),stbnTexture:new J(null),skyLightScale:new J(1),groundBounceScale:new J(1),powderScale:new J(.8),powderExponent:new J(150),maxIterationCount:new J(It.clouds.maxIterationCount),minStepSize:new J(It.clouds.minStepSize),maxStepSize:new J(It.clouds.maxStepSize),maxRayDistance:new J(It.clouds.maxRayDistance),perspectiveStepScale:new J(It.clouds.perspectiveStepScale),minDensity:new J(It.clouds.minDensity),minExtinction:new J(It.clouds.minExtinction),minTransmittance:new J(It.clouds.minTransmittance),maxIterationCountToSun:new J(It.clouds.maxIterationCountToSun),maxIterationCountToGround:new J(It.clouds.maxIterationCountToGround),minSecondaryStepSize:new J(It.clouds.minSecondaryStepSize),secondaryStepScale:new J(It.clouds.secondaryStepScale),shadowBuffer:new J(null),shadowTexelSize:new J(new de),shadowIntervals:new J(Array.from({length:4},()=>new de)),shadowMatrices:new J(Array.from({length:4},()=>new ke)),shadowFar:new J(0),maxShadowFilterRadius:new J(6),shadowLayerMask:new J(new zt().setScalar(1)),maxShadowLengthIterationCount:new J(It.clouds.maxShadowLengthIterationCount),minShadowLengthStepSize:new J(It.clouds.minShadowLengthStepSize),maxShadowLengthRayDistance:new J(It.clouds.maxShadowLengthRayDistance),hazeDensityScale:new J(3e-5),hazeExponent:new J(.001),hazeScatteringCoefficient:new J(.9),hazeAbsorptionCoefficient:new J(.5)}},a),this.temporalUpscale=!0,this.depthPacking=0,this.localWeatherChannels="rgba",this.shapeDetail=It.shapeDetail,this.turbulence=It.turbulence,this.shadowLength=It.lightShafts,this.haze=It.haze,this.multiScatteringOctaves=It.clouds.multiScatteringOctaves,this.accurateSunSkyLight=It.clouds.accurateSunSkyLight,this.accuratePhaseFunction=It.clouds.accuratePhaseFunction,this.shadowCascadeCount=It.shadow.cascadeCount,this.shadowSampleCount=8,this.scatterAnisotropy1=.7,this.scatterAnisotropy2=-.2,this.scatterAnisotropyMix=.5}onBeforeRender(e,t,i,a,r,s){const o=this.defines.USE_LOGARITHMIC_DEPTH_BUFFER!=null,c=e.capabilities.logarithmicDepthBuffer;c!==o&&(c?this.defines.USE_LOGARITHMIC_DEPTH_BUFFER="1":delete this.defines.USE_LOGARITHMIC_DEPTH_BUFFER);const h=this.defines.POWDER!=null,f=this.uniforms.powderScale.value>0;f!==h&&(f?this.defines.POWDER="1":delete this.defines.POWDER,this.needsUpdate=!0);const d=this.defines.GROUND_BOUNCE!=null;(this.uniforms.groundBounceScale.value>0&&this.uniforms.maxIterationCountToGround.value>0)!==d&&(f?this.defines.GROUND_BOUNCE="1":delete this.defines.GROUND_BOUNCE,this.needsUpdate=!0)}copyCameraSettings(e){e.isPerspectiveCamera===!0?this.defines.PERSPECTIVE_CAMERA!=="1"&&(this.defines.PERSPECTIVE_CAMERA="1",this.needsUpdate=!0):this.defines.PERSPECTIVE_CAMERA!=null&&(delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0);const t=this.uniforms;t.viewMatrix.value.copy(e.matrixWorldInverse),t.inverseViewMatrix.value.copy(e.matrixWorld);const i=this.previousProjectionMatrix??e.projectionMatrix,a=this.previousViewMatrix??e.matrixWorldInverse,r=t.inverseProjectionMatrix.value,s=t.inverseViewMatrix.value,o=t.reprojectionMatrix.value,c=t.viewReprojectionMatrix.value;if(this.temporalUpscale){const d=t.frame.value%16,m=t.resolution.value,g=t9[d],x=(g.x-.5)/m.x*4,T=(g.y-.5)/m.y*4;t.temporalJitter.value.set(x,T),t.mipLevelScale.value=.25,r.copy(e.projectionMatrix),r.elements[8]+=x*2,r.elements[9]+=T*2,r.invert(),o.copy(i),o.elements[8]+=x*2,o.elements[9]+=T*2,o.multiply(a),c.copy(o).multiply(s)}else t.temporalJitter.value.setScalar(0),t.mipLevelScale.value=1,r.copy(e.projectionMatrixInverse),o.copy(i).multiply(a),c.copy(o).multiply(s);t.cameraNear.value=e.near,t.cameraFar.value=e.far;const h=e.getWorldPosition(t.cameraPosition.value),f=Zie.copy(h).applyMatrix4(t.worldToECEFMatrix.value);try{t.cameraHeight.value=Kie.setFromECEF(f).height}catch{}}copyReprojectionMatrix(e){this.previousProjectionMatrix??(this.previousProjectionMatrix=new ke),this.previousViewMatrix??(this.previousViewMatrix=new ke),this.previousProjectionMatrix.copy(e.projectionMatrix),this.previousViewMatrix.copy(e.matrixWorldInverse)}setSize(e,t,i,a){this.uniforms.resolution.value.set(e,t),i!=null&&a!=null?this.uniforms.targetUvScale.value.set(e/i,t/a):this.uniforms.targetUvScale.value.setScalar(1),this.previousProjectionMatrix=void 0,this.previousViewMatrix=void 0}setShadowSize(e,t){this.uniforms.shadowTexelSize.value.set(1/e,1/t)}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(e){this.uniforms.depthBuffer.value=e}get accurateSunSkyIrradiance(){return this.accurateSunSkyLight}set accurateSunSkyIrradiance(e){this.accurateSunSkyLight=e}};rr([mh("DEPTH_PACKING")],Ha.prototype,"depthPacking");rr([RP("LOCAL_WEATHER_CHANNELS",{validate:n=>/^[rgba]{4}$/.test(n)})],Ha.prototype,"localWeatherChannels");rr([dn("SHAPE_DETAIL")],Ha.prototype,"shapeDetail");rr([dn("TURBULENCE")],Ha.prototype,"turbulence");rr([dn("SHADOW_LENGTH")],Ha.prototype,"shadowLength");rr([dn("HAZE")],Ha.prototype,"haze");rr([mh("MULTI_SCATTERING_OCTAVES",{min:1,max:12})],Ha.prototype,"multiScatteringOctaves");rr([dn("ACCURATE_SUN_SKY_LIGHT")],Ha.prototype,"accurateSunSkyLight");rr([dn("ACCURATE_PHASE_FUNCTION")],Ha.prototype,"accuratePhaseFunction");rr([mh("SHADOW_CASCADE_COUNT",{min:1,max:4})],Ha.prototype,"shadowCascadeCount");rr([mh("SHADOW_SAMPLE_COUNT",{min:1,max:16})],Ha.prototype,"shadowSampleCount");rr([vA("SCATTER_ANISOTROPY_1")],Ha.prototype,"scatterAnisotropy1");rr([vA("SCATTER_ANISOTROPY_2")],Ha.prototype,"scatterAnisotropy2");rr([vA("SCATTER_ANISOTROPY_MIX")],Ha.prototype,"scatterAnisotropyMix");const Qie=`// Taken from https://gist.github.com/TheRealMJP/c83b8c0f46b63f3a88a5986f4fa982b1 -// TODO: Use 5-taps version: https://www.shadertoy.com/view/MtVGWz -// Or even 4 taps (requires preprocessing in the input buffer): -// https://www.shadertoy.com/view/4tyGDD - -/** - * MIT License - * - * Copyright (c) 2019 MJP - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -vec4 textureCatmullRom(sampler2D tex, vec2 uv) { - vec2 texSize = vec2(textureSize(tex, 0)); - - // We're going to sample a a 4x4 grid of texels surrounding the target UV - // coordinate. We'll do this by rounding down the sample location to get the - // exact center of our "starting" texel. The starting texel will be at - // location [1, 1] in the grid, where [0, 0] is the top left corner. - vec2 samplePos = uv * texSize; - vec2 texPos1 = floor(samplePos - 0.5) + 0.5; - - // Compute the fractional offset from our starting texel to our original - // sample location, which we'll feed into the Catmull-Rom spline function to - // get our filter weights. - vec2 f = samplePos - texPos1; - - // Compute the Catmull-Rom weights using the fractional offset that we - // calculated earlier. These equations are pre-expanded based on our knowledge - // of where the texels will be located, which lets us avoid having to evaluate - // a piece-wise function. - vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f)); - vec2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f); - vec2 w2 = f * (0.5 + f * (2.0 - 1.5 * f)); - vec2 w3 = f * f * (-0.5 + 0.5 * f); - - // Work out weighting factors and sampling offsets that will let us use - // bilinear filtering to simultaneously evaluate the middle 2 samples from the - // 4x4 grid. - vec2 w12 = w1 + w2; - vec2 offset12 = w2 / (w1 + w2); - - // Compute the final UV coordinates we'll use for sampling the texture - vec2 texPos0 = texPos1 - 1.0; - vec2 texPos3 = texPos1 + 2.0; - vec2 texPos12 = texPos1 + offset12; - - texPos0 /= texSize; - texPos3 /= texSize; - texPos12 /= texSize; - - vec4 result = vec4(0.0); - result += texture(tex, vec2(texPos0.x, texPos0.y)) * w0.x * w0.y; - result += texture(tex, vec2(texPos12.x, texPos0.y)) * w12.x * w0.y; - result += texture(tex, vec2(texPos3.x, texPos0.y)) * w3.x * w0.y; - - result += texture(tex, vec2(texPos0.x, texPos12.y)) * w0.x * w12.y; - result += texture(tex, vec2(texPos12.x, texPos12.y)) * w12.x * w12.y; - result += texture(tex, vec2(texPos3.x, texPos12.y)) * w3.x * w12.y; - - result += texture(tex, vec2(texPos0.x, texPos3.y)) * w0.x * w3.y; - result += texture(tex, vec2(texPos12.x, texPos3.y)) * w12.x * w3.y; - result += texture(tex, vec2(texPos3.x, texPos3.y)) * w3.x * w3.y; - - return result; -} - -vec4 textureCatmullRom(sampler2DArray tex, vec3 uv) { - vec2 texSize = vec2(textureSize(tex, 0)); - vec2 samplePos = uv.xy * texSize; - vec2 texPos1 = floor(samplePos - 0.5) + 0.5; - vec2 f = samplePos - texPos1; - vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f)); - vec2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f); - vec2 w2 = f * (0.5 + f * (2.0 - 1.5 * f)); - vec2 w3 = f * f * (-0.5 + 0.5 * f); - vec2 w12 = w1 + w2; - vec2 offset12 = w2 / (w1 + w2); - vec2 texPos0 = texPos1 - 1.0; - vec2 texPos3 = texPos1 + 2.0; - vec2 texPos12 = texPos1 + offset12; - texPos0 /= texSize; - texPos3 /= texSize; - texPos12 /= texSize; - vec4 result = vec4(0.0); - result += texture(tex, vec3(texPos0.x, texPos0.y, uv.z)) * w0.x * w0.y; - result += texture(tex, vec3(texPos12.x, texPos0.y, uv.z)) * w12.x * w0.y; - result += texture(tex, vec3(texPos3.x, texPos0.y, uv.z)) * w3.x * w0.y; - result += texture(tex, vec3(texPos0.x, texPos12.y, uv.z)) * w0.x * w12.y; - result += texture(tex, vec3(texPos12.x, texPos12.y, uv.z)) * w12.x * w12.y; - result += texture(tex, vec3(texPos3.x, texPos12.y, uv.z)) * w3.x * w12.y; - result += texture(tex, vec3(texPos0.x, texPos3.y, uv.z)) * w0.x * w3.y; - result += texture(tex, vec3(texPos12.x, texPos3.y, uv.z)) * w12.x * w3.y; - result += texture(tex, vec3(texPos3.x, texPos3.y, uv.z)) * w3.x * w3.y; - return result; -} -`,Jie=`precision highp float; -precision highp sampler2DArray; - -#include "core/turbo" -#include "catmullRomSampling" -#include "varianceClipping" - -uniform sampler2D colorBuffer; -uniform sampler2D depthVelocityBuffer; -uniform sampler2D colorHistoryBuffer; - -#ifdef SHADOW_LENGTH -uniform sampler2D shadowLengthBuffer; -uniform sampler2D shadowLengthHistoryBuffer; -#endif // SHADOW_LENGTH - -uniform vec2 texelSize; -uniform int frame; -uniform float varianceGamma; -uniform float temporalAlpha; -uniform vec2 jitterOffset; - -in vec2 vUv; - -layout(location = 0) out vec4 outputColor; -#ifdef SHADOW_LENGTH -layout(location = 1) out float outputShadowLength; -#endif // SHADOW_LENGTH - -const ivec2 neighborOffsets[9] = ivec2[9]( - ivec2(-1, -1), - ivec2(-1, 0), - ivec2(-1, 1), - ivec2(0, -1), - ivec2(0, 0), - ivec2(0, 1), - ivec2(1, -1), - ivec2(1, 0), - ivec2(1, 1) -); - -const ivec4[4] bayerIndices = ivec4[4]( - ivec4(0, 12, 3, 15), - ivec4(8, 4, 11, 7), - ivec4(2, 14, 1, 13), - ivec4(10, 6, 9, 5) -); - -vec4 getClosestFragment(const ivec2 coord) { - vec4 result = vec4(1e7, 0.0, 0.0, 0.0); - vec4 neighbor; - #pragma unroll_loop_start - for (int i = 0; i < 9; ++i) { - neighbor = texelFetchOffset(depthVelocityBuffer, coord, 0, neighborOffsets[i]); - if (neighbor.r < result.r) { - result = neighbor; - } - } - #pragma unroll_loop_end - return result; -} - -void temporalUpscale( - const ivec2 coord, - const ivec2 lowResCoord, - const bool currentFrame, - out vec4 outputColor, - out float outputShadowLength -) { - vec4 currentColor = texelFetch(colorBuffer, lowResCoord, 0); - #ifdef SHADOW_LENGTH - vec4 currentShadowLength = vec4(texelFetch(shadowLengthBuffer, lowResCoord, 0).rgb, 1.0); - #endif // SHADOW_LENGTH - - if (currentFrame) { - // Use the texel just rendered without any accumulation. - outputColor = currentColor; - #ifdef SHADOW_LENGTH - outputShadowLength = currentShadowLength.r; - #endif // SHADOW_LENGTH - return; - } - - vec4 depthVelocity = getClosestFragment(lowResCoord); - vec2 velocity = depthVelocity.gb; - vec2 prevUv = vUv - velocity; - if (prevUv.x < 0.0 || prevUv.x > 1.0 || prevUv.y < 0.0 || prevUv.y > 1.0) { - outputColor = currentColor; - #ifdef SHADOW_LENGTH - outputShadowLength = currentShadowLength.r; - #endif // SHADOW_LENGTH - return; // Rejection - } - - // Variance clipping with a large variance gamma seems to work fine for - // upsampling. This increases ghosting, of course, but it's hard to notice on - // clouds. - // vec4 historyColor = textureCatmullRom(colorHistoryBuffer, prevUv); - vec4 historyColor = texture(colorHistoryBuffer, prevUv); - vec4 clippedColor = varianceClipping(colorBuffer, vUv, currentColor, historyColor, varianceGamma); - outputColor = clippedColor; - - #ifdef SHADOW_LENGTH - // Sampling the shadow length history using scene depth doesn't make much - // sense, but it's too hard to derive it properly. At least this approach - // resolves the edges of scene objects. - // vec4 historyShadowLength = vec4(textureCatmullRom(shadowLengthHistoryBuffer, prevUv).rgb, 1.0); - vec4 historyShadowLength = vec4(texture(shadowLengthHistoryBuffer, prevUv).rgb, 1.0); - vec4 clippedShadowLength = varianceClipping( - shadowLengthBuffer, - vUv, - currentShadowLength, - historyShadowLength, - varianceGamma - ); - outputShadowLength = clippedShadowLength.r; - #endif // SHADOW_LENGTH -} - -void temporalAntialiasing(const ivec2 coord, out vec4 outputColor, out float outputShadowLength) { - vec4 currentColor = texelFetch(colorBuffer, coord, 0); - #ifdef SHADOW_LENGTH - vec4 currentShadowLength = vec4(texelFetch(shadowLengthBuffer, coord, 0).rgb, 1.0); - #endif // SHADOW_LENGTH - - vec4 depthVelocity = getClosestFragment(coord); - vec2 velocity = depthVelocity.gb; - - vec2 prevUv = vUv - velocity; - if (prevUv.x < 0.0 || prevUv.x > 1.0 || prevUv.y < 0.0 || prevUv.y > 1.0) { - outputColor = currentColor; - #ifdef SHADOW_LENGTH - outputShadowLength = currentShadowLength.r; - #endif // SHADOW_LENGTH - return; // Rejection - } - - vec4 historyColor = texture(colorHistoryBuffer, prevUv); - vec4 clippedColor = varianceClipping(colorBuffer, coord, currentColor, historyColor); - outputColor = mix(clippedColor, currentColor, temporalAlpha); - - #ifdef SHADOW_LENGTH - vec4 historyShadowLength = vec4(texture(shadowLengthHistoryBuffer, prevUv).rgb, 1.0); - vec4 clippedShadowLength = varianceClipping( - shadowLengthBuffer, - coord, - currentShadowLength, - historyShadowLength - ); - outputShadowLength = mix(clippedShadowLength.r, currentShadowLength.r, temporalAlpha); - #endif // SHADOW_LENGTH -} - -void main() { - ivec2 coord = ivec2(gl_FragCoord.xy); - - #if !defined(SHADOW_LENGTH) - float outputShadowLength; - #endif // !defined(SHADOW_LENGTH) - - #ifdef TEMPORAL_UPSCALE - ivec2 lowResCoord = coord / 4; - int bayerValue = bayerIndices[coord.x % 4][coord.y % 4]; - bool currentFrame = bayerValue == frame % 16; - temporalUpscale(coord, lowResCoord, currentFrame, outputColor, outputShadowLength); - #else // TEMPORAL_UPSCALE - temporalAntialiasing(coord, outputColor, outputShadowLength); - #endif // TEMPORAL_UPSCALE - - #if defined(SHADOW_LENGTH) && defined(DEBUG_SHOW_SHADOW_LENGTH) - outputColor = vec4(turbo(outputShadowLength * 0.05), 1.0); - #endif // defined(SHADOW_LENGTH) && defined(DEBUG_SHOW_SHADOW_LENGTH) - - #ifdef DEBUG_SHOW_VELOCITY - outputColor.rgb = outputColor.rgb + vec3(abs(texture(depthVelocityBuffer, vUv).gb) * 10.0, 0.0); - #endif // DEBUG_SHOW_VELOCITY -} -`,$ie=`precision highp float; - -layout(location = 0) in vec3 position; - -out vec2 vUv; - -void main() { - vUv = position.xy * 0.5 + 0.5; - gl_Position = vec4(position.xy, 1.0, 1.0); -} -`,a9=`#ifdef VARIANCE_9_SAMPLES -#define VARIANCE_OFFSET_COUNT 8 -const ivec2 varianceOffsets[8] = ivec2[8]( - ivec2(-1, -1), - ivec2(-1, 1), - ivec2(1, -1), - ivec2(1, 1), - ivec2(1, 0), - ivec2(0, -1), - ivec2(0, 1), - ivec2(-1, 0) -); -#else // VARIANCE_9_SAMPLES -#define VARIANCE_OFFSET_COUNT 4 -const ivec2 varianceOffsets[4] = ivec2[4](ivec2(1, 0), ivec2(0, -1), ivec2(0, 1), ivec2(-1, 0)); -#endif // VARIANCE_9_SAMPLES - -// Reference: https://github.com/playdeadgames/temporal -vec4 clipAABB(const vec4 current, const vec4 history, const vec4 minColor, const vec4 maxColor) { - vec3 pClip = 0.5 * (maxColor.rgb + minColor.rgb); - vec3 eClip = 0.5 * (maxColor.rgb - minColor.rgb) + 1e-7; - vec4 vClip = history - vec4(pClip, current.a); - vec3 vUnit = vClip.xyz / eClip; - vec3 aUnit = abs(vUnit); - float maUnit = max(aUnit.x, max(aUnit.y, aUnit.z)); - if (maUnit > 1.0) { - return vec4(pClip, current.a) + vClip / maUnit; - } - return history; -} - -#ifdef VARIANCE_SAMPLER_ARRAY -#define VARIANCE_SAMPLER sampler2DArray -#define VARIANCE_SAMPLER_COORD ivec3 -#else // VARIANCE_SAMPLER_ARRAY -#define VARIANCE_SAMPLER sampler2D -#define VARIANCE_SAMPLER_COORD ivec2 -#endif // VARIANCE_SAMPLER_ARRAY - -// Variance clipping -// Reference: https://developer.download.nvidia.com/gameworks/events/GDC2016/msalvi_temporal_supersampling.pdf -vec4 varianceClipping( - const VARIANCE_SAMPLER inputBuffer, - const VARIANCE_SAMPLER_COORD coord, - const vec4 current, - const vec4 history, - const float gamma -) { - vec4 moment1 = current; - vec4 moment2 = current * current; - vec4 neighbor; - #pragma unroll_loop_start - for (int i = 0; i < 8; ++i) { - #if UNROLLED_LOOP_INDEX < VARIANCE_OFFSET_COUNT - neighbor = texelFetchOffset(inputBuffer, coord, 0, varianceOffsets[i]); - moment1 += neighbor; - moment2 += neighbor * neighbor; - #endif // UNROLLED_LOOP_INDEX < VARIANCE_OFFSET_COUNT - } - #pragma unroll_loop_end - - const float N = float(VARIANCE_OFFSET_COUNT + 1); - vec4 mean = moment1 / N; - vec4 varianceGamma = sqrt(max(moment2 / N - mean * mean, 0.0)) * gamma; - vec4 minColor = mean - varianceGamma; - vec4 maxColor = mean + varianceGamma; - return clipAABB(clamp(mean, minColor, maxColor), history, minColor, maxColor); -} - -vec4 varianceClipping( - const VARIANCE_SAMPLER inputBuffer, - const VARIANCE_SAMPLER_COORD coord, - const vec4 current, - const vec4 history -) { - return varianceClipping(inputBuffer, coord, current, history, 1.0); -} - -vec4 varianceClipping( - const sampler2D inputBuffer, - const vec2 coord, - const vec4 current, - const vec4 history, - const float gamma -) { - vec4 moment1 = current; - vec4 moment2 = current * current; - vec4 neighbor; - #pragma unroll_loop_start - for (int i = 0; i < 8; ++i) { - #if UNROLLED_LOOP_INDEX < VARIANCE_OFFSET_COUNT - neighbor = textureOffset(inputBuffer, coord, varianceOffsets[i]); - moment1 += neighbor; - moment2 += neighbor * neighbor; - #endif // UNROLLED_LOOP_INDEX < VARIANCE_OFFSET_COUNT - } - #pragma unroll_loop_end - - const float N = float(VARIANCE_OFFSET_COUNT + 1); - vec4 mean = moment1 / N; - vec4 varianceGamma = sqrt(max(moment2 / N - mean * mean, 0.0)) * gamma; - vec4 minColor = mean - varianceGamma; - vec4 maxColor = mean + varianceGamma; - return clipAABB(clamp(mean, minColor, maxColor), history, minColor, maxColor); -} - -vec4 varianceClipping( - const sampler2D inputBuffer, - const vec2 coord, - const vec4 current, - const vec4 history -) { - return varianceClipping(inputBuffer, coord, current, history, 1.0); -} -`;var eae=Object.defineProperty,r9=(n,e,t,i)=>{for(var a=void 0,r=n.length-1,s;r>=0;r--)(s=n[r])&&(a=s(e,t,a)||a);return a&&eae(e,t,a),a};class wA extends hh{constructor({colorBuffer:e=null,depthVelocityBuffer:t=null,shadowLengthBuffer:i=null,colorHistoryBuffer:a=null,shadowLengthHistoryBuffer:r=null}={}){super({name:"CloudsResolveMaterial",glslVersion:ro,vertexShader:$ie,fragmentShader:q0(Na(Jie,{core:{turbo:IP},catmullRomSampling:Qie,varianceClipping:a9})),uniforms:{colorBuffer:new J(e),depthVelocityBuffer:new J(t),shadowLengthBuffer:new J(i),colorHistoryBuffer:new J(a),shadowLengthHistoryBuffer:new J(r),texelSize:new J(new de),frame:new J(0),jitterOffset:new J(new de),varianceGamma:new J(2),temporalAlpha:new J(.1)}}),this.temporalUpscale=!0,this.shadowLength=!0}setSize(e,t){this.uniforms.texelSize.value.set(1/e,1/t)}onBeforeRender(e,t,i,a,r,s){const o=this.uniforms.frame.value%16,c=t9[o],h=(c.x-.5)*4,f=(c.y-.5)*4;this.uniforms.jitterOffset.value.set(h,f)}}r9([dn("TEMPORAL_UPSCALE")],wA.prototype,"temporalUpscale");r9([dn("SHADOW_LENGTH")],wA.prototype,"shadowLength");class s9 extends za{constructor(e,t){super(e),this._mainCamera=new bc;const{shadow:i}=t;this.shadow=i}get mainCamera(){return this._mainCamera}set mainCamera(e){this._mainCamera=e}}function n3(n,{depthVelocity:e,shadowLength:t}){const i=new xi(1,1,{depthBuffer:!1,type:Xn});i.texture.minFilter=Ht,i.texture.magFilter=Ht,i.texture.name=n;let a;e&&(a=i.texture.clone(),a.isRenderTargetTexture=!0,i.depthVelocity=a,i.textures.push(a));let r;return t&&(r=i.texture.clone(),r.isRenderTargetTexture=!0,r.format=As,i.shadowLength=r,i.textures.push(r)),Object.assign(i,{depthVelocity:a??null,shadowLength:r??null})}class tae extends s9{constructor({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i,...a},r){super("CloudsPass",a),this.atmosphere=r,this.width=0,this.height=0,this.currentMaterial=new Ha({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i},r),this.currentPass=new IE(this.currentMaterial),this.resolveMaterial=new wA,this.resolvePass=new IE(this.resolveMaterial),this.initRenderTargets({depthVelocity:!0,shadowLength:It.lightShafts})}copyCameraSettings(e){this.currentMaterial.copyCameraSettings(e)}initialize(e,t,i){this.currentPass.initialize(e,t,i),this.resolvePass.initialize(e,t,i)}initRenderTargets(e){var s,o,c;(s=this.currentRenderTarget)==null||s.dispose(),(o=this.resolveRenderTarget)==null||o.dispose(),(c=this.historyRenderTarget)==null||c.dispose();const t=n3("Clouds",e),i=n3("Clouds.A",{...e,depthVelocity:!1}),a=n3("Clouds.B",{...e,depthVelocity:!1});this.currentRenderTarget=t,this.resolveRenderTarget=i,this.historyRenderTarget=a;const r=this.resolveMaterial.uniforms;r.colorBuffer.value=t.texture,r.depthVelocityBuffer.value=t.depthVelocity,r.shadowLengthBuffer.value=t.shadowLength,r.colorHistoryBuffer.value=a.texture,r.shadowLengthHistoryBuffer.value=a.shadowLength}copyShadow(){const e=this.shadow,t=this.currentMaterial.uniforms;for(let i=0;i - -#include "core/math" -#include "core/raySphereIntersection" -#include "types" -#include "parameters" -#include "structuredSampling" -#include "clouds" - -uniform mat4 inverseShadowMatrices[CASCADE_COUNT]; -uniform mat4 reprojectionMatrices[CASCADE_COUNT]; - -// Primary raymarch -uniform int maxIterationCount; -uniform float minStepSize; -uniform float maxStepSize; -uniform float opticalDepthTailScale; - -in vec2 vUv; - -layout(location = 0) out vec4 outputColor[CASCADE_COUNT]; - -// Redundant notation for prettier. -#if CASCADE_COUNT == 1 -layout(location = 1) out vec3 outputDepthVelocity[CASCADE_COUNT]; -#elif CASCADE_COUNT == 2 -layout(location = 2) out vec3 outputDepthVelocity[CASCADE_COUNT]; -#elif CASCADE_COUNT == 3 -layout(location = 3) out vec3 outputDepthVelocity[CASCADE_COUNT]; -#elif CASCADE_COUNT == 4 -layout(location = 4) out vec3 outputDepthVelocity[CASCADE_COUNT]; -#endif // CASCADE_COUNT - -vec4 marchClouds( - const vec3 rayOrigin, - const vec3 rayDirection, - const float maxRayDistance, - const float jitter, - const float mipLevel -) { - // Setup structured volume sampling (SVS). - // While SVS introduces spatial aliasing, it is indeed temporally stable, - // which is important for lower-resolution shadow maps where a flickering - // single pixel can be highly noticeable. - vec3 normal = getStructureNormal(rayDirection, jitter); - float rayDistance; - float stepSize; - intersectStructuredPlanes( - normal, - rayOrigin, - rayDirection, - clamp(maxRayDistance / float(maxIterationCount), minStepSize, maxStepSize), - rayDistance, - stepSize - ); - - #ifdef TEMPORAL_JITTER - rayDistance -= stepSize * jitter; - #endif // TEMPORAL_JITTER - - float extinctionSum = 0.0; - float maxOpticalDepth = 0.0; - float maxOpticalDepthTail = 0.0; - float transmittanceIntegral = 1.0; - float weightedDistanceSum = 0.0; - float transmittanceSum = 0.0; - - int sampleCount = 0; - for (int i = 0; i < maxIterationCount; ++i) { - if (rayDistance > maxRayDistance) { - break; // Termination - } - - vec3 position = rayDistance * rayDirection + rayOrigin; - float height = length(position) - bottomRadius; - - #if !defined(DEBUG_MARCH_INTERVALS) - if (insideLayerIntervals(height)) { - rayDistance += stepSize; - continue; - } - #endif // !defined(DEBUG_MARCH_INTERVALS) - - // Sample rough weather. - vec2 uv = getGlobeUv(position); - WeatherSample weather = sampleWeather(uv, height, mipLevel); - - if (any(greaterThan(weather.density, vec4(minDensity)))) { - // Sample detailed participating media. - // Note this assumes an homogeneous medium. - MediaSample media = sampleMedia(weather, position, uv, mipLevel, jitter); - if (media.extinction > minExtinction) { - extinctionSum += media.extinction; - maxOpticalDepth += media.extinction * stepSize; - transmittanceIntegral *= exp(-media.extinction * stepSize); - weightedDistanceSum += rayDistance * transmittanceIntegral; - transmittanceSum += transmittanceIntegral; - ++sampleCount; - } - } - - if (transmittanceIntegral <= minTransmittance) { - // A large amount of optical depth accumulates in the tail, beyond the - // point of minimum transmittance. The expected optical depth seems to - // decrease exponentially with the number of samples taken before reaching - // the minimum transmittance. - // See the discussion here: https://x.com/shotamatsuda/status/1886259549931520437 - maxOpticalDepthTail = min( - opticalDepthTailScale * stepSize * exp(float(1 - sampleCount)), - stepSize * 0.5 // Excessive optical depth only introduces aliasing. - ); - break; // Early termination - } - rayDistance += stepSize; - } - - if (sampleCount == 0) { - return vec4(maxRayDistance, 0.0, 0.0, 0.0); - } - float frontDepth = min(weightedDistanceSum / transmittanceSum, maxRayDistance); - float meanExtinction = extinctionSum / float(sampleCount); - return vec4(frontDepth, meanExtinction, maxOpticalDepth, maxOpticalDepthTail); -} - -void getRayNearFar( - const vec3 sunPosition, - const vec3 rayDirection, - out float rayNear, - out float rayFar -) { - vec4 firstIntersections = raySphereFirstIntersection( - sunPosition, - rayDirection, - vec3(0.0), - bottomRadius + vec4(shadowTopHeight, shadowBottomHeight, 0.0, 0.0) - ); - rayNear = max(0.0, firstIntersections.x); - rayFar = firstIntersections.y; - if (rayFar < 0.0) { - rayFar = 1e6; - } -} - -void cascade( - const int cascadeIndex, - const float mipLevel, - out vec4 outputColor, - out vec3 outputDepthVelocity -) { - vec2 clip = vUv * 2.0 - 1.0; - vec4 point = inverseShadowMatrices[cascadeIndex] * vec4(clip.xy, -1.0, 1.0); - point /= point.w; - vec3 sunPosition = (worldToECEFMatrix * vec4(point.xyz, 1.0)).xyz + altitudeCorrection; - - vec3 rayDirection = normalize(-sunDirection); - float rayNear; - float rayFar; - getRayNearFar(sunPosition, rayDirection, rayNear, rayFar); - - vec3 rayOrigin = rayNear * rayDirection + sunPosition; - float stbn = getSTBN(); - vec4 color = marchClouds(rayOrigin, rayDirection, rayFar - rayNear, stbn, mipLevel); - outputColor = color; - - // Velocity for temporal resolution. - #ifdef TEMPORAL_PASS - vec3 frontPosition = color.x * rayDirection + rayOrigin; - vec3 frontPositionWorld = (ecefToWorldMatrix * vec4(frontPosition - altitudeCorrection, 1.0)).xyz; - vec4 prevClip = reprojectionMatrices[cascadeIndex] * vec4(frontPositionWorld, 1.0); - prevClip /= prevClip.w; - vec2 prevUv = prevClip.xy * 0.5 + 0.5; - vec2 velocity = (vUv - prevUv) * resolution; - outputDepthVelocity = vec3(color.x, velocity); - #else // TEMPORAL_PASS - outputDepthVelocity = vec3(0.0); - #endif // TEMPORAL_PASS -} - -// TODO: Calculate from the main camera frustum perhaps? -const float mipLevels[4] = float[4](0.0, 0.5, 1.0, 2.0); - -void main() { - #pragma unroll_loop_start - for (int i = 0; i < 4; ++i) { - #if UNROLLED_LOOP_INDEX < CASCADE_COUNT - cascade(UNROLLED_LOOP_INDEX, mipLevels[i], outputColor[i], outputDepthVelocity[i]); - #endif // UNROLLED_LOOP_INDEX < CASCADE_COUNT - } - #pragma unroll_loop_end -} -`,aae=`precision highp float; - -layout(location = 0) in vec3 position; - -out vec2 vUv; - -void main() { - vUv = position.xy * 0.5 + 0.5; - gl_Position = vec4(position.xy, 1.0, 1.0); -} -`,rae=`// Implements Structured Volume Sampling in fragment shader: -// https://github.com/huwb/volsample -// Implementation reference: -// https://www.shadertoy.com/view/ttVfDc - -void getIcosahedralVertices(const vec3 direction, out vec3 v1, out vec3 v2, out vec3 v3) { - // Normalization scalers to fit dodecahedron to unit sphere. - const float a = 0.85065080835204; // phi / sqrt(2 + phi) - const float b = 0.5257311121191336; // 1 / sqrt(2 + phi) - - // Derive the vertices of icosahedron where triangle intersects the direction. - // See: https://www.ppsloan.org/publications/AmbientDice.pdf - const float kT = 0.6180339887498948; // 1 / phi - const float kT2 = 0.38196601125010515; // 1 / phi^2 - vec3 absD = abs(direction); - float selector1 = dot(absD, vec3(1.0, kT2, -kT)); - float selector2 = dot(absD, vec3(-kT, 1.0, kT2)); - float selector3 = dot(absD, vec3(kT2, -kT, 1.0)); - v1 = selector1 > 0.0 ? vec3(a, b, 0.0) : vec3(-b, 0.0, a); - v2 = selector2 > 0.0 ? vec3(0.0, a, b) : vec3(a, -b, 0.0); - v3 = selector3 > 0.0 ? vec3(b, 0.0, a) : vec3(0.0, a, -b); - vec3 octantSign = sign(direction); - v1 *= octantSign; - v2 *= octantSign; - v3 *= octantSign; -} - -void swapIfBigger(inout vec4 a, inout vec4 b) { - if (a.w > b.w) { - vec4 t = a; - a = b; - b = t; - } -} - -void sortVertices(inout vec3 a, inout vec3 b, inout vec3 c) { - const vec3 base = vec3(0.5, 0.5, 1.0); - vec4 aw = vec4(a, dot(a, base)); - vec4 bw = vec4(b, dot(b, base)); - vec4 cw = vec4(c, dot(c, base)); - swapIfBigger(aw, bw); - swapIfBigger(bw, cw); - swapIfBigger(aw, bw); - a = aw.xyz; - b = bw.xyz; - c = cw.xyz; -} - -vec3 getPentagonalWeights(const vec3 direction, const vec3 v1, const vec3 v2, const vec3 v3) { - float d1 = dot(v1, direction); - float d2 = dot(v2, direction); - float d3 = dot(v3, direction); - vec3 w = exp(vec3(d1, d2, d3) * 40.0); - return w / (w.x + w.y + w.z); -} - -vec3 getStructureNormal( - const vec3 direction, - const float jitter, - out vec3 a, - out vec3 b, - out vec3 c, - out vec3 weights -) { - getIcosahedralVertices(direction, a, b, c); - sortVertices(a, b, c); - weights = getPentagonalWeights(direction, a, b, c); - return jitter < weights.x - ? a - : jitter < weights.x + weights.y - ? b - : c; -} - -vec3 getStructureNormal(const vec3 direction, const float jitter) { - vec3 a, b, c, weights; - return getStructureNormal(direction, jitter, a, b, c, weights); -} - -// Reference: https://github.com/huwb/volsample/blob/master/src/unity/Assets/Shaders/RayMarchCore.cginc -void intersectStructuredPlanes( - const vec3 normal, - const vec3 rayOrigin, - const vec3 rayDirection, - const float samplePeriod, - out float stepOffset, - out float stepSize -) { - float NoD = dot(rayDirection, normal); - stepSize = samplePeriod / abs(NoD); - - // Skips leftover bit to get from rayOrigin to first strata plane. - stepOffset = -mod(dot(rayOrigin, normal), samplePeriod) / NoD; - - // mod() gives different results depending on if the arg is negative or - // positive. This line makes it consistent, and ensures the first sample is in - // front of the viewer. - if (stepOffset < 0.0) { - stepOffset += stepSize; - } -} -`;var sae=Object.defineProperty,np=(n,e,t,i)=>{for(var a=void 0,r=n.length-1,s;r>=0;r--)(s=n[r])&&(a=s(e,t,a)||a);return a&&sae(e,t,a),a};class vh extends hh{constructor({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i}){super({name:"ShadowMaterial",glslVersion:ro,vertexShader:aae,fragmentShader:q0(Na(iae,{core:{math:_A,raySphereIntersection:my},types:oM,parameters:i9,structuredSampling:rae,clouds:n9})),uniforms:{...e,...t,...i,inverseShadowMatrices:new J(Array.from({length:4},()=>new ke)),reprojectionMatrices:new J(Array.from({length:4},()=>new ke)),resolution:new J(new de),frame:new J(0),stbnTexture:new J(null),maxIterationCount:new J(It.shadow.maxIterationCount),minStepSize:new J(It.shadow.minStepSize),maxStepSize:new J(It.shadow.maxStepSize),minDensity:new J(It.shadow.minDensity),minExtinction:new J(It.shadow.minExtinction),minTransmittance:new J(It.shadow.minTransmittance),opticalDepthTailScale:new J(2)},defines:{SHADOW:"1",TEMPORAL_PASS:"1",TEMPORAL_JITTER:"1"}}),this.localWeatherChannels="rgba",this.cascadeCount=It.shadow.cascadeCount,this.temporalPass=!0,this.temporalJitter=!0,this.shapeDetail=It.shapeDetail,this.turbulence=It.turbulence,this.cascadeCount=It.shadow.cascadeCount}setSize(e,t){this.uniforms.resolution.value.set(e,t)}}np([RP("LOCAL_WEATHER_CHANNELS",{validate:n=>/^[rgba]{4}$/.test(n)})],vh.prototype,"localWeatherChannels");np([mh("CASCADE_COUNT",{min:1,max:4})],vh.prototype,"cascadeCount");np([dn("TEMPORAL_PASS")],vh.prototype,"temporalPass");np([dn("TEMPORAL_JITTER")],vh.prototype,"temporalJitter");np([dn("SHAPE_DETAIL")],vh.prototype,"shapeDetail");np([dn("TURBULENCE")],vh.prototype,"turbulence");const oae=`precision highp float; -precision highp sampler2DArray; - -#define VARIANCE_9_SAMPLES 1 -#define VARIANCE_SAMPLER_ARRAY 1 - -#include "varianceClipping" - -uniform sampler2DArray inputBuffer; -uniform sampler2DArray historyBuffer; - -uniform vec2 texelSize; -uniform float varianceGamma; -uniform float temporalAlpha; - -in vec2 vUv; - -layout(location = 0) out vec4 outputColor[CASCADE_COUNT]; - -const ivec2 neighborOffsets[9] = ivec2[9]( - ivec2(-1, -1), - ivec2(-1, 0), - ivec2(-1, 1), - ivec2(0, -1), - ivec2(0, 0), - ivec2(0, 1), - ivec2(1, -1), - ivec2(1, 0), - ivec2(1, 1) -); - -vec4 getClosestFragment(const ivec3 coord) { - vec4 result = vec4(1e7, 0.0, 0.0, 0.0); - vec4 neighbor; - #pragma unroll_loop_start - for (int i = 0; i < 9; ++i) { - neighbor = texelFetchOffset( - inputBuffer, - coord + ivec3(0, 0, CASCADE_COUNT), - 0, - neighborOffsets[i] - ); - if (neighbor.r < result.r) { - result = neighbor; - } - } - #pragma unroll_loop_end - return result; -} - -void cascade(const int cascadeIndex, out vec4 outputColor) { - ivec3 coord = ivec3(gl_FragCoord.xy, cascadeIndex); - vec4 current = texelFetch(inputBuffer, coord, 0); - - vec4 depthVelocity = getClosestFragment(coord); - vec2 velocity = depthVelocity.gb * texelSize; - vec2 prevUv = vUv - velocity; - if (prevUv.x < 0.0 || prevUv.x > 1.0 || prevUv.y < 0.0 || prevUv.y > 1.0) { - outputColor = current; - return; // Rejection - } - - vec4 history = texture(historyBuffer, vec3(prevUv, float(cascadeIndex))); - vec4 clippedHistory = varianceClipping(inputBuffer, coord, current, history, varianceGamma); - outputColor = mix(clippedHistory, current, temporalAlpha); -} - -void main() { - #pragma unroll_loop_start - for (int i = 0; i < 4; ++i) { - #if UNROLLED_LOOP_INDEX < CASCADE_COUNT - cascade(UNROLLED_LOOP_INDEX, outputColor[i]); - #endif // UNROLLED_LOOP_INDEX < CASCADE_COUNT - } - #pragma unroll_loop_end -} -`,lae=`precision highp float; - -layout(location = 0) in vec3 position; - -out vec2 vUv; - -void main() { - vUv = position.xy * 0.5 + 0.5; - gl_Position = vec4(position.xy, 1.0, 1.0); -} -`;var cae=Object.defineProperty,uae=(n,e,t,i)=>{for(var a=void 0,r=n.length-1,s;r>=0;r--)(s=n[r])&&(a=s(e,t,a)||a);return a&&cae(e,t,a),a};class o9 extends hh{constructor({inputBuffer:e=null,historyBuffer:t=null}={}){super({name:"ShadowResolveMaterial",glslVersion:ro,vertexShader:lae,fragmentShader:q0(Na(oae,{varianceClipping:a9})),uniforms:{inputBuffer:new J(e),historyBuffer:new J(t),texelSize:new J(new de),varianceGamma:new J(1),temporalAlpha:new J(.01)},defines:{}}),this.cascadeCount=It.shadow.cascadeCount}setSize(e,t){this.uniforms.texelSize.value.set(1/e,1/t)}}uae([mh("CASCADE_COUNT",{min:1,max:4})],o9.prototype,"cascadeCount");function i3(n){const e=new BU(1,1,1,{depthBuffer:!1});return e.texture.type=Xn,e.texture.minFilter=Ht,e.texture.magFilter=Ht,e.texture.name=n,e}class hae extends s9{constructor({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i,...a}){super("ShadowPass",a),this.width=0,this.height=0,this.currentMaterial=new vh({parameterUniforms:e,layerUniforms:t,atmosphereUniforms:i}),this.currentPass=new FO(this.currentMaterial),this.resolveMaterial=new o9,this.resolvePass=new FO(this.resolveMaterial),this.initRenderTargets()}initialize(e,t,i){this.currentPass.initialize(e,t,i),this.resolvePass.initialize(e,t,i)}initRenderTargets(){var r,s,o;(r=this.currentRenderTarget)==null||r.dispose(),(s=this.resolveRenderTarget)==null||s.dispose(),(o=this.historyRenderTarget)==null||o.dispose();const e=i3("Shadow"),t=this.temporalPass?i3("Shadow.A"):null,i=this.temporalPass?i3("Shadow.B"):null;this.currentRenderTarget=e,this.resolveRenderTarget=t,this.historyRenderTarget=i;const a=this.resolveMaterial.uniforms;a.inputBuffer.value=e.texture,a.historyBuffer.value=(i==null?void 0:i.texture)??null}copyShadow(){const e=this.shadow,t=this.currentMaterial.uniforms;for(let i=0;i0&&(ca&&(a=d),f&&d>s&&(s=d)),a3[o]=f?1:0}i!==1/0?(n.minHeight.value=i,n.maxHeight.value=a):(ec(a===0),n.minHeight.value=0),r!==1/0?(n.shadowBottomHeight.value=r,n.shadowTopHeight.value=s):(ec(s===0),n.shadowBottomHeight.value=0),n.shadowLayerMask.value.fromArray(a3)}function mae(n,e){return{bottomRadius:new J(n.bottomRadius),topRadius:new J(n.topRadius),worldToECEFMatrix:new J(e.worldToECEFMatrix),ecefToWorldMatrix:new J(e.ecefToWorldMatrix),altitudeCorrection:new J(e.altitudeCorrection),sunDirection:new J(e.sunDirection)}}const gae=`uniform sampler2D cloudsBuffer; - -void mainImage(const vec4 inputColor, const vec2 uv, out vec4 outputColor) { - #ifdef SKIP_RENDERING - outputColor = inputColor; - #else // SKIP_RENDERING - vec4 clouds = texture(cloudsBuffer, uv); - outputColor.rgb = inputColor.rgb * (1.0 - clouds.a) + clouds.rgb; - outputColor.a = inputColor.a * (1.0 - clouds.a) + clouds.a; - #endif // SKIP_RENDERING -} -`;var vae=Object.defineProperty,_ae=(n,e,t,i)=>{for(var a=void 0,r=n.length-1,s;r>=0;r--)(s=n[r])&&(a=s(e,t,a)||a);return a&&vae(e,t,a),a};const im=new L,xae=new de,yae=new Et,Sae=["maxIterationCount","minStepSize","maxStepSize","maxRayDistance","perspectiveStepScale","minDensity","minExtinction","minTransmittance","maxIterationCountToSun","maxIterationCountToGround","minSecondaryStepSize","secondaryStepScale","maxShadowFilterRadius","maxShadowLengthIterationCount","minShadowLengthStepSize","maxShadowLengthRayDistance","hazeDensityScale","hazeExponent","hazeScatteringCoefficient","hazeAbsorptionCoefficient"],Tae=["multiScatteringOctaves","accurateSunSkyLight","accuratePhaseFunction"],Eae=["maxIterationCount","minStepSize","maxStepSize","minDensity","minExtinction","minTransmittance","opticalDepthTailScale"],Mae=["temporalJitter"],bae=["temporalPass"],Aae=["cascadeCount","mapSize","maxFar","farScale","splitMode","splitLambda"],Uo={type:"change"},l9={resolutionScale:It.resolutionScale,width:rs.AUTO_SIZE,height:rs.AUTO_SIZE};class c9 extends v0{constructor(e=new bc,t,i=j0.DEFAULT){var f,d,m,g;super("CloudsEffect",gae,{attributes:$o.DEPTH,uniforms:new Map([["cloudsBuffer",new J(null)]])}),this.camera=e,this.atmosphere=i,this.cloudLayers=o1.DEFAULT.clone(),this.correctAltitude=!0,this.localWeatherRepeat=new de().setScalar(100),this.localWeatherOffset=new de,this.shapeRepeat=new L().setScalar(3e-4),this.shapeOffset=new L,this.shapeDetailRepeat=new L().setScalar(.006),this.shapeDetailOffset=new L,this.turbulenceRepeat=new de().setScalar(20),this.worldToECEFMatrix=new ke,this.ecefToWorldMatrix=new ke,this.altitudeCorrection=new L,this.sunDirection=new L,this.localWeatherVelocity=new de,this.shapeVelocity=new L,this.shapeDetailVelocity=new L,this._atmosphereOverlay=null,this._atmosphereShadow=null,this._atmosphereShadowLength=null,this.events=new nr,this.frame=0,this.shadowCascadeCount=0,this.shadowMapSize=new de,this.onResolutionChange=()=>{this.setSize(this.resolution.baseWidth,this.resolution.baseHeight)},this.skipRendering=!0;const{resolutionScale:a,width:r,height:s,resolutionX:o=r,resolutionY:c=s}={...l9,...t};this.shadowMaps=new kie({cascadeCount:It.shadow.cascadeCount,mapSize:It.shadow.mapSize,splitLambda:.6}),this.parameterUniforms=fae({localWeatherTexture:((f=this.proceduralLocalWeather)==null?void 0:f.texture)??null,localWeatherRepeat:this.localWeatherRepeat,localWeatherOffset:this.localWeatherOffset,shapeTexture:((d=this.proceduralShape)==null?void 0:d.texture)??null,shapeRepeat:this.shapeRepeat,shapeOffset:this.shapeOffset,shapeDetailTexture:((m=this.proceduralShapeDetail)==null?void 0:m.texture)??null,shapeDetailRepeat:this.shapeDetailRepeat,shapeDetailOffset:this.shapeDetailOffset,turbulenceTexture:((g=this.proceduralTurbulence)==null?void 0:g.texture)??null,turbulenceRepeat:this.turbulenceRepeat}),this.layerUniforms=dae(),this.atmosphereUniforms=mae(i,{worldToECEFMatrix:this.worldToECEFMatrix,ecefToWorldMatrix:this.ecefToWorldMatrix,altitudeCorrection:this.altitudeCorrection,sunDirection:this.sunDirection});const h={shadow:this.shadowMaps,parameterUniforms:this.parameterUniforms,layerUniforms:this.layerUniforms,atmosphereUniforms:this.atmosphereUniforms};this.shadowPass=new hae(h),this.shadowPass.mainCamera=e,this.cloudsPass=new tae(h,i),this.cloudsPass.mainCamera=e,this.clouds=xO(yO({},this.cloudsPass.currentMaterial,Sae),this.cloudsPass.currentMaterial,Tae),this.shadow=xO(yO({},this.shadowPass.currentMaterial,Eae),this.shadowPass.currentMaterial,Mae,this.shadowPass,bae,this.shadowMaps,Aae),this.resolution=new rs(this,o,c,a),this.resolution.addEventListener("change",this.onResolutionChange)}get mainCamera(){return this.camera}set mainCamera(e){this.camera=e,this.shadowPass.mainCamera=e,this.cloudsPass.mainCamera=e}initialize(e,t,i){this.shadowPass.initialize(e,t,i),this.cloudsPass.initialize(e,t,i)}updateSharedUniforms(e){pae(this.layerUniforms,this.cloudLayers);const{parameterUniforms:t}=this;t.localWeatherOffset.value.add(xae.copy(this.localWeatherVelocity).multiplyScalar(e)),t.shapeOffset.value.add(im.copy(this.shapeVelocity).multiplyScalar(e)),t.shapeDetailOffset.value.add(im.copy(this.shapeDetailVelocity).multiplyScalar(e));const i=this.worldToECEFMatrix;this.ecefToWorldMatrix.copy(i).invert();const a=this.camera.getWorldPosition(im).applyMatrix4(this.worldToECEFMatrix),r=this.altitudeCorrection;this.correctAltitude?xA(a,this.atmosphere.bottomRadius,this.ellipsoid,r):r.setScalar(0);const s=this.ellipsoid.getSurfaceNormal(a,im),o=this.sunDirection.dot(s),c=wP(1e6,1e3,o),h=yae.setFromMatrix4(i).transpose();this.shadowMaps.update(this.camera,im.copy(this.sunDirection).applyMatrix3(h),c)}updateWeatherTextureChannels(){const e=this.cloudLayers.localWeatherChannels;this.cloudsPass.currentMaterial.localWeatherChannels=e,this.shadowPass.currentMaterial.localWeatherChannels=e}updateAtmosphereComposition(){const{shadowMaps:e,shadowPass:t,cloudsPass:i}=this,a=t.currentMaterial.uniforms,r=i.currentMaterial.uniforms,s=this._atmosphereOverlay,o=Object.assign(this._atmosphereOverlay??{},{map:i.outputBuffer});s!==o&&(this._atmosphereOverlay=o,Uo.target=this,Uo.property="atmosphereOverlay",this.events.dispatchEvent(Uo));const c=this._atmosphereShadow,h=Object.assign(this._atmosphereShadow??{},{map:t.outputBuffer,mapSize:e.mapSize,cascadeCount:e.cascadeCount,intervals:r.shadowIntervals.value,matrices:r.shadowMatrices.value,inverseMatrices:a.inverseShadowMatrices.value,far:e.far,topHeight:r.shadowTopHeight.value});c!==h&&(this._atmosphereShadow=h,Uo.target=this,Uo.property="atmosphereShadow",this.events.dispatchEvent(Uo));const f=this._atmosphereShadowLength,d=i.shadowLengthBuffer!=null?Object.assign(this._atmosphereShadowLength??{},{map:i.shadowLengthBuffer}):null;f!==d&&(this._atmosphereShadowLength=d,Uo.target=this,Uo.property="atmosphereShadowLength",this.events.dispatchEvent(Uo))}update(e,t,i=0){var o,c,h,f;const{shadowMaps:a,shadowPass:r,cloudsPass:s}=this;if(a.cascadeCount!==this.shadowCascadeCount||!a.mapSize.equals(this.shadowMapSize)){const{width:d,height:m}=a.mapSize,g=a.cascadeCount;this.shadowMapSize.set(d,m),this.shadowCascadeCount=g,r.setSize(d,m,g),s.setShadowSize(d,m,g)}(o=this.proceduralLocalWeather)==null||o.render(e,i),(c=this.proceduralShape)==null||c.render(e,i),(h=this.proceduralShapeDetail)==null||h.render(e,i),(f=this.proceduralTurbulence)==null||f.render(e,i),++this.frame,this.updateSharedUniforms(i),this.updateWeatherTextureChannels(),r.update(e,this.frame,i),s.shadowBuffer=r.outputBuffer,s.update(e,this.frame,i),this.updateAtmosphereComposition(),this.uniforms.get("cloudsBuffer").value=this.cloudsPass.outputBuffer}setSize(e,t){const{resolution:i}=this;i.setBaseSize(e,t);const{width:a,height:r}=i;this.cloudsPass.setSize(a,r)}setDepthTexture(e,t){this.shadowPass.setDepthTexture(e,t),this.cloudsPass.setDepthTexture(e,t)}set qualityPreset(e){const{clouds:t,shadow:i,...a}=Xie[e];Object.assign(this,a),Object.assign(this.clouds,t),Object.assign(this.shadow,i)}get localWeatherTexture(){return this.proceduralLocalWeather??this.parameterUniforms.localWeatherTexture.value}set localWeatherTexture(e){e instanceof Nn||e==null?(this.proceduralLocalWeather=void 0,this.parameterUniforms.localWeatherTexture.value=e):(this.proceduralLocalWeather=e,this.parameterUniforms.localWeatherTexture.value=e.texture)}get shapeTexture(){return this.proceduralShape??this.parameterUniforms.shapeTexture.value}set shapeTexture(e){e instanceof as||e==null?(this.proceduralShape=void 0,this.parameterUniforms.shapeTexture.value=e):(this.proceduralShape=e,this.parameterUniforms.shapeTexture.value=e.texture)}get shapeDetailTexture(){return this.proceduralShapeDetail??this.parameterUniforms.shapeDetailTexture.value}set shapeDetailTexture(e){e instanceof as||e==null?(this.proceduralShapeDetail=void 0,this.parameterUniforms.shapeDetailTexture.value=e):(this.proceduralShapeDetail=e,this.parameterUniforms.shapeDetailTexture.value=e.texture)}get turbulenceTexture(){return this.proceduralTurbulence??this.parameterUniforms.turbulenceTexture.value}set turbulenceTexture(e){e instanceof Nn||e==null?(this.proceduralTurbulence=void 0,this.parameterUniforms.turbulenceTexture.value=e):(this.proceduralTurbulence=e,this.parameterUniforms.turbulenceTexture.value=e.texture)}get stbnTexture(){return this.cloudsPass.currentMaterial.uniforms.stbnTexture.value}set stbnTexture(e){this.cloudsPass.currentMaterial.uniforms.stbnTexture.value=e,this.shadowPass.currentMaterial.uniforms.stbnTexture.value=e}get resolutionScale(){return this.resolution.scale}set resolutionScale(e){this.resolution.scale=e}get temporalUpscale(){return this.cloudsPass.temporalUpscale}set temporalUpscale(e){this.cloudsPass.temporalUpscale=e}get lightShafts(){return this.cloudsPass.lightShafts}set lightShafts(e){this.cloudsPass.lightShafts=e}get shapeDetail(){return this.cloudsPass.currentMaterial.shapeDetail}set shapeDetail(e){this.cloudsPass.currentMaterial.shapeDetail=e,this.shadowPass.currentMaterial.shapeDetail=e}get turbulence(){return this.cloudsPass.currentMaterial.turbulence}set turbulence(e){this.cloudsPass.currentMaterial.turbulence=e,this.shadowPass.currentMaterial.turbulence=e}get haze(){return this.cloudsPass.currentMaterial.haze}set haze(e){this.cloudsPass.currentMaterial.haze=e}get scatteringCoefficient(){return this.parameterUniforms.scatteringCoefficient.value}set scatteringCoefficient(e){this.parameterUniforms.scatteringCoefficient.value=e}get absorptionCoefficient(){return this.parameterUniforms.absorptionCoefficient.value}set absorptionCoefficient(e){this.parameterUniforms.absorptionCoefficient.value=e}get coverage(){return this.parameterUniforms.coverage.value}set coverage(e){this.parameterUniforms.coverage.value=e}get turbulenceDisplacement(){return this.parameterUniforms.turbulenceDisplacement.value}set turbulenceDisplacement(e){this.parameterUniforms.turbulenceDisplacement.value=e}get scatterAnisotropy1(){return this.cloudsPass.currentMaterial.scatterAnisotropy1}set scatterAnisotropy1(e){this.cloudsPass.currentMaterial.scatterAnisotropy1=e}get scatterAnisotropy2(){return this.cloudsPass.currentMaterial.scatterAnisotropy2}set scatterAnisotropy2(e){this.cloudsPass.currentMaterial.scatterAnisotropy2=e}get scatterAnisotropyMix(){return this.cloudsPass.currentMaterial.scatterAnisotropyMix}set scatterAnisotropyMix(e){this.cloudsPass.currentMaterial.scatterAnisotropyMix=e}get skyIrradianceScale(){return this.skyLightScale}set skyIrradianceScale(e){this.skyLightScale=e}get skyLightScale(){return this.cloudsPass.currentMaterial.uniforms.skyLightScale.value}set skyLightScale(e){this.cloudsPass.currentMaterial.uniforms.skyLightScale.value=e}get groundIrradianceScale(){return this.groundBounceScale}set groundIrradianceScale(e){this.groundBounceScale=e}get groundBounceScale(){return this.cloudsPass.currentMaterial.uniforms.groundBounceScale.value}set groundBounceScale(e){this.cloudsPass.currentMaterial.uniforms.groundBounceScale.value=e}get powderScale(){return this.cloudsPass.currentMaterial.uniforms.powderScale.value}set powderScale(e){this.cloudsPass.currentMaterial.uniforms.powderScale.value=e}get powderExponent(){return this.cloudsPass.currentMaterial.uniforms.powderExponent.value}set powderExponent(e){this.cloudsPass.currentMaterial.uniforms.powderExponent.value=e}get atmosphereOverlay(){return this._atmosphereOverlay}get atmosphereShadow(){return this._atmosphereShadow}get atmosphereShadowLength(){return this._atmosphereShadowLength}get irradianceTexture(){return this.cloudsPass.currentMaterial.irradianceTexture}set irradianceTexture(e){this.cloudsPass.currentMaterial.irradianceTexture=e}get scatteringTexture(){return this.cloudsPass.currentMaterial.scatteringTexture}set scatteringTexture(e){this.cloudsPass.currentMaterial.scatteringTexture=e}get transmittanceTexture(){return this.cloudsPass.currentMaterial.transmittanceTexture}set transmittanceTexture(e){this.cloudsPass.currentMaterial.transmittanceTexture=e}get singleMieScatteringTexture(){return this.cloudsPass.currentMaterial.singleMieScatteringTexture}set singleMieScatteringTexture(e){this.cloudsPass.currentMaterial.singleMieScatteringTexture=e}get higherOrderScatteringTexture(){return this.cloudsPass.currentMaterial.higherOrderScatteringTexture}set higherOrderScatteringTexture(e){this.cloudsPass.currentMaterial.higherOrderScatteringTexture=e}get ellipsoid(){return this.cloudsPass.currentMaterial.ellipsoid}set ellipsoid(e){this.cloudsPass.currentMaterial.ellipsoid=e}get sunAngularRadius(){return this.cloudsPass.currentMaterial.sunAngularRadius}set sunAngularRadius(e){this.cloudsPass.currentMaterial.sunAngularRadius=e}}_ae([dn("SKIP_RENDERING")],c9.prototype,"skipRendering");const wae=128,Rae=32,Ty="45a1c6c1bb9fd38b3680fd120795ff4c32df68ff",Cae=`https://media.githubusercontent.com/media/takram-design-engineering/three-geospatial/${Ty}/packages/clouds/assets/local_weather.png`,Nae=`https://media.githubusercontent.com/media/takram-design-engineering/three-geospatial/${Ty}/packages/clouds/assets/shape.bin`,Dae=`https://media.githubusercontent.com/media/takram-design-engineering/three-geospatial/${Ty}/packages/clouds/assets/shape_detail.bin`,Oae=`https://media.githubusercontent.com/media/takram-design-engineering/three-geospatial/${Ty}/packages/clouds/assets/turbulence.png`,u9=Me.createContext(null),Lae=({layers:n,disableDefault:e=!1,children:t})=>{const[i,a]=Me.useState();return Me.useLayoutEffect(()=>{n.set(e?Array(4).fill(Es.DEFAULT):o1.DEFAULT),a({layers:n,indexPool:[0,1,2,3],disableDefault:e})},[n,e]),i!=null&&Rt.jsx(u9.Provider,{value:i,children:t})};function GO(n,e){const t=Me.useMemo(()=>typeof n=="string"?new kb().load(n,i=>{i.minFilter=SU,i.magFilter=Ht,i.wrapS=Ea,i.wrapT=Ea,i.colorSpace=Da,i.needsUpdate=!0}):void 0,[n]);return Me.useEffect(()=>{if(t!=null)return()=>{t.dispose()}},[t]),(typeof n=="string"?t:n)??null}function VO(n,e){const t=Me.useMemo(()=>typeof n=="string"?new Su(as,CP,{width:e,height:e,depth:e,format:As,minFilter:Ht,magFilter:Ht,wrapS:Ea,wrapT:Ea,wrapR:Ea,colorSpace:Da}).load(n):void 0,[n,e]);return Me.useEffect(()=>{if(t!=null)return()=>{t.dispose()}},[t]),(typeof n=="string"?t:n)??null}function Iae(n){const e=Me.useMemo(()=>typeof n=="string"?new NP().load(n):void 0,[n]);return Me.useEffect(()=>{if(e!=null)return()=>{e.dispose()}},[e]),(typeof n=="string"?e:n)??null}const Uae=({ref:n,disableDefaultLayers:e=!1,localWeatherTexture:t=Cae,shapeTexture:i=Nae,shapeDetailTexture:a=Dae,turbulenceTexture:r=Oae,stbnTexture:s=aP,children:o,...c})=>{const{textures:h,transientStates:f,...d}=Me.useContext(AA),[m,g]=JP({...l9,...d,...h,...c}),x=Me.useMemo(()=>new c9,[]);Me.useEffect(()=>()=>{x.dispose()},[x]),cl(()=>{f!=null&&(x.sunDirection.copy(f.sunDirection),x.worldToECEFMatrix.copy(f.worldToECEFMatrix))}),Me.useEffect(()=>{if(f!=null)return f.overlay=x.atmosphereOverlay,f.shadow=x.atmosphereShadow,f.shadowLength=x.atmosphereShadowLength,()=>{f.overlay=null,f.shadow=null,f.shadowLength=null}},[x,f]);const T=Me.useCallback(C=>{if(f!=null)switch(C.property){case"atmosphereOverlay":f.overlay=x.atmosphereOverlay;break;case"atmosphereShadow":f.shadow=x.atmosphereShadow;break;case"atmosphereShadowLength":f.shadowLength=x.atmosphereShadowLength;break}},[x,f]);Me.useEffect(()=>(x.events.addEventListener("change",T),()=>{x.events.removeEventListener("change",T)}),[x,T]),Oi(({gl:C})=>C);const y=GO(t),v=VO(i,wae),S=VO(a,Rae),E=GO(r),b=Iae(s),{camera:D}=Me.useContext(lA);return Rt.jsxs(Rt.Fragment,{children:[Rt.jsx("primitive",{ref:n,object:x,mainCamera:D,...m,localWeatherTexture:y,shapeTexture:v,shapeDetailTexture:S,turbulenceTexture:E,stbnTexture:b,...g}),Rt.jsx(Lae,{layers:x.cloudLayers,disableDefault:e,children:o})]})},Pae=({ref:n,index:e,...t})=>{const i=Me.useContext(u9);if(i==null)throw new Error("CloudLayer can only be used within the Clouds component!");const{layers:a,indexPool:r,disableDefault:s}=i,[o,c]=Me.useState();if(Me.useLayoutEffect(()=>{if(e!=null){const h=r.indexOf(e);if(h!==-1)return r.splice(h,1),c(e),()=>{r.push(e),c(void 0)}}else{const h=r.sort((f,d)=>f-d).shift();if(h!=null)return c(h),()=>{r.push(h),c(void 0)}}},[e,a,r]),Me.useLayoutEffect(()=>{if(o==null)return;const h=a[o];return()=>{h.copy(s?Es.DEFAULT:o1.DEFAULT[o])}},[a,o,s]),Me.useEffect(()=>{o!=null&&(typeof n=="function"?n(a[o]):n!=null&&(n.current=a[o]))},[n,a,o]),o!=null){const h=a[o];h.copy(s?Es.DEFAULT:o1.DEFAULT[o]),h.set(t)}return null},M_="/pkg/atmosphere/",zae=`${M_}ai.vrm`,Bae=6378137,Hae=5*60*1e3,Fae=100,Gae=new Date("2024-06-21T12:00:00"),kO=[{name:"Clear (快晴)",coverage:.1,layers:[{channel:"r",altitude:1500,height:500,densityScale:0},{channel:"g",altitude:2500,height:800,densityScale:0},{channel:"b",altitude:7500,height:500,densityScale:.1}]},{name:"Sunny (晴れ)",coverage:.4,layers:[{channel:"r",altitude:1500,height:500,densityScale:.4},{channel:"g",altitude:2500,height:800,densityScale:0},{channel:"b",altitude:7500,height:500,densityScale:.2}]},{name:"Cloudy (曇り)",coverage:.75,layers:[{channel:"r",altitude:1500,height:500,densityScale:.6},{channel:"g",altitude:2e3,height:1e3,densityScale:.5},{channel:"b",altitude:7500,height:500,densityScale:0}]}],Gl={position:new L(0,Bae+2e3,0),quaternion:new St,speed:5e3},Qn={w:!1,a:!1,s:!1,d:!1,Shift:!1,Space:!1};typeof window<"u"&&(window.addEventListener("keydown",n=>{const e=n.key.toLowerCase();Qn.hasOwnProperty(e)&&(Qn[e]=!0),n.key==="Shift"&&(Qn.Shift=!0),n.key===" "&&(Qn.Space=!0)}),window.addEventListener("keyup",n=>{const e=n.key.toLowerCase();Qn.hasOwnProperty(e)&&(Qn[e]=!1),n.key==="Shift"&&(Qn.Shift=!1),n.key===" "&&(Qn.Space=!1)}));function Vae(){const{gl:n}=Oi(),e=Me.useRef(),t=Me.useRef(),i=Me.useRef(new Date(Gae)),[a,r]=Me.useState(kO[1]);return Me.useEffect(()=>{n.toneMapping=is,n.toneMappingExposure=10},[n]),Me.useEffect(()=>{const s=setInterval(()=>{r(o=>{const c=kO.filter(f=>f.name!==o.name),h=c[Math.floor(Math.random()*c.length)];return console.log(`[Weather] Changing to: ${h.name}`),h})},Hae);return()=>clearInterval(s)},[]),cl((s,o)=>{const c=i.current,h=o*Fae*1e3;if(c.setTime(c.getTime()+h),t.current&&t.current.updateByDate(c),e.current){const f=c.getHours()+c.getMinutes()/60+c.getSeconds()/3600,d=$t.mapLinear(f,6,18,0,Math.PI),m=-Math.cos(d),g=Math.sin(d);f<6||f>18?(e.current.position.set(0,-1,0),e.current.intensity=0):(e.current.position.set(m,g,.2),e.current.intensity=$t.lerp(.5,3,g))}}),Rt.jsxs(Rt.Fragment,{children:[Rt.jsx(W8,{makeDefault:!0,near:1,far:1e7,fov:45}),Rt.jsx(kae,{}),Rt.jsx("directionalLight",{ref:e,position:[0,1,0],intensity:3,castShadow:!0}),Rt.jsx(Rie,{ref:t,children:Rt.jsxs(hee,{multisampling:0,disableNormalPass:!1,children:[Rt.jsx(Uae,{disableDefaultLayers:!0,coverage:a.coverage,children:a.layers.map((s,o)=>Rt.jsx(Pae,{channel:s.channel,altitude:s.altitude,height:s.height,densityScale:s.densityScale,shapeAmount:.5},o))}),Rt.jsx(Nie,{sky:!0,sunLight:!0,skyLight:!0}),Rt.jsx(pee,{mode:qa.AGX})]})})]})}function kae(){return cl(n=>{n.camera.position.copy(Gl.position),n.camera.quaternion.copy(Gl.quaternion)}),null}function Wae(){const n=Me.useRef(null),e=Me.useRef(null),{camera:t}=Oi(),i=Me.useRef({}),a=Me.useRef(null),r=Wx(KN,zae,h=>{h.register(f=>new oJ(f))}),[s,o,c]=Wx(KN,[`${M_}fly.vrma`,`${M_}fly_stop.vrma`,`${M_}fly_idle.vrma`],h=>{h.register(f=>new kJ(f))});return Me.useEffect(()=>{const h=r.userData.vrm;e.current=h,ph.removeUnnecessaryJoints(h.scene),h.humanoid.resetPose(),h.scene.rotation.y=Math.PI;const f=new D6(h.scene);n.current=f;const d=(y,v)=>{var S;if((S=y.userData.vrmAnimations)!=null&&S[0]){const E=zJ(y.userData.vrmAnimations[0],h),b=f.clipAction(E);return b.name=v,b}return null},m=d(s,"fly"),g=d(o,"fly_stop"),x=d(c,"fly_idle");i.current={fly:m,fly_stop:g,fly_idle:x},g&&(g.setLoop(gb),g.clampWhenFinished=!0),x?(x.play(),a.current="fly_idle"):m&&(m.play(),a.current="fly");const T=y=>{y.action===g&&i.current.fly_idle&&(g.fadeOut(.5),i.current.fly_idle.reset().fadeIn(.5).play(),a.current="fly_idle")};return f.addEventListener("finished",T),()=>{f.removeEventListener("finished",T)}},[r,s,o,c]),cl((h,f)=>{var x,T;(x=n.current)==null||x.update(f),(T=e.current)==null||T.update(f);const d=Qn.w||Qn.s||Qn.a||Qn.d,m=i.current,g=a.current;if(m.fly&&m.fly_stop&&m.fly_idle)if(d){if(g!=="fly"){const y=m[g];y&&y.fadeOut(.5),m.fly.reset().fadeIn(.5).play(),a.current="fly"}}else g==="fly"&&(m.fly.fadeOut(.5),m.fly_stop.reset().fadeIn(.5).play(),a.current="fly_stop");if(e.current){const y=e.current.scene,v=new L(0,0,0);if(Qn.w&&(v.z-=1),Qn.s&&(v.z+=1),Qn.a&&(v.x-=1),Qn.d&&(v.x+=1),v.lengthSq()>0){v.normalize();const S=t.quaternion.clone();v.applyQuaternion(S);const E=y.position.clone().sub(v),b=new Wt;b.position.copy(y.position),b.lookAt(E),y.quaternion.slerp(b.quaternion,10*f)}}}),Rt.jsx("primitive",{object:r.scene})}function Xae(){const{camera:n}=Oi(),e=new L;new Ei(0,0,0,"YXZ");const t=Me.useRef(0),i=10,a=2;return cl((r,s)=>{Gl.quaternion.copy(n.quaternion);const o=Qn.w||Qn.s||Qn.a||Qn.d,c=Gl.speed*(Qn.Shift?2:1)*s;Qn.w&&(e.set(0,0,-1).applyQuaternion(n.quaternion),Gl.position.addScaledVector(e,c)),Qn.s&&(e.set(0,0,1).applyQuaternion(n.quaternion),Gl.position.addScaledVector(e,c)),Qn.a&&(e.set(-1,0,0).applyQuaternion(n.quaternion),Gl.position.addScaledVector(e,c)),Qn.d&&(e.set(1,0,0).applyQuaternion(n.quaternion),Gl.position.addScaledVector(e,c));const d=((o?i:0)-t.current)*a*s;t.current+=d,n.translateZ(d)}),null}function Yae(){return Rt.jsxs(v8,{gl:{alpha:!0,antialias:!0},children:[Rt.jsx(W8,{makeDefault:!0,position:[0,1.5,3],fov:30}),Rt.jsx(Xae,{}),Rt.jsx("directionalLight",{position:[-1,1,1],intensity:1.5}),Rt.jsx("ambientLight",{intensity:1}),Rt.jsx("spotLight",{position:[0,2,-2],intensity:3,color:"#ffdcb4"}),Rt.jsx(Me.Suspense,{fallback:null,children:Rt.jsx(Wae,{})}),Rt.jsx(e$,{target:[0,1.2,0],minDistance:2,maxDistance:10})]})}function qae(){return Rt.jsx(v8,{children:Rt.jsx(Vae,{})})}function jae(){const n={position:"absolute",top:0,left:0,width:"100%",height:"100%"};return Rt.jsxs("div",{style:{position:"relative",width:"100vw",height:"100vh",background:"#000"},children:[Rt.jsx("div",{style:{...n,zIndex:0},children:Rt.jsx(qae,{})}),Rt.jsx("div",{style:{...n,zIndex:1,pointerEvents:"none"},children:Rt.jsx("div",{style:{width:"100%",height:"100%",pointerEvents:"auto"},children:Rt.jsx(Yae,{})})})]})}lF.createRoot(document.getElementById("root")).render(Rt.jsx(dM.StrictMode,{children:Rt.jsx(jae,{})})); diff --git a/static/pkg/atmosphere/favicon.ico b/static/pkg/atmosphere/favicon.ico new file mode 100644 index 00000000..7f94540e Binary files /dev/null and b/static/pkg/atmosphere/favicon.ico differ diff --git a/static/pkg/atmosphere/index.html b/static/pkg/atmosphere/index.html index 74780bd3..1e42c214 100644 --- a/static/pkg/atmosphere/index.html +++ b/static/pkg/atmosphere/index.html @@ -3,11 +3,12 @@ - VRM Animation Preview + + VRM Animation Preview - +