three-render-objects 1.41.0 → 1.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- // Version 1.41.0 three-render-objects - https://github.com/vasturiano/three-render-objects
2
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("three")):"function"==typeof define&&define.amd?define(["three"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).ThreeRenderObjects=t(e.THREE)}(this,function(e){"use strict";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function s(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function i(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],h=!0,u=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);h=!0);}catch(e){u=!0,r=e}finally{try{if(!h&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||n(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e){return function(e){if(Array.isArray(e))return t(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||n(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(e,s){if(e){if("string"==typeof e)return t(e,s);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(e,s):void 0}}!function(e,t){void 0===t&&(t={});var s=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===s&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".scene-nav-info {\n position: absolute;\n bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n font-family: sans-serif;\n pointer-events: none;\n user-select: none;\n}\n\n.scene-container canvas:focus {\n outline: none;\n}");const a="183",o=0,h=1,u=2,l=100,c=101,d=102,p=200,m=201,g=202,f=203,y=204,b=205,_=206,x=207,v=208,T=209,S=210,w=0,M=1,N=2,E=3,A=4,C=5,R=6,P=7,B=301,F=302,D=1e3,I=1001,L=1002,O=1003,U=1004,k=1005,z=1006,V=1007,G=1008,j=1009,$=1010,W=1011,H=1012,q=1013,X=1014,Y=1015,K=1016,Q=1017,Z=1018,J=1020,ee=35902,te=35899,se=1022,ie=1023,re=1026,ne=1027,ae=1028,oe=1029,he=1030,ue=1031,le=1033,ce=33776,de=33777,pe=33778,me=33779,ge=35840,fe=35841,ye=35842,be=35843,_e=36196,xe=37492,ve=37496,Te=37488,Se=37489,we=37490,Me=37491,Ne=37808,Ee=37809,Ae=37810,Ce=37811,Re=37812,Pe=37813,Be=37814,Fe=37815,De=37816,Ie=37817,Le=37818,Oe=37819,Ue=37820,ke=37821,ze=36492,Ve=36283,Ge=36284,je=36285,$e=36286,We="",He="srgb",qe="srgb-linear",Xe="linear",Ye="srgb",Ke=7680,Qe=512,Ze=513,Je=514,et=515,tt=516,st=517,it=518,rt=519,nt=35044,at=35048,ot=2e3,ht=2001,ut="compute",lt="render",ct="depthTextureCompare";function dt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function pt(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const mt={};function gt(...e){const t="THREE."+e.shift();console.log(t,...e)}function ft(e){const t=e[0];if("string"==typeof t&&t.startsWith("TSL:")){const t=e[1];t&&t.isStackTrace?e[0]+=" "+t.getLocation():e[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return e}function yt(...e){const t="THREE."+(e=ft(e)).shift();{const s=e[0];s&&s.isStackTrace?console.warn(s.getError(t)):console.warn(t,...e)}}function bt(...e){const t="THREE."+(e=ft(e)).shift();{const s=e[0];s&&s.isStackTrace?console.error(s.getError(t)):console.error(t,...e)}}function _t(...e){const t=e.join(" ");t in mt||(mt[t]=!0,yt(...e))}const xt={[w]:1,[N]:6,[A]:7,[E]:5,[M]:0,[R]:2,[P]:4,[C]:3};class vt{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const s=this._listeners;void 0===s[e]&&(s[e]=[]),-1===s[e].indexOf(t)&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return void 0!==s&&(void 0!==s[e]&&-1!==s[e].indexOf(t))}removeEventListener(e,t){const s=this._listeners;if(void 0===s)return;const i=s[e];if(void 0!==i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}dispatchEvent(e){const t=this._listeners;if(void 0===t)return;const s=t[e.type];if(void 0!==s){e.target=this;const t=s.slice(0);for(let s=0,i=t.length;s<i;s++)t[s].call(this,e);e.target=null}}}const Tt=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let St=1234567;const wt=Math.PI/180,Mt=180/Math.PI;function Nt(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(Tt[255&e]+Tt[e>>8&255]+Tt[e>>16&255]+Tt[e>>24&255]+"-"+Tt[255&t]+Tt[t>>8&255]+"-"+Tt[t>>16&15|64]+Tt[t>>24&255]+"-"+Tt[63&s|128]+Tt[s>>8&255]+"-"+Tt[s>>16&255]+Tt[s>>24&255]+Tt[255&i]+Tt[i>>8&255]+Tt[i>>16&255]+Tt[i>>24&255]).toLowerCase()}function Et(e,t,s){return Math.max(t,Math.min(s,e))}function At(e,t){return(e%t+t)%t}function Ct(e,t,s){return(1-s)*e+s*t}function Rt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function Pt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const Bt={DEG2RAD:wt,RAD2DEG:Mt,generateUUID:Nt,clamp:Et,euclideanModulo:At,mapLinear:function(e,t,s,i,r){return i+(e-t)*(r-i)/(s-t)},inverseLerp:function(e,t,s){return e!==t?(s-e)/(t-e):0},lerp:Ct,damp:function(e,t,s,i){return Ct(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(At(e,2*t)-t)},smoothstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*(3-2*e)},smootherstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(St=e);let t=St+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*wt},radToDeg:function(e){return e*Mt},isPowerOfTwo:function(e){return!(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,s,i,r){const n=Math.cos,a=Math.sin,o=n(s/2),h=a(s/2),u=n((t+i)/2),l=a((t+i)/2),c=n((t-i)/2),d=a((t-i)/2),p=n((i-t)/2),m=a((i-t)/2);switch(r){case"XYX":e.set(o*l,h*c,h*d,o*u);break;case"YZY":e.set(h*d,o*l,h*c,o*u);break;case"ZXZ":e.set(h*c,h*d,o*l,o*u);break;case"XZX":e.set(o*l,h*m,h*p,o*u);break;case"YXY":e.set(h*p,o*l,h*m,o*u);break;case"ZYZ":e.set(h*m,h*p,o*l,o*u);break;default:yt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Pt,denormalize:Rt};class Ft{constructor(e=0,t=0){Ft.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,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Et(this.x,e.x,t.x),this.y=Et(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Et(this.x,e,t),this.y=Et(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Et(s,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(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Et(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,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 s=Math.cos(t),i=Math.sin(t),r=this.x-e.x,n=this.y-e.y;return this.x=r*s-n*i+e.x,this.y=r*i+n*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Dt{constructor(e=0,t=0,s=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=s,this._w=i}static slerpFlat(e,t,s,i,r,n,a){let o=s[i+0],h=s[i+1],u=s[i+2],l=s[i+3],c=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(l!==m||o!==c||h!==d||u!==p){let e=o*c+h*d+u*p+l*m;e<0&&(c=-c,d=-d,p=-p,m=-m,e=-e);let t=1-a;if(e<.9995){const s=Math.acos(e),i=Math.sin(s);t=Math.sin(t*s)/i,o=o*t+c*(a=Math.sin(a*s)/i),h=h*t+d*a,u=u*t+p*a,l=l*t+m*a}else{o=o*t+c*a,h=h*t+d*a,u=u*t+p*a,l=l*t+m*a;const e=1/Math.sqrt(o*o+h*h+u*u+l*l);o*=e,h*=e,u*=e,l*=e}}e[t]=o,e[t+1]=h,e[t+2]=u,e[t+3]=l}static multiplyQuaternionsFlat(e,t,s,i,r,n){const a=s[i],o=s[i+1],h=s[i+2],u=s[i+3],l=r[n],c=r[n+1],d=r[n+2],p=r[n+3];return e[t]=a*p+u*l+o*d-h*c,e[t+1]=o*p+u*c+h*l-a*d,e[t+2]=h*p+u*d+a*c-o*l,e[t+3]=u*p-a*l-o*c-h*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,i=e._y,r=e._z,n=e._order,a=Math.cos,o=Math.sin,h=a(s/2),u=a(i/2),l=a(r/2),c=o(s/2),d=o(i/2),p=o(r/2);switch(n){case"XYZ":this._x=c*u*l+h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l-c*d*p;break;case"YXZ":this._x=c*u*l+h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l+c*d*p;break;case"ZXY":this._x=c*u*l-h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l-c*d*p;break;case"ZYX":this._x=c*u*l-h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l+c*d*p;break;case"YZX":this._x=c*u*l+h*d*p,this._y=h*d*l+c*u*p,this._z=h*u*p-c*d*l,this._w=h*u*l-c*d*p;break;case"XZY":this._x=c*u*l-h*d*p,this._y=h*d*l-c*u*p,this._z=h*u*p+c*d*l,this._w=h*u*l+c*d*p;break;default:yt("Quaternion: .setFromEuler() encountered an unknown order: "+n)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],r=t[8],n=t[1],a=t[5],o=t[9],h=t[2],u=t[6],l=t[10],c=s+a+l;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(u-o)*e,this._y=(r-h)*e,this._z=(n-i)*e}else if(s>a&&s>l){const e=2*Math.sqrt(1+s-a-l);this._w=(u-o)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+h)/e}else if(a>l){const e=2*Math.sqrt(1+a-s-l);this._w=(r-h)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(o+u)/e}else{const e=2*Math.sqrt(1+l-s-a);this._w=(n-i)/e,this._x=(r+h)/e,this._y=(o+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return s<1e-8?(s=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*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=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Et(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(0===s)return this;const i=Math.min(1,t/s);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(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 s=e._x,i=e._y,r=e._z,n=e._w,a=t._x,o=t._y,h=t._z,u=t._w;return this._x=s*u+n*a+i*h-r*o,this._y=i*u+n*o+r*a-s*h,this._z=r*u+n*h+s*o-i*a,this._w=n*u-s*a-i*o-r*h,this._onChangeCallback(),this}slerp(e,t){let s=e._x,i=e._y,r=e._z,n=e._w,a=this.dot(e);a<0&&(s=-s,i=-i,r=-r,n=-n,a=-a);let o=1-t;if(a<.9995){const e=Math.acos(a),h=Math.sin(e);o=Math.sin(o*e)/h,t=Math.sin(t*e)/h,this._x=this._x*o+s*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+n*t,this._onChangeCallback()}else this._x=this._x*o+s*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+n*t,this.normalize();return this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),r=Math.sqrt(s);return this.set(i*Math.sin(e),i*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 It{constructor(e=0,t=0,s=0){It.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return void 0===s&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,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(Ot.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ot.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*s+r[6]*i,this.y=r[1]*t+r[4]*s+r[7]*i,this.z=r[2]*t+r[5]*s+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=e.elements,n=1/(r[3]*t+r[7]*s+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*s+r[8]*i+r[12])*n,this.y=(r[1]*t+r[5]*s+r[9]*i+r[13])*n,this.z=(r[2]*t+r[6]*s+r[10]*i+r[14])*n,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,r=e.x,n=e.y,a=e.z,o=e.w,h=2*(n*i-a*s),u=2*(a*t-r*i),l=2*(r*s-n*t);return this.x=t+o*h+n*l-a*u,this.y=s+o*u+a*h-r*l,this.z=i+o*l+r*u-n*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,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i,this.y=r[1]*t+r[5]*s+r[9]*i,this.z=r[2]*t+r[6]*s+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Et(this.x,e.x,t.x),this.y=Et(this.y,e.y,t.y),this.z=Et(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Et(this.x,e,t),this.y=Et(this.y,e,t),this.z=Et(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Et(s,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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,r=e.z,n=t.x,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*n-s*o,this.z=s*a-i*n,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return Lt.copy(this).projectOnVector(e),this.sub(Lt)}reflect(e){return this.sub(Lt.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Et(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,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(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Lt=new It,Ot=new Dt;class Ut{constructor(e,t,s,i,r,n,a,o,h){Ut.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,a,o,h)}set(e,t,s,i,r,n,a,o,h){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=t,u[4]=r,u[5]=o,u[6]=s,u[7]=n,u[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.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 s=e.elements,i=t.elements,r=this.elements,n=s[0],a=s[3],o=s[6],h=s[1],u=s[4],l=s[7],c=s[2],d=s[5],p=s[8],m=i[0],g=i[3],f=i[6],y=i[1],b=i[4],_=i[7],x=i[2],v=i[5],T=i[8];return r[0]=n*m+a*y+o*x,r[3]=n*g+a*b+o*v,r[6]=n*f+a*_+o*T,r[1]=h*m+u*y+l*x,r[4]=h*g+u*b+l*v,r[7]=h*f+u*_+l*T,r[2]=c*m+d*y+p*x,r[5]=c*g+d*b+p*v,r[8]=c*f+d*_+p*T,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],s=e[1],i=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],u=e[8];return t*n*u-t*a*h-s*r*u+s*a*o+i*r*h-i*n*o}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],u=e[8],l=u*n-a*h,c=a*o-u*r,d=h*r-n*o,p=t*l+s*c+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=l*m,e[1]=(i*h-u*s)*m,e[2]=(a*s-i*n)*m,e[3]=c*m,e[4]=(u*t-i*o)*m,e[5]=(i*r-a*t)*m,e[6]=d*m,e[7]=(s*o-h*t)*m,e[8]=(n*t-s*r)*m,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,s,i,r,n,a){const o=Math.cos(r),h=Math.sin(r);return this.set(s*o,s*h,-s*(o*n+h*a)+n+e,-i*h,i*o,-i*(-h*n+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(kt.makeScale(e,t)),this}rotate(e){return this.premultiply(kt.makeRotation(-e)),this}translate(e,t){return this.premultiply(kt.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),s=Math.sin(e);return this.set(t,-s,0,s,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,s=e.elements;for(let e=0;e<9;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const kt=new Ut,zt=(new Ut).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Vt=(new Ut).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Gt(){const e={enabled:!0,workingColorSpace:qe,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Ye&&(e.r=$t(e.r),e.g=$t(e.g),e.b=$t(e.b)),this.spaces[t].primaries!==this.spaces[s].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===Ye&&(e.r=Wt(e.r),e.g=Wt(e.g),e.b=Wt(e.b)),e):e},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===We?Xe:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,s){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,s){return _t("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,s)},toWorkingColorSpace:function(t,s){return _t("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(t,s)}},t=[.64,.33,.3,.6,.15,.06],s=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[qe]:{primaries:t,whitePoint:i,transfer:Xe,toXYZ:zt,fromXYZ:Vt,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:He},outputColorSpaceConfig:{drawingBufferColorSpace:He}},[He]:{primaries:t,whitePoint:i,transfer:Ye,toXYZ:zt,fromXYZ:Vt,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:He}}}),e}const jt=Gt();function $t(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function Wt(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Ht;class qt{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let s;if(e instanceof HTMLCanvasElement)s=e;else{void 0===Ht&&(Ht=pt("canvas")),Ht.width=e.width,Ht.height=e.height;const t=Ht.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),s=Ht}return s.toDataURL(t)}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=pt("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e<r.length;e++)r[e]=255*$t(r[e]/255);return s.putImageData(i,0,0),t}if(e.data){const t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(255*$t(t[e]/255)):t[e]=$t(t[e]);return{data:t,width:e.width,height:e.height}}return yt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Xt=0;class Yt{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Xt++}),this.uuid=Nt(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):null!==t?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){!0===e&&this.version++}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.images[this.uuid])return e.images[this.uuid];const s={uuid:this.uuid,url:""},i=this.data;if(null!==i){let e;if(Array.isArray(i)){e=[];for(let t=0,s=i.length;t<s;t++)i[t].isDataTexture?e.push(Kt(i[t].image)):e.push(Kt(i[t]))}else e=Kt(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function Kt(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?qt.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(yt("Texture: Unable to serialize Texture."),{})}let Qt=0;const Zt=new It;class Jt extends vt{constructor(e=Jt.DEFAULT_IMAGE,t=Jt.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,a=1023,o=1009,h=Jt.DEFAULT_ANISOTROPY,u=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Qt++}),this.uuid=Nt(),this.name="",this.source=new Yt(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=s,this.wrapT=i,this.magFilter=r,this.minFilter=n,this.anisotropy=h,this.format=a,this.internalFormat=null,this.type=o,this.offset=new Ft(0,0),this.repeat=new Ft(1,1),this.center=new Ft(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ut,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Zt).x}get height(){return this.source.getSize(Zt).y}get depth(){return this.source.getSize(Zt).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 s=e[t];if(void 0===s){yt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&s&&i.isVector2&&s.isVector2||i&&s&&i.isVector3&&s.isVector3||i&&s&&i.isMatrix3&&s.isMatrix3?i.copy(s):this[t]=s:yt(`Texture.setValues(): property '${t}' does not exist.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.textures[this.uuid])return e.textures[this.uuid];const s={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(300!==this.mapping)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case D:e.x=e.x-Math.floor(e.x);break;case I:e.x=e.x<0?0:1;break;case L:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case D:e.y=e.y-Math.floor(e.y);break;case I:e.y=e.y<0?0:1;break;case L:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}Jt.DEFAULT_IMAGE=null,Jt.DEFAULT_MAPPING=300,Jt.DEFAULT_ANISOTROPY=1;class es{constructor(e=0,t=0,s=0,i=1){es.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?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,s=this.y,i=this.z,r=this.w,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i+n[12]*r,this.y=n[1]*t+n[5]*s+n[9]*i+n[13]*r,this.z=n[2]*t+n[6]*s+n[10]*i+n[14]*r,this.w=n[3]*t+n[7]*s+n[11]*i+n[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,s,i,r;const n=.01,a=.1,o=e.elements,h=o[0],u=o[4],l=o[8],c=o[1],d=o[5],p=o[9],m=o[2],g=o[6],f=o[10];if(Math.abs(u-c)<n&&Math.abs(l-m)<n&&Math.abs(p-g)<n){if(Math.abs(u+c)<a&&Math.abs(l+m)<a&&Math.abs(p+g)<a&&Math.abs(h+d+f-3)<a)return this.set(1,0,0,0),this;t=Math.PI;const e=(h+1)/2,o=(d+1)/2,y=(f+1)/2,b=(u+c)/4,_=(l+m)/4,x=(p+g)/4;return e>o&&e>y?e<n?(s=0,i=.707106781,r=.707106781):(s=Math.sqrt(e),i=b/s,r=_/s):o>y?o<n?(s=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),s=b/i,r=x/i):y<n?(s=.707106781,i=.707106781,r=0):(r=Math.sqrt(y),s=_/r,i=x/r),this.set(s,i,r,t),this}let y=Math.sqrt((g-p)*(g-p)+(l-m)*(l-m)+(c-u)*(c-u));return Math.abs(y)<.001&&(y=1),this.x=(g-p)/y,this.y=(l-m)/y,this.z=(c-u)/y,this.w=Math.acos((h+d+f-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=Et(this.x,e.x,t.x),this.y=Et(this.y,e.y,t.y),this.z=Et(this.z,e.z,t.z),this.w=Et(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Et(this.x,e,t),this.y=Et(this.y,e,t),this.z=Et(this.z,e,t),this.w=Et(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Et(s,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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this.w=e.w+(t.w-e.w)*s,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,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 ts extends vt{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:z,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},s),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=s.depth,this.scissor=new es(0,0,e,t),this.scissorTest=!1,this.viewport=new es(0,0,e,t),this.textures=[];const i={width:e,height:t,depth:s.depth},r=new Jt(i),n=s.count;for(let e=0;e<n;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(s),this.depthBuffer=s.depthBuffer,this.stencilBuffer=s.stencilBuffer,this.resolveDepthBuffer=s.resolveDepthBuffer,this.resolveStencilBuffer=s.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=s.depthTexture,this.samples=s.samples,this.multiview=s.multiview}_setTextureOptions(e={}){const t={minFilter:z,generateMipmaps:!1,flipY:!1,internalFormat:null};void 0!==e.mapping&&(t.mapping=e.mapping),void 0!==e.wrapS&&(t.wrapS=e.wrapS),void 0!==e.wrapT&&(t.wrapT=e.wrapT),void 0!==e.wrapR&&(t.wrapR=e.wrapR),void 0!==e.magFilter&&(t.magFilter=e.magFilter),void 0!==e.minFilter&&(t.minFilter=e.minFilter),void 0!==e.format&&(t.format=e.format),void 0!==e.type&&(t.type=e.type),void 0!==e.anisotropy&&(t.anisotropy=e.anisotropy),void 0!==e.colorSpace&&(t.colorSpace=e.colorSpace),void 0!==e.flipY&&(t.flipY=e.flipY),void 0!==e.generateMipmaps&&(t.generateMipmaps=e.generateMipmaps),void 0!==e.internalFormat&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++){this.textures[e].setValues(t)}}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){null!==this._depthTexture&&(this._depthTexture.renderTarget=null),null!==e&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,s=1){if(this.width!==e||this.height!==t||this.depth!==s){this.width=e,this.height=t,this.depth=s;for(let i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=s,!0!==this.textures[i].isData3DTexture&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return(new this.constructor).copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,s=e.textures.length;t<s;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new Yt(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,null!==e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ss extends Jt{constructor(e=null,t=1,s=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:s,depth:i},this.magFilter=O,this.minFilter=O,this.wrapR=I,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class is{constructor(e,t,s,i,r,n,a,o,h,u,l,c,d,p,m,g){is.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,a,o,h,u,l,c,d,p,m,g)}set(e,t,s,i,r,n,a,o,h,u,l,c,d,p,m,g){const f=this.elements;return f[0]=e,f[4]=t,f[8]=s,f[12]=i,f[1]=r,f[5]=n,f[9]=a,f[13]=o,f[2]=h,f[6]=u,f[10]=l,f[14]=c,f[3]=d,f[7]=p,f[11]=m,f[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new is).fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[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,s){return 0===this.determinant()?(e.set(1,0,0),t.set(0,1,0),s.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this)}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){if(0===e.determinant())return this.identity();const t=this.elements,s=e.elements,i=1/rs.setFromMatrixColumn(e,0).length(),r=1/rs.setFromMatrixColumn(e,1).length(),n=1/rs.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*r,t[5]=s[5]*r,t[6]=s[6]*r,t[7]=0,t[8]=s[8]*n,t[9]=s[9]*n,t[10]=s[10]*n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,r=e.z,n=Math.cos(s),a=Math.sin(s),o=Math.cos(i),h=Math.sin(i),u=Math.cos(r),l=Math.sin(r);if("XYZ"===e.order){const e=n*u,s=n*l,i=a*u,r=a*l;t[0]=o*u,t[4]=-o*l,t[8]=h,t[1]=s+i*h,t[5]=e-r*h,t[9]=-a*o,t[2]=r-e*h,t[6]=i+s*h,t[10]=n*o}else if("YXZ"===e.order){const e=o*u,s=o*l,i=h*u,r=h*l;t[0]=e+r*a,t[4]=i*a-s,t[8]=n*h,t[1]=n*l,t[5]=n*u,t[9]=-a,t[2]=s*a-i,t[6]=r+e*a,t[10]=n*o}else if("ZXY"===e.order){const e=o*u,s=o*l,i=h*u,r=h*l;t[0]=e-r*a,t[4]=-n*l,t[8]=i+s*a,t[1]=s+i*a,t[5]=n*u,t[9]=r-e*a,t[2]=-n*h,t[6]=a,t[10]=n*o}else if("ZYX"===e.order){const e=n*u,s=n*l,i=a*u,r=a*l;t[0]=o*u,t[4]=i*h-s,t[8]=e*h+r,t[1]=o*l,t[5]=r*h+e,t[9]=s*h-i,t[2]=-h,t[6]=a*o,t[10]=n*o}else if("YZX"===e.order){const e=n*o,s=n*h,i=a*o,r=a*h;t[0]=o*u,t[4]=r-e*l,t[8]=i*l+s,t[1]=l,t[5]=n*u,t[9]=-a*u,t[2]=-h*u,t[6]=s*l+i,t[10]=e-r*l}else if("XZY"===e.order){const e=n*o,s=n*h,i=a*o,r=a*h;t[0]=o*u,t[4]=-l,t[8]=h*u,t[1]=e*l+r,t[5]=n*u,t[9]=s*l-i,t[2]=i*l-s,t[6]=a*u,t[10]=r*l+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(as,e,os)}lookAt(e,t,s){const i=this.elements;return ls.subVectors(e,t),0===ls.lengthSq()&&(ls.z=1),ls.normalize(),hs.crossVectors(s,ls),0===hs.lengthSq()&&(1===Math.abs(s.z)?ls.x+=1e-4:ls.z+=1e-4,ls.normalize(),hs.crossVectors(s,ls)),hs.normalize(),us.crossVectors(ls,hs),i[0]=hs.x,i[4]=us.x,i[8]=ls.x,i[1]=hs.y,i[5]=us.y,i[9]=ls.y,i[2]=hs.z,i[6]=us.z,i[10]=ls.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],a=s[4],o=s[8],h=s[12],u=s[1],l=s[5],c=s[9],d=s[13],p=s[2],m=s[6],g=s[10],f=s[14],y=s[3],b=s[7],_=s[11],x=s[15],v=i[0],T=i[4],S=i[8],w=i[12],M=i[1],N=i[5],E=i[9],A=i[13],C=i[2],R=i[6],P=i[10],B=i[14],F=i[3],D=i[7],I=i[11],L=i[15];return r[0]=n*v+a*M+o*C+h*F,r[4]=n*T+a*N+o*R+h*D,r[8]=n*S+a*E+o*P+h*I,r[12]=n*w+a*A+o*B+h*L,r[1]=u*v+l*M+c*C+d*F,r[5]=u*T+l*N+c*R+d*D,r[9]=u*S+l*E+c*P+d*I,r[13]=u*w+l*A+c*B+d*L,r[2]=p*v+m*M+g*C+f*F,r[6]=p*T+m*N+g*R+f*D,r[10]=p*S+m*E+g*P+f*I,r[14]=p*w+m*A+g*B+f*L,r[3]=y*v+b*M+_*C+x*F,r[7]=y*T+b*N+_*R+x*D,r[11]=y*S+b*E+_*P+x*I,r[15]=y*w+b*A+_*B+x*L,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],s=e[4],i=e[8],r=e[12],n=e[1],a=e[5],o=e[9],h=e[13],u=e[2],l=e[6],c=e[10],d=e[14],p=e[3],m=e[7],g=e[11],f=e[15],y=o*d-h*c,b=a*d-h*l,_=a*c-o*l,x=n*d-h*u,v=n*c-o*u,T=n*l-a*u;return t*(m*y-g*b+f*_)-s*(p*y-g*x+f*v)+i*(p*b-m*x+f*T)-r*(p*_-m*v+g*T)}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,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],u=e[8],l=e[9],c=e[10],d=e[11],p=e[12],m=e[13],g=e[14],f=e[15],y=t*a-s*n,b=t*o-i*n,_=t*h-r*n,x=s*o-i*a,v=s*h-r*a,T=i*h-r*o,S=u*m-l*p,w=u*g-c*p,M=u*f-d*p,N=l*g-c*m,E=l*f-d*m,A=c*f-d*g,C=y*A-b*E+_*N+x*M-v*w+T*S;if(0===C)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const R=1/C;return e[0]=(a*A-o*E+h*N)*R,e[1]=(i*E-s*A-r*N)*R,e[2]=(m*T-g*v+f*x)*R,e[3]=(c*v-l*T-d*x)*R,e[4]=(o*M-n*A-h*w)*R,e[5]=(t*A-i*M+r*w)*R,e[6]=(g*_-p*T-f*b)*R,e[7]=(u*T-c*_+d*b)*R,e[8]=(n*E-a*M+h*S)*R,e[9]=(s*M-t*E-r*S)*R,e[10]=(p*v-m*_+f*y)*R,e[11]=(l*_-u*v-d*y)*R,e[12]=(a*w-n*N-o*S)*R,e[13]=(t*N-s*w+i*S)*R,e[14]=(m*b-p*x-g*y)*R,e[15]=(u*x-l*b+c*y)*R,this}scale(e){const t=this.elements,s=e.x,i=e.y,r=e.z;return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){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,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),r=1-s,n=e.x,a=e.y,o=e.z,h=r*n,u=r*a;return this.set(h*n+s,h*a-i*o,h*o+i*a,0,h*a+i*o,u*a+s,u*o-i*n,0,h*o-i*a,u*o+i*n,r*o*o+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,r,n){return this.set(1,s,r,0,e,1,n,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,r=t._x,n=t._y,a=t._z,o=t._w,h=r+r,u=n+n,l=a+a,c=r*h,d=r*u,p=r*l,m=n*u,g=n*l,f=a*l,y=o*h,b=o*u,_=o*l,x=s.x,v=s.y,T=s.z;return i[0]=(1-(m+f))*x,i[1]=(d+_)*x,i[2]=(p-b)*x,i[3]=0,i[4]=(d-_)*v,i[5]=(1-(c+f))*v,i[6]=(g+y)*v,i[7]=0,i[8]=(p+b)*T,i[9]=(g-y)*T,i[10]=(1-(c+m))*T,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;e.x=i[12],e.y=i[13],e.z=i[14];const r=this.determinant();if(0===r)return s.set(1,1,1),t.identity(),this;let n=rs.set(i[0],i[1],i[2]).length();const a=rs.set(i[4],i[5],i[6]).length(),o=rs.set(i[8],i[9],i[10]).length();r<0&&(n=-n),ns.copy(this);const h=1/n,u=1/a,l=1/o;return ns.elements[0]*=h,ns.elements[1]*=h,ns.elements[2]*=h,ns.elements[4]*=u,ns.elements[5]*=u,ns.elements[6]*=u,ns.elements[8]*=l,ns.elements[9]*=l,ns.elements[10]*=l,t.setFromRotationMatrix(ns),s.x=n,s.y=a,s.z=o,this}makePerspective(e,t,s,i,r,n,a=2e3,o=!1){const h=this.elements,u=2*r/(t-e),l=2*r/(s-i),c=(t+e)/(t-e),d=(s+i)/(s-i);let p,m;if(o)p=r/(n-r),m=n*r/(n-r);else if(a===ot)p=-(n+r)/(n-r),m=-2*n*r/(n-r);else{if(a!==ht)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);p=-n/(n-r),m=-n*r/(n-r)}return h[0]=u,h[4]=0,h[8]=c,h[12]=0,h[1]=0,h[5]=l,h[9]=d,h[13]=0,h[2]=0,h[6]=0,h[10]=p,h[14]=m,h[3]=0,h[7]=0,h[11]=-1,h[15]=0,this}makeOrthographic(e,t,s,i,r,n,a=2e3,o=!1){const h=this.elements,u=2/(t-e),l=2/(s-i),c=-(t+e)/(t-e),d=-(s+i)/(s-i);let p,m;if(o)p=1/(n-r),m=n/(n-r);else if(a===ot)p=-2/(n-r),m=-(n+r)/(n-r);else{if(a!==ht)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=-1/(n-r),m=-r/(n-r)}return h[0]=u,h[4]=0,h[8]=0,h[12]=c,h[1]=0,h[5]=l,h[9]=0,h[13]=d,h[2]=0,h[6]=0,h[10]=p,h[14]=m,h[3]=0,h[7]=0,h[11]=0,h[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<16;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const rs=new It,ns=new is,as=new It(0,0,0),os=new It(1,1,1),hs=new It,us=new It,ls=new It,cs=new is,ds=new Dt;class ps{constructor(e=0,t=0,s=0,i=ps.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const i=e.elements,r=i[0],n=i[4],a=i[8],o=i[1],h=i[5],u=i[9],l=i[2],c=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Et(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(c,h),this._z=0);break;case"YXZ":this._x=Math.asin(-Et(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,h)):(this._y=Math.atan2(-l,r),this._z=0);break;case"ZXY":this._x=Math.asin(Et(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(-l,d),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Et(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(Et(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,h),this._y=Math.atan2(-l,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Et(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,h),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-u,d),this._y=0);break;default:yt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return cs.makeRotationFromQuaternion(e),this.setFromRotationMatrix(cs,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ds.setFromEuler(this),this.setFromQuaternion(ds,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],void 0!==e[3]&&(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}}ps.DEFAULT_ORDER="XYZ";class ms{constructor(){this.mask=1}set(e){this.mask=1<<e>>>0}enable(e){this.mask|=1<<e}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e}disable(e){this.mask&=~(1<<e)}disableAll(){this.mask=0}test(e){return 0!==(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let gs=0;const fs=new It,ys=new Dt,bs=new is,_s=new It,xs=new It,vs=new It,Ts=new Dt,Ss=new It(1,0,0),ws=new It(0,1,0),Ms=new It(0,0,1),Ns={type:"added"},Es={type:"removed"},As={type:"childadded",child:null},Cs={type:"childremoved",child:null};class Rs extends vt{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:gs++}),this.uuid=Nt(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Rs.DEFAULT_UP.clone();const e=new It,t=new ps,s=new Dt,i=new It(1,1,1);t._onChange(function(){s.setFromEuler(t,!1)}),s._onChange(function(){t.setFromQuaternion(s,void 0,!1)}),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:s},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new is},normalMatrix:{value:new Ut}}),this.matrix=new is,this.matrixWorld=new is,this.matrixAutoUpdate=Rs.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Rs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new ms,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return ys.setFromAxisAngle(e,t),this.quaternion.multiply(ys),this}rotateOnWorldAxis(e,t){return ys.setFromAxisAngle(e,t),this.quaternion.premultiply(ys),this}rotateX(e){return this.rotateOnAxis(Ss,e)}rotateY(e){return this.rotateOnAxis(ws,e)}rotateZ(e){return this.rotateOnAxis(Ms,e)}translateOnAxis(e,t){return fs.copy(e).applyQuaternion(this.quaternion),this.position.add(fs.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Ss,e)}translateY(e){return this.translateOnAxis(ws,e)}translateZ(e){return this.translateOnAxis(Ms,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(bs.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?_s.copy(e):_s.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),xs.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?bs.lookAt(xs,_s,this.up):bs.lookAt(_s,xs,this.up),this.quaternion.setFromRotationMatrix(bs),i&&(bs.extractRotation(i.matrixWorld),ys.setFromRotationMatrix(bs),this.quaternion.premultiply(ys.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(bt("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Ns),As.child=e,this.dispatchEvent(As),As.child=null):bt("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}const t=this.children.indexOf(e);return-1!==t&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(Es),Cs.child=e,this.dispatchEvent(Cs),Cs.child=null),this}removeFromParent(){const e=this.parent;return null!==e&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),bs.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),bs.multiply(e.parent.matrixWorld)),e.applyMatrix4(bs),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Ns),As.child=e,this.dispatchEvent(As),As.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let s=0,i=this.children.length;s<i;s++){const i=this.children[s].getObjectByProperty(e,t);if(void 0!==i)return i}}getObjectsByProperty(e,t,s=[]){this[e]===t&&s.push(this);const i=this.children;for(let r=0,n=i.length;r<n;r++)i[r].getObjectsByProperty(e,t,s);return s}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(xs,e,vs),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(xs,Ts,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverse(e)}traverseVisible(e){if(!1===this.visible)return;e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverseVisible(e)}traverseAncestors(e){const t=this.parent;null!==t&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(null!==e){const t=e.x,s=e.y,i=e.z,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*s-r[8]*i,r[13]+=s-r[1]*t-r[5]*s-r[9]*i,r[14]+=i-r[2]*t-r[6]*s-r[10]*i}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}updateWorldMatrix(e,t){const s=this.parent;if(!0===e&&null!==s&&s.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),!0===t){const e=this.children;for(let t=0,s=e.length;t<s;t++){e[t].updateWorldMatrix(!1,!0)}}}toJSON(e){const t=void 0===e||"string"==typeof e,s={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},s.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};function r(t,s){return void 0===t[s.uuid]&&(t[s.uuid]=s.toJSON(e)),s.uuid}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),!0===this.castShadow&&(i.castShadow=!0),!0===this.receiveShadow&&(i.receiveShadow=!0),!1===this.visible&&(i.visible=!1),!1===this.frustumCulled&&(i.frustumCulled=!1),0!==this.renderOrder&&(i.renderOrder=this.renderOrder),!1!==this.static&&(i.static=this.static),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),null!==this.pivot&&(i.pivot=this.pivot.toArray()),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),void 0!==this.morphTargetDictionary&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(e=>({...e})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(i.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const s=t.shapes;if(Array.isArray(s))for(let t=0,i=s.length;t<i;t++){const i=s[t];r(e.shapes,i)}else r(e.shapes,s)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let s=0,i=this.material.length;s<i;s++)t.push(r(e.materials,this.material[s]));i.material=t}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let t=0;t<this.children.length;t++)i.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let t=0;t<this.animations.length;t++){const s=this.animations[t];i.animations.push(r(e.animations,s))}}if(t){const t=n(e.geometries),i=n(e.materials),r=n(e.textures),a=n(e.images),o=n(e.shapes),h=n(e.skeletons),u=n(e.animations),l=n(e.nodes);t.length>0&&(s.geometries=t),i.length>0&&(s.materials=i),r.length>0&&(s.textures=r),a.length>0&&(s.images=a),o.length>0&&(s.shapes=o),h.length>0&&(s.skeletons=h),u.length>0&&(s.animations=u),l.length>0&&(s.nodes=l)}return s.object=i,s;function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),null!==e.pivot&&(this.pivot=e.pivot.clone()),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t<e.children.length;t++){const s=e.children[t];this.add(s.clone())}return this}}Rs.DEFAULT_UP=new It(0,1,0),Rs.DEFAULT_MATRIX_AUTO_UPDATE=!0,Rs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;let Ps=class extends Rs{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Bs={type:"move"};class Fs{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Ps,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new Ps,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new It,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new It),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Ps,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new It,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new It),this._grip}dispatchEvent(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const s of e.hand.values())this._getHandJoint(t,s)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(e,t,s){let i=null,r=null,n=null;const a=this._targetRay,o=this._grip,h=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(h&&e.hand){n=!0;for(const i of e.hand.values()){const e=t.getJointPose(i,s),r=this._getHandJoint(h,i);null!==e&&(r.matrix.fromArray(e.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=e.radius),r.visible=null!==e}const i=h.joints["index-finger-tip"],r=h.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,u=.005;h.inputState.pinching&&a>o+u?(h.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!h.inputState.pinching&&a<=o-u&&(h.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,s),null!==r&&(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));null!==a&&(i=t.getPose(e.targetRaySpace,s),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Bs)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==h&&(h.visible=null!==n),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const s=new Ps;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}const Ds={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},Is={h:0,s:0,l:0},Ls={h:0,s:0,l:0};function Os(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+6*(t-e)*(2/3-s):e}class Us{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(void 0===t&&void 0===s){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=He){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,jt.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=jt.workingColorSpace){return this.r=e,this.g=t,this.b=s,jt.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=jt.workingColorSpace){if(e=At(e,1),t=Et(t,0,1),s=Et(s,0,1),0===t)this.r=this.g=this.b=s;else{const i=s<=.5?s*(1+t):s+t-s*t,r=2*s-i;this.r=Os(r,i,e+1/3),this.g=Os(r,i,e),this.b=Os(r,i,e-1/3)}return jt.colorSpaceToWorking(this,i),this}setStyle(e,t=He){function s(t){void 0!==t&&parseFloat(t)<1&&yt("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],a=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(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(a))return s(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(a))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:yt("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],r=s.length;if(3===r)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(s,16),t);yt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=He){const s=Ds[e.toLowerCase()];return void 0!==s?this.setHex(s,t):yt("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=$t(e.r),this.g=$t(e.g),this.b=$t(e.b),this}copyLinearToSRGB(e){return this.r=Wt(e.r),this.g=Wt(e.g),this.b=Wt(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=He){return jt.workingToColorSpace(ks.copy(this),e),65536*Math.round(Et(255*ks.r,0,255))+256*Math.round(Et(255*ks.g,0,255))+Math.round(Et(255*ks.b,0,255))}getHexString(e=He){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=jt.workingColorSpace){jt.workingToColorSpace(ks.copy(this),t);const s=ks.r,i=ks.g,r=ks.b,n=Math.max(s,i,r),a=Math.min(s,i,r);let o,h;const u=(a+n)/2;if(a===n)o=0,h=0;else{const e=n-a;switch(h=u<=.5?e/(n+a):e/(2-n-a),n){case s:o=(i-r)/e+(i<r?6:0);break;case i:o=(r-s)/e+2;break;case r:o=(s-i)/e+4}o/=6}return e.h=o,e.s=h,e.l=u,e}getRGB(e,t=jt.workingColorSpace){return jt.workingToColorSpace(ks.copy(this),t),e.r=ks.r,e.g=ks.g,e.b=ks.b,e}getStyle(e=He){jt.workingToColorSpace(ks.copy(this),e);const t=ks.r,s=ks.g,i=ks.b;return e!==He?`color(${e} ${t.toFixed(3)} ${s.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*s)},${Math.round(255*i)})`}offsetHSL(e,t,s){return this.getHSL(Is),this.setHSL(Is.h+e,Is.s+t,Is.l+s)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,s){return this.r=e.r+(t.r-e.r)*s,this.g=e.g+(t.g-e.g)*s,this.b=e.b+(t.b-e.b)*s,this}lerpHSL(e,t){this.getHSL(Is),e.getHSL(Ls);const s=Ct(Is.h,Ls.h,t),i=Ct(Is.s,Ls.s,t),r=Ct(Is.l,Ls.l,t);return this.setHSL(s,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,s=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*s+r[6]*i,this.g=r[1]*t+r[4]*s+r[7]*i,this.b=r[2]*t+r[5]*s+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const ks=new Us;Us.NAMES=Ds;class zs extends Rs{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 ps,this.environmentIntensity=1,this.environmentRotation=new ps,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(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),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Vs=new It,Gs=new It,js=new It,$s=new It,Ws=new It,Hs=new It,qs=new It,Xs=new It,Ys=new It,Ks=new It,Qs=new es,Zs=new es,Js=new es;class ei{constructor(e=new It,t=new It,s=new It){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),Vs.subVectors(e,t),i.cross(Vs);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,s,i,r){Vs.subVectors(i,t),Gs.subVectors(s,t),js.subVectors(e,t);const n=Vs.dot(Vs),a=Vs.dot(Gs),o=Vs.dot(js),h=Gs.dot(Gs),u=Gs.dot(js),l=n*h-a*a;if(0===l)return r.set(0,0,0),null;const c=1/l,d=(h*o-a*u)*c,p=(n*u-a*o)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,$s)&&($s.x>=0&&$s.y>=0&&$s.x+$s.y<=1)}static getInterpolation(e,t,s,i,r,n,a,o){return null===this.getBarycoord(e,t,s,i,$s)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,$s.x),o.addScaledVector(n,$s.y),o.addScaledVector(a,$s.z),o)}static getInterpolatedAttribute(e,t,s,i,r,n){return Qs.setScalar(0),Zs.setScalar(0),Js.setScalar(0),Qs.fromBufferAttribute(e,t),Zs.fromBufferAttribute(e,s),Js.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Qs,r.x),n.addScaledVector(Zs,r.y),n.addScaledVector(Js,r.z),n}static isFrontFacing(e,t,s,i){return Vs.subVectors(s,t),Gs.subVectors(e,t),Vs.cross(Gs).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Vs.subVectors(this.c,this.b),Gs.subVectors(this.a,this.b),.5*Vs.cross(Gs).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return ei.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return ei.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return ei.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return ei.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return ei.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,r=this.c;let n,a;Ws.subVectors(i,s),Hs.subVectors(r,s),Xs.subVectors(e,s);const o=Ws.dot(Xs),h=Hs.dot(Xs);if(o<=0&&h<=0)return t.copy(s);Ys.subVectors(e,i);const u=Ws.dot(Ys),l=Hs.dot(Ys);if(u>=0&&l<=u)return t.copy(i);const c=o*l-u*h;if(c<=0&&o>=0&&u<=0)return n=o/(o-u),t.copy(s).addScaledVector(Ws,n);Ks.subVectors(e,r);const d=Ws.dot(Ks),p=Hs.dot(Ks);if(p>=0&&d<=p)return t.copy(r);const m=d*h-o*p;if(m<=0&&h>=0&&p<=0)return a=h/(h-p),t.copy(s).addScaledVector(Hs,a);const g=u*p-d*l;if(g<=0&&l-u>=0&&d-p>=0)return qs.subVectors(r,i),a=(l-u)/(l-u+(d-p)),t.copy(i).addScaledVector(qs,a);const f=1/(g+m+c);return n=m*f,a=c*f,t.copy(s).addScaledVector(Ws,n).addScaledVector(Hs,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class ti{constructor(e=new It(1/0,1/0,1/0),t=new It(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t+=3)this.expandByPoint(ii.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(ii.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const s=ii.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(s),this.max.copy(e).add(s),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return(new this.constructor).copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const s=e.geometry;if(void 0!==s){const i=s.getAttribute("position");if(!0===t&&void 0!==i&&!0!==e.isInstancedMesh)for(let t=0,s=i.count;t<s;t++)!0===e.isMesh?e.getVertexPosition(t,ii):ii.fromBufferAttribute(i,t),ii.applyMatrix4(e.matrixWorld),this.expandByPoint(ii);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),ri.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),ri.copy(s.boundingBox)),ri.applyMatrix4(e.matrixWorld),this.union(ri)}const i=e.children;for(let e=0,s=i.length;e<s;e++)this.expandByObject(i[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,ii),ii.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ci),di.subVectors(this.max,ci),ni.subVectors(e.a,ci),ai.subVectors(e.b,ci),oi.subVectors(e.c,ci),hi.subVectors(ai,ni),ui.subVectors(oi,ai),li.subVectors(ni,oi);let t=[0,-hi.z,hi.y,0,-ui.z,ui.y,0,-li.z,li.y,hi.z,0,-hi.x,ui.z,0,-ui.x,li.z,0,-li.x,-hi.y,hi.x,0,-ui.y,ui.x,0,-li.y,li.x,0];return!!gi(t,ni,ai,oi,di)&&(t=[1,0,0,0,1,0,0,0,1],!!gi(t,ni,ai,oi,di)&&(pi.crossVectors(hi,ui),t=[pi.x,pi.y,pi.z],gi(t,ni,ai,oi,di)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ii).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(ii).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(si[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),si[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),si[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),si[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),si[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),si[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),si[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),si[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(si)),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 si=[new It,new It,new It,new It,new It,new It,new It,new It],ii=new It,ri=new ti,ni=new It,ai=new It,oi=new It,hi=new It,ui=new It,li=new It,ci=new It,di=new It,pi=new It,mi=new It;function gi(e,t,s,i,r){for(let n=0,a=e.length-3;n<=a;n+=3){mi.fromArray(e,n);const a=r.x*Math.abs(mi.x)+r.y*Math.abs(mi.y)+r.z*Math.abs(mi.z),o=t.dot(mi),h=s.dot(mi),u=i.dot(mi);if(Math.max(-Math.max(o,h,u),Math.min(o,h,u))>a)return!1}return!0}const fi=yi();function yi(){const e=new ArrayBuffer(4),t=new Float32Array(e),s=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const n=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,s=0;for(;!(8388608&t);)t<<=1,s-=8388608;t&=-8388609,s+=947912704,n[e]=t|s}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:a,offsetTable:o}}function bi(e){Math.abs(e)>65504&&yt("DataUtils.toHalfFloat(): Value out of range."),e=Et(e,-65504,65504),fi.floatView[0]=e;const t=fi.uint32View[0],s=t>>23&511;return fi.baseTable[s]+((8388607&t)>>fi.shiftTable[s])}function _i(e){const t=e>>10;return fi.uint32View[0]=fi.mantissaTable[fi.offsetTable[t]+(1023&e)]+fi.exponentTable[t],fi.floatView[0]}const xi=new It,vi=new Ft;let Ti=0;class Si{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Ti++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=nt,this.updateRanges=[],this.gpuType=Y,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[e+i]=t.array[s+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,s=this.count;t<s;t++)vi.fromBufferAttribute(this,t),vi.applyMatrix3(e),this.setXY(t,vi.x,vi.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)xi.fromBufferAttribute(this,t),xi.applyMatrix3(e),this.setXYZ(t,xi.x,xi.y,xi.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)xi.fromBufferAttribute(this,t),xi.applyMatrix4(e),this.setXYZ(t,xi.x,xi.y,xi.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)xi.fromBufferAttribute(this,t),xi.applyNormalMatrix(e),this.setXYZ(t,xi.x,xi.y,xi.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)xi.fromBufferAttribute(this,t),xi.transformDirection(e),this.setXYZ(t,xi.x,xi.y,xi.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let s=this.array[e*this.itemSize+t];return this.normalized&&(s=Rt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=Pt(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Rt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Rt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Rt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Rt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),s=Pt(s,this.array)),this.array[e+0]=t,this.array[e+1]=s,this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),s=Pt(s,this.array),i=Pt(i,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),s=Pt(s,this.array),i=Pt(i,this.array),r=Pt(r,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return""!==this.name&&(e.name=this.name),this.usage!==nt&&(e.usage=this.usage),e}}class wi extends Si{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Mi extends Si{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class Ni extends Si{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=_i(this.array[e*this.itemSize]);return this.normalized&&(t=Rt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize]=bi(t),this}getY(e){let t=_i(this.array[e*this.itemSize+1]);return this.normalized&&(t=Rt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+1]=bi(t),this}getZ(e){let t=_i(this.array[e*this.itemSize+2]);return this.normalized&&(t=Rt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+2]=bi(t),this}getW(e){let t=_i(this.array[e*this.itemSize+3]);return this.normalized&&(t=Rt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+3]=bi(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),s=Pt(s,this.array)),this.array[e+0]=bi(t),this.array[e+1]=bi(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),s=Pt(s,this.array),i=Pt(i,this.array)),this.array[e+0]=bi(t),this.array[e+1]=bi(s),this.array[e+2]=bi(i),this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),s=Pt(s,this.array),i=Pt(i,this.array),r=Pt(r,this.array)),this.array[e+0]=bi(t),this.array[e+1]=bi(s),this.array[e+2]=bi(i),this.array[e+3]=bi(r),this}}class Ei extends Si{constructor(e,t,s){super(new Float32Array(e),t,s)}}const Ai=new ti,Ci=new It,Ri=new It;class Pi{constructor(e=new It,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 s=this.center;void 0!==t?s.copy(t):Ai.setFromPoints(e).getCenter(s);let i=0;for(let t=0,r=e.length;t<r;t++)i=Math.max(i,s.distanceToSquared(e[t]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const s=this.center.distanceToSquared(e);return t.copy(e),s>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=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;Ci.subVectors(e,this.center);const t=Ci.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Ci,s/e),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(Ri.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ci.copy(e.center).add(Ri)),this.expandByPoint(Ci.copy(e.center).sub(Ri))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}let Bi=0;const Fi=new is,Di=new Rs,Ii=new It,Li=new ti,Oi=new ti,Ui=new It;class ki extends vt{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Bi++}),this.uuid=Nt(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(e)?Mi:wi)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(void 0!==s){const t=(new Ut).getNormalMatrix(e);s.applyNormalMatrix(t),s.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return Fi.makeRotationFromQuaternion(e),this.applyMatrix4(Fi),this}rotateX(e){return Fi.makeRotationX(e),this.applyMatrix4(Fi),this}rotateY(e){return Fi.makeRotationY(e),this.applyMatrix4(Fi),this}rotateZ(e){return Fi.makeRotationZ(e),this.applyMatrix4(Fi),this}translate(e,t,s){return Fi.makeTranslation(e,t,s),this.applyMatrix4(Fi),this}scale(e,t,s){return Fi.makeScale(e,t,s),this.applyMatrix4(Fi),this}lookAt(e){return Di.lookAt(e),Di.updateMatrix(),this.applyMatrix4(Di.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Ii).negate(),this.translate(Ii.x,Ii.y,Ii.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let s=0,i=e.length;s<i;s++){const i=e[s];t.push(i.x,i.y,i.z||0)}this.setAttribute("position",new Ei(t,3))}else{const s=Math.min(e.length,t.count);for(let i=0;i<s;i++){const s=e[i];t.setXYZ(i,s.x,s.y,s.z||0)}e.length>t.count&&yt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new ti);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return bt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new It(-1/0,-1/0,-1/0),new It(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];Li.setFromBufferAttribute(s),this.morphTargetsRelative?(Ui.addVectors(this.boundingBox.min,Li.min),this.boundingBox.expandByPoint(Ui),Ui.addVectors(this.boundingBox.max,Li.max),this.boundingBox.expandByPoint(Ui)):(this.boundingBox.expandByPoint(Li.min),this.boundingBox.expandByPoint(Li.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&bt('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new Pi);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return bt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new It,1/0);if(e){const s=this.boundingSphere.center;if(Li.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];Oi.setFromBufferAttribute(s),this.morphTargetsRelative?(Ui.addVectors(Li.min,Oi.min),Li.expandByPoint(Ui),Ui.addVectors(Li.max,Oi.max),Li.expandByPoint(Ui)):(Li.expandByPoint(Oi.min),Li.expandByPoint(Oi.max))}Li.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)Ui.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(Ui));if(t)for(let r=0,n=t.length;r<n;r++){const n=t[r],a=this.morphTargetsRelative;for(let t=0,r=n.count;t<r;t++)Ui.fromBufferAttribute(n,t),a&&(Ii.fromBufferAttribute(e,t),Ui.add(Ii)),i=Math.max(i,s.distanceToSquared(Ui))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&bt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(null===e||void 0===t.position||void 0===t.normal||void 0===t.uv)return void bt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const s=t.position,i=t.normal,r=t.uv;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new Si(new Float32Array(4*s.count),4));const n=this.getAttribute("tangent"),a=[],o=[];for(let e=0;e<s.count;e++)a[e]=new It,o[e]=new It;const h=new It,u=new It,l=new It,c=new Ft,d=new Ft,p=new Ft,m=new It,g=new It;function f(e,t,i){h.fromBufferAttribute(s,e),u.fromBufferAttribute(s,t),l.fromBufferAttribute(s,i),c.fromBufferAttribute(r,e),d.fromBufferAttribute(r,t),p.fromBufferAttribute(r,i),u.sub(h),l.sub(h),d.sub(c),p.sub(c);const n=1/(d.x*p.y-p.x*d.y);isFinite(n)&&(m.copy(u).multiplyScalar(p.y).addScaledVector(l,-d.y).multiplyScalar(n),g.copy(l).multiplyScalar(d.x).addScaledVector(u,-p.x).multiplyScalar(n),a[e].add(m),a[t].add(m),a[i].add(m),o[e].add(g),o[t].add(g),o[i].add(g))}let y=this.groups;0===y.length&&(y=[{start:0,count:e.count}]);for(let t=0,s=y.length;t<s;++t){const s=y[t],i=s.start;for(let t=i,r=i+s.count;t<r;t+=3)f(e.getX(t+0),e.getX(t+1),e.getX(t+2))}const b=new It,_=new It,x=new It,v=new It;function T(e){x.fromBufferAttribute(i,e),v.copy(x);const t=a[e];b.copy(t),b.sub(x.multiplyScalar(x.dot(t))).normalize(),_.crossVectors(v,t);const s=_.dot(o[e])<0?-1:1;n.setXYZW(e,b.x,b.y,b.z,s)}for(let t=0,s=y.length;t<s;++t){const s=y[t],i=s.start;for(let t=i,r=i+s.count;t<r;t+=3)T(e.getX(t+0)),T(e.getX(t+1)),T(e.getX(t+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(void 0!==t){let s=this.getAttribute("normal");if(void 0===s)s=new Si(new Float32Array(3*t.count),3),this.setAttribute("normal",s);else for(let e=0,t=s.count;e<t;e++)s.setXYZ(e,0,0,0);const i=new It,r=new It,n=new It,a=new It,o=new It,h=new It,u=new It,l=new It;if(e)for(let c=0,d=e.count;c<d;c+=3){const d=e.getX(c+0),p=e.getX(c+1),m=e.getX(c+2);i.fromBufferAttribute(t,d),r.fromBufferAttribute(t,p),n.fromBufferAttribute(t,m),u.subVectors(n,r),l.subVectors(i,r),u.cross(l),a.fromBufferAttribute(s,d),o.fromBufferAttribute(s,p),h.fromBufferAttribute(s,m),a.add(u),o.add(u),h.add(u),s.setXYZ(d,a.x,a.y,a.z),s.setXYZ(p,o.x,o.y,o.z),s.setXYZ(m,h.x,h.y,h.z)}else for(let e=0,a=t.count;e<a;e+=3)i.fromBufferAttribute(t,e+0),r.fromBufferAttribute(t,e+1),n.fromBufferAttribute(t,e+2),u.subVectors(n,r),l.subVectors(i,r),u.cross(l),s.setXYZ(e+0,u.x,u.y,u.z),s.setXYZ(e+1,u.x,u.y,u.z),s.setXYZ(e+2,u.x,u.y,u.z);this.normalizeNormals(),s.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,s=e.count;t<s;t++)Ui.fromBufferAttribute(e,t),Ui.normalize(),e.setXYZ(t,Ui.x,Ui.y,Ui.z)}toNonIndexed(){function e(e,t){const s=e.array,i=e.itemSize,r=e.normalized,n=new s.constructor(t.length*i);let a=0,o=0;for(let r=0,h=t.length;r<h;r++){a=e.isInterleavedBufferAttribute?t[r]*e.data.stride+e.offset:t[r]*i;for(let e=0;e<i;e++)n[o++]=s[a++]}return new Si(n,i,r)}if(null===this.index)return yt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ki,s=this.index.array,i=this.attributes;for(const r in i){const n=e(i[r],s);t.setAttribute(r,n)}const r=this.morphAttributes;for(const i in r){const n=[],a=r[i];for(let t=0,i=a.length;t<i;t++){const i=e(a[t],s);n.push(i)}t.morphAttributes[i]=n}t.morphTargetsRelative=this.morphTargetsRelative;const n=this.groups;for(let e=0,s=n.length;e<s;e++){const s=n[e];t.addGroup(s.start,s.count,s.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,""!==this.name&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const s in t)void 0!==t[s]&&(e[s]=t[s]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const t in s){const i=s[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const s=this.morphAttributes[t],n=[];for(let t=0,i=s.length;t<i;t++){const i=s[t];n.push(i.toJSON(e.data))}n.length>0&&(i[t]=n,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const n=this.groups;n.length>0&&(e.data.groups=JSON.parse(JSON.stringify(n)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere=a.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 s=e.index;null!==s&&this.setIndex(s.clone());const i=e.attributes;for(const e in i){const s=i[e];this.setAttribute(e,s.clone(t))}const r=e.morphAttributes;for(const e in r){const s=[],i=r[e];for(let e=0,r=i.length;e<r;e++)s.push(i[e].clone(t));this.morphAttributes[e]=s}this.morphTargetsRelative=e.morphTargetsRelative;const n=e.groups;for(let e=0,t=n.length;e<t;e++){const t=n[e];this.addGroup(t.start,t.count,t.materialIndex)}const a=e.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=e.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}class zi{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=nt,this.updateRanges=[],this.version=0,this.uuid=Nt()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,s){e*=this.stride,s*=t.stride;for(let i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[s+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=Nt()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),s=new this.constructor(t,this.stride);return s.setUsage(this.usage),s}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=Nt()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const Vi=new It;class Gi{constructor(e,t,s,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=s,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,s=this.data.count;t<s;t++)Vi.fromBufferAttribute(this,t),Vi.applyMatrix4(e),this.setXYZ(t,Vi.x,Vi.y,Vi.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Vi.fromBufferAttribute(this,t),Vi.applyNormalMatrix(e),this.setXYZ(t,Vi.x,Vi.y,Vi.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Vi.fromBufferAttribute(this,t),Vi.transformDirection(e),this.setXYZ(t,Vi.x,Vi.y,Vi.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=Rt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=Pt(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=Rt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Rt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Rt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Rt(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Pt(t,this.array),s=Pt(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this}setXYZ(e,t,s,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=Pt(t,this.array),s=Pt(s,this.array),i=Pt(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this}setXYZW(e,t,s,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=Pt(t,this.array),s=Pt(s,this.array),i=Pt(i,this.array),r=Pt(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this.data.array[e+3]=r,this}clone(e){if(void 0===e){gt("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const s=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[s+t])}return new Si(new this.array.constructor(e),this.itemSize,this.normalized)}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new Gi(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){gt("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const s=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[s+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}let ji=0;class $i extends vt{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:ji++}),this.uuid=Nt(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=y,this.blendDst=b,this.blendEquation=l,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Us(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Ke,this.stencilZFail=Ke,this.stencilZPass=Ke,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const s=e[t];if(void 0===s){yt(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s:yt(`Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const s={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(s.uuid=this.uuid,s.type=this.type,""!==this.name&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),void 0!==this.roughness&&(s.roughness=this.roughness),void 0!==this.metalness&&(s.metalness=this.metalness),void 0!==this.sheen&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(s.shininess=this.shininess),void 0!==this.clearcoat&&(s.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(s.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(s.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),void 0!==this.dispersion&&(s.dispersion=this.dispersion),void 0!==this.iridescence&&(s.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(s.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(s.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(s.combine=this.combine)),void 0!==this.envMapRotation&&(s.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(s.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(s.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(s.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(s.size=this.size),null!==this.shadowSide&&(s.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(s.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(s.blending=this.blending),0!==this.side&&(s.side=this.side),!0===this.vertexColors&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),!0===this.transparent&&(s.transparent=!0),this.blendSrc!==y&&(s.blendSrc=this.blendSrc),this.blendDst!==b&&(s.blendDst=this.blendDst),this.blendEquation!==l&&(s.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(s.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(s.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(s.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(s.depthFunc=this.depthFunc),!1===this.depthTest&&(s.depthTest=this.depthTest),!1===this.depthWrite&&(s.depthWrite=this.depthWrite),!1===this.colorWrite&&(s.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(s.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(s.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(s.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ke&&(s.stencilFail=this.stencilFail),this.stencilZFail!==Ke&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==Ke&&(s.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(s.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(s.rotation=this.rotation),!0===this.polygonOffset&&(s.polygonOffset=!0),0!==this.polygonOffsetFactor&&(s.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(s.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(s.linewidth=this.linewidth),void 0!==this.dashSize&&(s.dashSize=this.dashSize),void 0!==this.gapSize&&(s.gapSize=this.gapSize),void 0!==this.scale&&(s.scale=this.scale),!0===this.dithering&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),!0===this.alphaHash&&(s.alphaHash=!0),!0===this.alphaToCoverage&&(s.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(s.premultipliedAlpha=!0),!0===this.forceSinglePass&&(s.forceSinglePass=!0),!1===this.allowOverride&&(s.allowOverride=!1),!0===this.wireframe&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(s.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(s.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(s.flatShading=!0),!1===this.visible&&(s.visible=!1),!1===this.toneMapped&&(s.toneMapped=!1),!1===this.fog&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(s.textures=t),r.length>0&&(s.images=r)}return s}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 s=null;if(null!==t){const e=t.length;s=new Array(e);for(let i=0;i!==e;++i)s[i]=t[i].clone()}return this.clippingPlanes=s,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}class Wi extends $i{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Us(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const Hi=new It,qi=new It,Xi=new It,Yi=new It,Ki=new It,Qi=new It,Zi=new It;class Ji{constructor(e=new It,t=new It(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,Hi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Hi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Hi.copy(this.origin).addScaledVector(this.direction,t),Hi.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){qi.copy(e).add(t).multiplyScalar(.5),Xi.copy(t).sub(e).normalize(),Yi.copy(this.origin).sub(qi);const r=.5*e.distanceTo(t),n=-this.direction.dot(Xi),a=Yi.dot(this.direction),o=-Yi.dot(Xi),h=Yi.lengthSq(),u=Math.abs(1-n*n);let l,c,d,p;if(u>0)if(l=n*o-a,c=n*a-o,p=r*u,l>=0)if(c>=-p)if(c<=p){const e=1/u;l*=e,c*=e,d=l*(l+n*c+2*a)+c*(n*l+c+2*o)+h}else c=r,l=Math.max(0,-(n*c+a)),d=-l*l+c*(c+2*o)+h;else c=-r,l=Math.max(0,-(n*c+a)),d=-l*l+c*(c+2*o)+h;else c<=-p?(l=Math.max(0,-(-n*r+a)),c=l>0?-r:Math.min(Math.max(-r,-o),r),d=-l*l+c*(c+2*o)+h):c<=p?(l=0,c=Math.min(Math.max(-r,-o),r),d=c*(c+2*o)+h):(l=Math.max(0,-(n*r+a)),c=l>0?r:Math.min(Math.max(-r,-o),r),d=-l*l+c*(c+2*o)+h);else c=n>0?-r:r,l=Math.max(0,-(n*c+a)),d=-l*l+c*(c+2*o)+h;return s&&s.copy(this.origin).addScaledVector(this.direction,l),i&&i.copy(qi).addScaledVector(Xi,c),d}intersectSphere(e,t){Hi.subVectors(e.center,this.origin);const s=Hi.dot(this.direction),i=Hi.dot(Hi)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),a=s-n,o=s+n;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return!(e.radius<0)&&this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return null===s?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,r,n,a,o;const h=1/this.direction.x,u=1/this.direction.y,l=1/this.direction.z,c=this.origin;return h>=0?(s=(e.min.x-c.x)*h,i=(e.max.x-c.x)*h):(s=(e.max.x-c.x)*h,i=(e.min.x-c.x)*h),u>=0?(r=(e.min.y-c.y)*u,n=(e.max.y-c.y)*u):(r=(e.max.y-c.y)*u,n=(e.min.y-c.y)*u),s>n||r>i?null:((r>s||isNaN(s))&&(s=r),(n<i||isNaN(i))&&(i=n),l>=0?(a=(e.min.z-c.z)*l,o=(e.max.z-c.z)*l):(a=(e.max.z-c.z)*l,o=(e.min.z-c.z)*l),s>o||a>i?null:((a>s||s!=s)&&(s=a),(o<i||i!=i)&&(i=o),i<0?null:this.at(s>=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Hi)}intersectTriangle(e,t,s,i,r){Ki.subVectors(t,e),Qi.subVectors(s,e),Zi.crossVectors(Ki,Qi);let n,a=this.direction.dot(Zi);if(a>0){if(i)return null;n=1}else{if(!(a<0))return null;n=-1,a=-a}Yi.subVectors(this.origin,e);const o=n*this.direction.dot(Qi.crossVectors(Yi,Qi));if(o<0)return null;const h=n*this.direction.dot(Ki.cross(Yi));if(h<0)return null;if(o+h>a)return null;const u=-n*Yi.dot(Zi);return u<0?null:this.at(u/a,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 er extends $i{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Us(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 ps,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const tr=new is,sr=new Ji,ir=new Pi,rr=new It,nr=new It,ar=new It,or=new It,hr=new It,ur=new It,lr=new It,cr=new It;class dr extends Rs{constructor(e=new ki,t=new er){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),void 0!==e.morphTargetInfluences&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),void 0!==e.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;e<t;e++){const t=s[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){const s=this.geometry,i=s.attributes.position,r=s.morphAttributes.position,n=s.morphTargetsRelative;t.fromBufferAttribute(i,e);const a=this.morphTargetInfluences;if(r&&a){ur.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=a[s],o=r[s];0!==i&&(hr.fromBufferAttribute(o,e),n?ur.addScaledVector(hr,i):ur.addScaledVector(hr.sub(t),i))}t.add(ur)}return t}raycast(e,t){const s=this.geometry,i=this.material,r=this.matrixWorld;if(void 0!==i){if(null===s.boundingSphere&&s.computeBoundingSphere(),ir.copy(s.boundingSphere),ir.applyMatrix4(r),sr.copy(e.ray).recast(e.near),!1===ir.containsPoint(sr.origin)){if(null===sr.intersectSphere(ir,rr))return;if(sr.origin.distanceToSquared(rr)>(e.far-e.near)**2)return}tr.copy(r).invert(),sr.copy(e.ray).applyMatrix4(tr),null!==s.boundingBox&&!1===sr.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,sr)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,a=r.index,o=r.attributes.position,h=r.attributes.uv,u=r.attributes.uv1,l=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(n))for(let r=0,o=c.length;r<o;r++){const o=c[r],p=n[o.materialIndex];for(let r=Math.max(o.start,d.start),n=Math.min(a.count,Math.min(o.start+o.count,d.start+d.count));r<n;r+=3){i=pr(this,p,e,s,h,u,l,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=o.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);r<o;r+=3){i=pr(this,n,e,s,h,u,l,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}else if(void 0!==o)if(Array.isArray(n))for(let r=0,a=c.length;r<a;r++){const a=c[r],p=n[a.materialIndex];for(let r=Math.max(a.start,d.start),n=Math.min(o.count,Math.min(a.start+a.count,d.start+d.count));r<n;r+=3){i=pr(this,p,e,s,h,u,l,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=a.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);r<a;r+=3){i=pr(this,n,e,s,h,u,l,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function pr(e,t,s,i,r,n,a,o,h,u){e.getVertexPosition(o,nr),e.getVertexPosition(h,ar),e.getVertexPosition(u,or);const l=function(e,t,s,i,r,n,a,o){let h;if(h=1===t.side?i.intersectTriangle(a,n,r,!0,o):i.intersectTriangle(r,n,a,0===t.side,o),null===h)return null;cr.copy(o),cr.applyMatrix4(e.matrixWorld);const u=s.ray.origin.distanceTo(cr);return u<s.near||u>s.far?null:{distance:u,point:cr.clone(),object:e}}(e,t,s,i,nr,ar,or,lr);if(l){const e=new It;ei.getBarycoord(lr,nr,ar,or,e),r&&(l.uv=ei.getInterpolatedAttribute(r,o,h,u,e,new Ft)),n&&(l.uv1=ei.getInterpolatedAttribute(n,o,h,u,e,new Ft)),a&&(l.normal=ei.getInterpolatedAttribute(a,o,h,u,e,new It),l.normal.dot(i.direction)>0&&l.normal.multiplyScalar(-1));const t={a:o,b:h,c:u,normal:new It,materialIndex:0};ei.getNormal(nr,ar,or,t.normal),l.face=t,l.barycoord=e}return l}class mr extends Jt{constructor(e=null,t=1,s=1,i,r,n,a,o,h=1003,u=1003,l,c){super(null,n,a,o,h,u,i,r,l,c),this.isDataTexture=!0,this.image={data:e,width:t,height:s},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class gr extends Si{constructor(e,t,s,i=1){super(e,t,s),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const fr=new It,yr=new It,br=new Ut;class _r{constructor(e=new It(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,s,i){return this.normal.set(e,t,s),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,s){const i=fr.subVectors(s,t).cross(yr.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const s=e.delta(fr),i=this.normal.dot(s);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(e.start).addScaledVector(s,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<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 s=t||br.getNormalMatrix(e),i=this.coplanarPoint(fr).applyMatrix4(e),r=this.normal.applyMatrix3(s).normalize();return this.constant=-i.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 xr=new Pi,vr=new Ft(.5,.5),Tr=new It;class Sr{constructor(e=new _r,t=new _r,s=new _r,i=new _r,r=new _r,n=new _r){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(s),a[3].copy(i),a[4].copy(r),a[5].copy(n),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=2e3,s=!1){const i=this.planes,r=e.elements,n=r[0],a=r[1],o=r[2],h=r[3],u=r[4],l=r[5],c=r[6],d=r[7],p=r[8],m=r[9],g=r[10],f=r[11],y=r[12],b=r[13],_=r[14],x=r[15];if(i[0].setComponents(h-n,d-u,f-p,x-y).normalize(),i[1].setComponents(h+n,d+u,f+p,x+y).normalize(),i[2].setComponents(h+a,d+l,f+m,x+b).normalize(),i[3].setComponents(h-a,d-l,f-m,x-b).normalize(),s)i[4].setComponents(o,c,g,_).normalize(),i[5].setComponents(h-o,d-c,f-g,x-_).normalize();else if(i[4].setComponents(h-o,d-c,f-g,x-_).normalize(),t===ot)i[5].setComponents(h+o,d+c,f+g,x+_).normalize();else{if(t!==ht)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(o,c,g,_).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),xr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),xr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(xr)}intersectsSprite(e){xr.center.set(0,0,0);const t=vr.distanceTo(e.center);return xr.radius=.7071067811865476+t,xr.applyMatrix4(e.matrixWorld),this.intersectsSphere(xr)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(s)<i)return!1}return!0}intersectsBox(e){const t=this.planes;for(let s=0;s<6;s++){const i=t[s];if(Tr.x=i.normal.x>0?e.max.x:e.min.x,Tr.y=i.normal.y>0?e.max.y:e.min.y,Tr.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Tr)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}const wr=new is,Mr=new Sr;class Nr{constructor(){this.coordinateSystem=ot}intersectsObject(e,t){if(!t.isArrayCamera||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(wr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Mr.setFromProjectionMatrix(wr,i.coordinateSystem,i.reversedDepth),Mr.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(wr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Mr.setFromProjectionMatrix(wr,i.coordinateSystem,i.reversedDepth),Mr.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(wr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Mr.setFromProjectionMatrix(wr,i.coordinateSystem,i.reversedDepth),Mr.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(wr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Mr.setFromProjectionMatrix(wr,i.coordinateSystem,i.reversedDepth),Mr.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(wr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Mr.setFromProjectionMatrix(wr,i.coordinateSystem,i.reversedDepth),Mr.containsPoint(e))return!0}return!1}clone(){return new Nr}}class Er extends $i{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Us(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}class Ar extends $i{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Us(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class Cr extends Jt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=O,this.minFilter=O,this.generateMipmaps=!1,this.needsUpdate=!0}}class Rr extends Jt{constructor(e=[],t=301,s,i,r,n,a,o,h,u){super(e,t,s,i,r,n,a,o,h,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Pr extends Jt{constructor(e,t,s=1014,i,r,n,a=1003,o=1003,h,u=1026,l=1){if(u!==re&&u!==ne)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:l},i,r,n,a,o,u,s,h),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Yt(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class Br extends Pr{constructor(e,t=1014,s=301,i,r,n=1003,a=1003,o,h=1026){const u={width:e,height:e,depth:1},l=[u,u,u,u,u,u];super(e,e,t,s,i,r,n,a,o,h),this.image=l,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class Fr extends ki{constructor(e=1,t=1,s=1,i=1,r=1,n=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:r,depthSegments:n};const a=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const o=[],h=[],u=[],l=[];let c=0,d=0;function p(e,t,s,i,r,n,p,m,g,f,y){const b=n/g,_=p/f,x=n/2,v=p/2,T=m/2,S=g+1,w=f+1;let M=0,N=0;const E=new It;for(let n=0;n<w;n++){const a=n*_-v;for(let o=0;o<S;o++){const c=o*b-x;E[e]=c*i,E[t]=a*r,E[s]=T,h.push(E.x,E.y,E.z),E[e]=0,E[t]=0,E[s]=m>0?1:-1,u.push(E.x,E.y,E.z),l.push(o/g),l.push(1-n/f),M+=1}}for(let e=0;e<f;e++)for(let t=0;t<g;t++){const s=c+t+S*e,i=c+t+S*(e+1),r=c+(t+1)+S*(e+1),n=c+(t+1)+S*e;o.push(s,i,n),o.push(i,r,n),N+=6}a.addGroup(d,N,y),d+=N,c+=M}p("z","y","x",-1,-1,s,t,e,n,r,0),p("z","y","x",1,-1,s,t,-e,n,r,1),p("x","z","y",1,1,e,s,t,i,n,2),p("x","z","y",1,-1,e,s,-t,i,n,3),p("x","y","z",1,-1,e,t,s,i,r,4),p("x","y","z",-1,-1,e,t,-s,i,r,5),this.setIndex(o),this.setAttribute("position",new Ei(h,3)),this.setAttribute("normal",new Ei(u,3)),this.setAttribute("uv",new Ei(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Fr(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class Dr extends ki{constructor(e=1,t=1,s=1,i=32,r=1,n=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:r,openEnded:n,thetaStart:a,thetaLength:o};const h=this;i=Math.floor(i),r=Math.floor(r);const u=[],l=[],c=[],d=[];let p=0;const m=[],g=s/2;let f=0;function y(s){const r=p,n=new Ft,m=new It;let y=0;const b=!0===s?e:t,_=!0===s?1:-1;for(let e=1;e<=i;e++)l.push(0,g*_,0),c.push(0,_,0),d.push(.5,.5),p++;const x=p;for(let e=0;e<=i;e++){const t=e/i*o+a,s=Math.cos(t),r=Math.sin(t);m.x=b*r,m.y=g*_,m.z=b*s,l.push(m.x,m.y,m.z),c.push(0,_,0),n.x=.5*s+.5,n.y=.5*r*_+.5,d.push(n.x,n.y),p++}for(let e=0;e<i;e++){const t=r+e,i=x+e;!0===s?u.push(i,i+1,t):u.push(i+1,i,t),y+=3}h.addGroup(f,y,!0===s?1:2),f+=y}!function(){const n=new It,y=new It;let b=0;const _=(t-e)/s;for(let h=0;h<=r;h++){const u=[],f=h/r,b=f*(t-e)+e;for(let e=0;e<=i;e++){const t=e/i,r=t*o+a,h=Math.sin(r),m=Math.cos(r);y.x=b*h,y.y=-f*s+g,y.z=b*m,l.push(y.x,y.y,y.z),n.set(h,_,m).normalize(),c.push(n.x,n.y,n.z),d.push(t,1-f),u.push(p++)}m.push(u)}for(let s=0;s<i;s++)for(let i=0;i<r;i++){const n=m[i][s],a=m[i+1][s],o=m[i+1][s+1],h=m[i][s+1];(e>0||0!==i)&&(u.push(n,a,h),b+=3),(t>0||i!==r-1)&&(u.push(a,o,h),b+=3)}h.addGroup(f,b,0),f+=b}(),!1===n&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(u),this.setAttribute("position",new Ei(l,3)),this.setAttribute("normal",new Ei(c,3)),this.setAttribute("uv",new Ei(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Dr(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Ir extends ki{constructor(e=1,t=1,s=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:s,heightSegments:i};const r=e/2,n=t/2,a=Math.floor(s),o=Math.floor(i),h=a+1,u=o+1,l=e/a,c=t/o,d=[],p=[],m=[],g=[];for(let e=0;e<u;e++){const t=e*c-n;for(let s=0;s<h;s++){const i=s*l-r;p.push(i,-t,0),m.push(0,0,1),g.push(s/a),g.push(1-e/o)}}for(let e=0;e<o;e++)for(let t=0;t<a;t++){const s=t+h*e,i=t+h*(e+1),r=t+1+h*(e+1),n=t+1+h*e;d.push(s,i,n),d.push(i,r,n)}this.setIndex(d),this.setAttribute("position",new Ei(p,3)),this.setAttribute("normal",new Ei(m,3)),this.setAttribute("uv",new Ei(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ir(e.width,e.height,e.widthSegments,e.heightSegments)}}class Lr extends ki{constructor(e=1,t=32,s=16,i=0,r=2*Math.PI,n=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:r,thetaStart:n,thetaLength:a},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const o=Math.min(n+a,Math.PI);let h=0;const u=[],l=new It,c=new It,d=[],p=[],m=[],g=[];for(let d=0;d<=s;d++){const f=[],y=d/s;let b=0;0===d&&0===n?b=.5/t:d===s&&o===Math.PI&&(b=-.5/t);for(let s=0;s<=t;s++){const o=s/t;l.x=-e*Math.cos(i+o*r)*Math.sin(n+y*a),l.y=e*Math.cos(n+y*a),l.z=e*Math.sin(i+o*r)*Math.sin(n+y*a),p.push(l.x,l.y,l.z),c.copy(l).normalize(),m.push(c.x,c.y,c.z),g.push(o+b,1-y),f.push(h++)}u.push(f)}for(let e=0;e<s;e++)for(let i=0;i<t;i++){const t=u[e][i+1],r=u[e][i],a=u[e+1][i],h=u[e+1][i+1];(0!==e||n>0)&&d.push(t,r,h),(e!==s-1||o<Math.PI)&&d.push(r,a,h)}this.setIndex(d),this.setAttribute("position",new Ei(p,3)),this.setAttribute("normal",new Ei(m,3)),this.setAttribute("uv",new Ei(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Lr(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class Or extends $i{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Us(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}class Ur extends $i{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Us(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Us(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ft(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ps,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class kr extends Ur{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new Ft(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Et(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Us(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new Us(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Us(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=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 zr extends $i{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Us(16777215),this.specular=new Us(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Us(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ft(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ps,this.combine=0,this.reflectivity=1,this.envMapIntensity=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.envMapIntensity=e.envMapIntensity,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 Vr extends $i{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Us(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Us(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ft(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 Gr extends $i{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ft(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 jr extends $i{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Us(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Us(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ft(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ps,this.combine=0,this.reflectivity=1,this.envMapIntensity=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.envMapIntensity=e.envMapIntensity,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 $i{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Us(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ft(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 Wr extends Er{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}}class Hr extends Rs{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Us(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}class qr extends Hr{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Rs.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Us(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){const t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}}const Xr=new is,Yr=new It,Kr=new It;class Qr{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Ft(512,512),this.mapType=j,this.map=null,this.mapPass=null,this.matrix=new is,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Sr,this._frameExtents=new Ft(1,1),this._viewportCount=1,this._viewports=[new es(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;Yr.setFromMatrixPosition(e.matrixWorld),t.position.copy(Yr),Kr.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Kr),t.updateMatrixWorld(),Xr.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Xr,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===ht||t.reversedDepth?s.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(Xr)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return(new this.constructor).copy(this)}toJSON(){const e={};return 1!==this.intensity&&(e.intensity=this.intensity),0!==this.bias&&(e.bias=this.bias),0!==this.normalBias&&(e.normalBias=this.normalBias),1!==this.radius&&(e.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const Zr=new It,Jr=new Dt,en=new It;class tn extends Rs{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new is,this.projectionMatrix=new is,this.projectionMatrixInverse=new is,this.coordinateSystem=ot,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.matrixWorld.decompose(Zr,Jr,en),1===en.x&&1===en.y&&1===en.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Zr,Jr,en.set(1,1,1)).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorld.decompose(Zr,Jr,en),1===en.x&&1===en.y&&1===en.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Zr,Jr,en.set(1,1,1)).invert()}clone(){return(new this.constructor).copy(this)}}const sn=new It,rn=new Ft,nn=new Ft;class an extends tn{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*Mt*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*wt*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Mt*Math.atan(Math.tan(.5*wt*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,s){sn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(sn.x,sn.y).multiplyScalar(-e/sn.z),sn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(sn.x,sn.y).multiplyScalar(-e/sn.z)}getViewSize(e,t){return this.getViewBounds(e,rn,nn),t.subVectors(nn,rn)}setViewOffset(e,t,s,i,r,n){this.aspect=e/t,null===this.view&&(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=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*wt*this.fov)/this.zoom,s=2*t,i=this.aspect*s,r=-.5*i;const n=this.view;if(null!==this.view&&this.view.enabled){const e=n.fullWidth,a=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/a,i*=n.width/e,s*=n.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-s,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,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}class on extends Qr{constructor(){super(new an(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=2*Mt*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,r=e.distance||t.far;s===t.fov&&i===t.aspect&&r===t.far||(t.fov=s,t.aspect=i,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class hn extends Hr{constructor(e,t,s=0,i=Math.PI/3,r=0,n=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Rs.DEFAULT_UP),this.updateMatrix(),this.target=new Rs,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new on}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}}class un extends Qr{constructor(){super(new an(90,1,.5,500)),this.isPointLightShadow=!0}}class ln extends Hr{constructor(e,t,s=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=s,this.decay=i,this.shadow=new un}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}}class cn extends tn{constructor(e=-1,t=1,s=1,i=-1,r=.1,n=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=s,this.bottom=i,this.near=r,this.far=n,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,s,i,r,n){null===this.view&&(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=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),s=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=s-e,n=s+e,a=i+t,o=i-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=e*this.view.offsetX,n=r+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(r,n,a,o,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}class dn extends Qr{constructor(){super(new cn(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class pn extends Hr{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Rs.DEFAULT_UP),this.updateMatrix(),this.target=new Rs,this.shadow=new dn}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class mn extends Hr{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class gn extends Hr{constructor(e,t,s=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=s,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class fn{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new It)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const s=e.x,i=e.y,r=e.z,n=this.coefficients;return t.copy(n[0]).multiplyScalar(.282095),t.addScaledVector(n[1],.488603*i),t.addScaledVector(n[2],.488603*r),t.addScaledVector(n[3],.488603*s),t.addScaledVector(n[4],s*i*1.092548),t.addScaledVector(n[5],i*r*1.092548),t.addScaledVector(n[6],.315392*(3*r*r-1)),t.addScaledVector(n[7],s*r*1.092548),t.addScaledVector(n[8],.546274*(s*s-i*i)),t}getIrradianceAt(e,t){const s=e.x,i=e.y,r=e.z,n=this.coefficients;return t.copy(n[0]).multiplyScalar(.886227),t.addScaledVector(n[1],1.023328*i),t.addScaledVector(n[2],1.023328*r),t.addScaledVector(n[3],1.023328*s),t.addScaledVector(n[4],.858086*s*i),t.addScaledVector(n[5],.858086*i*r),t.addScaledVector(n[6],.743125*r*r-.247708),t.addScaledVector(n[7],.858086*s*r),t.addScaledVector(n[8],.429043*(s*s-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let s=0;s<9;s++)this.coefficients[s].addScaledVector(e.coefficients[s],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let s=0;s<9;s++)this.coefficients[s].lerp(e.coefficients[s],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(e,t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].fromArray(e,t+3*i);return this}toArray(e=[],t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].toArray(e,t+3*i);return e}static getBasisAt(e,t){const s=e.x,i=e.y,r=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*r,t[3]=.488603*s,t[4]=1.092548*s*i,t[5]=1.092548*i*r,t[6]=.315392*(3*r*r-1),t[7]=1.092548*s*r,t[8]=.546274*(s*s-i*i)}}class yn extends Hr{constructor(e=new fn,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}const bn=-90;class _n extends Rs{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new an(bn,1,e,t);i.layers=this.layers,this.add(i);const r=new an(bn,1,e,t);r.layers=this.layers,this.add(r);const n=new an(bn,1,e,t);n.layers=this.layers,this.add(n);const a=new an(bn,1,e,t);a.layers=this.layers,this.add(a);const o=new an(bn,1,e,t);o.layers=this.layers,this.add(o);const h=new an(bn,1,e,t);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,a,o]=t;for(const e of t)this.remove(e);if(e===ot)s.up.set(0,1,0),s.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),n.up.set(0,0,1),n.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==ht)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);s.up.set(0,-1,0),s.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),n.up.set(0,0,-1),n.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,n,a,o,h,u]=this.children,l=e.getRenderTarget(),c=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=s.texture.generateMipmaps;s.texture.generateMipmaps=!1;let g=!1;g=!0===e.isWebGLRenderer?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(s,0,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,r),e.setRenderTarget(s,1,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,n),e.setRenderTarget(s,2,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,a),e.setRenderTarget(s,3,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,o),e.setRenderTarget(s,4,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,h),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,u),e.setRenderTarget(l,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class xn extends an{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class vn extends zi{constructor(e,t,s=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=s}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}class Tn{constructor(e,t,s,i){Tn.prototype.isMatrix2=!0,this.elements=[1,0,0,1],void 0!==e&&this.set(e,t,s,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let s=0;s<4;s++)this.elements[s]=e[s+t];return this}set(e,t,s,i){const r=this.elements;return r[0]=e,r[2]=t,r[1]=s,r[3]=i,this}}function Sn(e,t,s,i){const r=function(e){switch(e){case j:case $:return{byteLength:1,components:1};case H:case W:case K:return{byteLength:2,components:1};case Q:case Z:return{byteLength:2,components:4};case X:case q:case Y:return{byteLength:4,components:1};case ee:case te:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(i);switch(s){case 1021:return e*t;case ae:case oe:return e*t/r.components*r.byteLength;case he:case ue:return e*t*2/r.components*r.byteLength;case se:return e*t*3/r.components*r.byteLength;case ie:case le:return e*t*4/r.components*r.byteLength;case ce:case de:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case pe:case me:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case fe:case be:return Math.max(e,16)*Math.max(t,8)/4;case ge:case ye:return Math.max(e,8)*Math.max(t,8)/2;case _e:case xe:case Te:case Se:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case ve:case we:case Me:case Ne:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ee:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Ae:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Ce:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Re:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case Pe:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Be:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Fe:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case De:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case Ie:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case Le:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case Oe:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case Ue:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case ke:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case ze:case 36494:case 36495:return Math.ceil(e/4)*Math.ceil(t/4)*16;case Ve:case Ge:return Math.ceil(e/4)*Math.ceil(t/4)*8;case je:case $e:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${s} format.`)}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:a}})),"undefined"!=typeof window&&(window.__THREE__?yt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=a);const wn=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],Mn=new WeakMap;class Nn{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=wn,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:s,material:i,object:r}=e;if(t={material:this.getMaterialData(i),geometry:{id:s.id,attributes:this.getAttributesData(s.attributes),indexId:s.index?s.index.id:null,indexVersion:s.index?s.index.version:null,drawRange:{start:s.drawRange.start,count:s.drawRange.count}},worldMatrix:r.matrixWorld.clone()},r.center&&(t.center=r.center.clone()),r.morphTargetInfluences&&(t.morphTargetInfluences=r.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:s,height:i}=e.context;t.bufferWidth=s,t.bufferHeight=i}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={id:i.id,version:i.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getMaterialData(e){const t={};for(const s of this.refreshUniforms){const i=e[s];null!=i&&("object"==typeof i&&void 0!==i.clone?!0===i.isTexture?t[s]={id:i.id,version:i.version}:t[s]=i.clone():t[s]=i)}return t}equals(e,t){const{object:s,material:i,geometry:r}=e,n=this.getRenderObjectData(e);if(!0!==n.worldMatrix.equals(s.matrixWorld))return n.worldMatrix.copy(s.matrixWorld),!1;const a=n.material;for(const e in a){const t=a[e],s=i[e];if(void 0!==t.equals){if(!1===t.equals(s))return t.copy(s),!1}else if(!0===s.isTexture){if(t.id!==s.id||t.version!==s.version)return t.id=s.id,t.version=s.version,!1}else if(t!==s)return a[e]=s,!1}if(a.transmission>0){const{width:t,height:s}=e.context;if(n.bufferWidth!==t||n.bufferHeight!==s)return n.bufferWidth=t,n.bufferHeight=s,!1}const o=n.geometry,h=r.attributes,u=o.attributes,l=Object.keys(u),c=Object.keys(h);if(o.id!==r.id)return o.id=r.id,!1;if(l.length!==c.length)return n.geometry.attributes=this.getAttributesData(h),!1;for(const e of l){const t=u[e],s=h[e];if(void 0===s)return delete u[e],!1;if(t.id!==s.id||t.version!==s.version)return t.id=s.id,t.version=s.version,!1}const d=r.index,p=o.indexId,m=o.indexVersion,g=d?d.id:null,f=d?d.version:null;if(p!==g||m!==f)return o.indexId=g,o.indexVersion=f,!1;if(o.drawRange.start!==r.drawRange.start||o.drawRange.count!==r.drawRange.count)return o.drawRange.start=r.drawRange.start,o.drawRange.count=r.drawRange.count,!1;if(n.morphTargetInfluences){let e=!1;for(let t=0;t<n.morphTargetInfluences.length;t++)n.morphTargetInfluences[t]!==s.morphTargetInfluences[t]&&(n.morphTargetInfluences[t]=s.morphTargetInfluences[t],e=!0);if(e)return!1}if(n.lights)for(let e=0;e<t.length;e++)if(n.lights[e].map!==t[e].map)return!1;return n.center&&!1===n.center.equals(s.center)?(n.center.copy(s.center),!0):(null!==e.bundle&&(n.version=e.bundle.version),!0)}getLightsData(e){const t=[];for(const s of e)!0===s.isSpotLight&&null!==s.map&&t.push({map:s.map.version});return t}getLights(e,t){if(Mn.has(e)){const s=Mn.get(e);if(s.renderId===t)return s.lightsData}const s=this.getLightsData(e.getLights());return Mn.set(e,{renderId:t,lightsData:s}),s}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:s}=t;if(this.renderId!==s)return this.renderId=s,!0;const i=!0===e.object.static,r=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(i||r)return!1;const n=this.getLights(e.lightsNode,s);return!0!==this.equals(e,n)}}const En=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];class An{constructor(e=null){this.isStackTrace=!0,this.stack=function(e){const t=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return e.split("\n").map(e=>{const s=e.match(t);if(!s)return null;const i=s[1]||s[2]||"",r=s[3].split("?")[0],n=parseInt(s[4],10),a=parseInt(s[5],10);return{fn:i,file:r.split("/").pop(),line:n,column:a}}).filter(e=>e&&!En.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;return`${e}\n${this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n")}`}}function Cn(e,t=0){let s=3735928559^t,i=1103547991^t;if(e instanceof Array)for(let t,r=0;r<e.length;r++)t=e[r],s=Math.imul(s^t,2654435761),i=Math.imul(i^t,1597334677);else for(let t,r=0;r<e.length;r++)t=e.charCodeAt(r),s=Math.imul(s^t,2654435761),i=Math.imul(i^t,1597334677);return s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(s^s>>>13,3266489909),4294967296*(2097151&i)+(s>>>0)}const Rn=e=>Cn(e),Pn=e=>Cn(e),Bn=(...e)=>Cn(e),Fn=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Dn=new WeakMap;function In(e){return Fn.get(e)}function Ln(e){if(null==e)return null;const t=typeof e;return!0===e.isNode?"node":"number"===t?"float":"boolean"===t?"bool":"string"===t?"string":"function"===t?"shader":!0===e.isVector2?"vec2":!0===e.isVector3?"vec3":!0===e.isVector4?"vec4":!0===e.isMatrix2?"mat2":!0===e.isMatrix3?"mat3":!0===e.isMatrix4?"mat4":!0===e.isColor?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function On(e,...t){const s=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===s?t=[t[0],t[0]]:"vec3"===s?t=[t[0],t[0],t[0]]:"vec4"===s&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new Us(...t):"vec2"===s?new Ft(...t):"vec3"===s?new It(...t):"vec4"===s?new es(...t):"mat2"===s?new Tn(...t):"mat3"===s?new Ut(...t):"mat4"===s?new is(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?(i=t[0],Uint8Array.from(atob(i),e=>e.charCodeAt(0)).buffer):null;var i}function Un(e){let t=Dn.get(e);return void 0===t&&(t={},Dn.set(e,t)),t}const kn="vertex",zn="none",Vn="frame",Gn="render",jn="object",$n="readOnly",Wn="writeOnly",Hn="readWrite",qn=["setup","analyze","generate"],Xn=["fragment","vertex","compute"],Yn=["x","y","z","w"],Kn={analyze:"setup",generate:"analyze"};let Qn=0;class Zn extends vt{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=zn,this.updateBeforeType=zn,this.updateAfterType=zn,this.uuid=Bt.generateUUID(),this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Qn++}),this.stackTrace=null,!0===Zn.captureStackTrace&&(this.stackTrace=new An)}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,Vn)}onRenderUpdate(e){return this.onUpdate(e,Gn)}onObjectUpdate(e){return this.onUpdate(e,jn)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const s of Object.getOwnPropertyNames(this)){const i=this[s];if(!0!==s.startsWith("_")&&!e.has(i))if(!0===Array.isArray(i))for(let e=0;e<i.length;e++){const r=i[e];r&&!0===r.isNode&&t.push({property:s,index:e,childNode:r})}else if(i&&!0===i.isNode)t.push({property:s,childNode:i});else if(i&&Object.getPrototypeOf(i)===Object.prototype)for(const e in i){if(!0===e.startsWith("_"))continue;const r=i[e];r&&!0===r.isNode&&t.push({property:s,index:e,childNode:r})}}return t}getCacheKey(e=!1,t=null){if(!0===(e=e||this.version!==this._cacheKeyVersion)||null===this._cacheKey){null===t&&(t=new Set);const s=[];for(const{property:i,childNode:r}of this._getChildren(t))s.push(Rn(i.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=Bn(Pn(s),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let s=0;for(const e of this.getChildren())t["node"+s++]=e;return t.outputNode||null}analyze(e,t=null){const s=e.increaseUsage(this);if(!0===this.parents){const s=e.getDataFromNode(this,"any");s.stages=s.stages||{},s.stages[e.shaderStage]=s.stages[e.shaderStage]||[],s.stages[e.shaderStage].push(t)}if(1===s){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e,this)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){yt("Abstract function.")}updateAfter(){yt("Abstract function.")}update(){yt("Abstract function.")}before(e){return null===this._beforeNodes&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);if(null!==this._beforeNodes){const s=this._beforeNodes;this._beforeNodes=null;for(const i of s)i.build(e,t);this._beforeNodes=s}const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const r=Kn[e.buildStage];if(r&&!0!==i.buildStages[r]){const t=e.getBuildStage();e.setBuildStage(r),this.build(e),e.setBuildStage(t)}e.addChain(this);let n=null;const a=e.getBuildStage();if("setup"===a){e.addNode(this),this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const s of Object.values(t))if(s&&!0===s.isNode){if(!0===s.parents){const t=e.getNodeProperties(s);t.parents=t.parents||[],t.parents.push(this)}s.build(e)}e.addSequentialNode(this)}n=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(this.generate.length<2){const s=this.getNodeType(e),i=e.getDataFromNode(this);n=i.snippet,void 0===n?void 0===i.generated?(i.generated=!0,n=this.generate(e)||"",i.snippet=n):(yt("Node: Recursion detected.",this),n="/* Recursion detected. */"):void 0!==i.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),n=e.format(n,s,t)}else n=this.generate(e,t)||"";""===n&&null!==t&&"void"!==t&&"OutputType"!==t&&(bt(`TSL: Invalid generated code, expected a "${t}".`),n=e.generateConst(t))}return e.removeChain(this),n}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:r,childNode:n}of t)void 0!==r?(void 0===s[i]&&(s[i]=Number.isInteger(r)?[]:{}),s[i][r]=n.toJSON(e.meta).uuid):s[i]=n.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const r of e.inputNodes[s])i.push(t[r]);this[s]=i}else if("object"==typeof e.inputNodes[s]){const i={};for(const r in e.inputNodes[s]){const n=e.inputNodes[s][r];i[r]=t[n]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:s,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=n(e.textures),s=n(e.images),i=n(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),i.length>0&&(r.nodes=i)}return r}}Zn.captureStackTrace=!1;class Jn extends Zn{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class ea extends Zn{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))null!==s&&e.getTypeLength(t)!==e.getTypeLength(i)||(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),r=s.build(e,i);return e.format(r,i,t)}}class ta extends Zn{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const s=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,s,t);if("void"!==s&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,s),n=e.getVarFromNode(this,null,s),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${r}`,this),i.snippet=r,i.propertyName=a,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class sa extends ta{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,s)=>t+e.getTypeLength(s.getNodeType(e)),0))}generate(e,t){const s=this.getNodeType(e),i=e.getTypeLength(s),r=this.nodes,n=e.getComponentType(s),a=[];let o=0;for(const t of r){if(o>=i){bt(`TSL: Length of parameters exceeds maximum length of function '${s}()' type.`,this.stackTrace);break}let r,h=t.getNodeType(e),u=e.getTypeLength(h);o+u>i&&(bt(`TSL: Length of '${s}()' data exceeds maximum length of output type.`,this.stackTrace),u=i-o,h=e.getTypeFromLength(u)),o+=u,r=t.build(e,h);if(e.getComponentType(h)!==n){const t=e.getTypeFromLength(u,n);r=e.format(r,h,t)}a.push(r)}const h=`${e.getType(s)}( ${a.join(", ")} )`;return e.format(h,s,t)}}const ia=Yn.join("");class ra extends Zn{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(Yn.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let r=null;if(i>1){let n=null;this.getVectorLength()>=i&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=s.build(e,n);r=this.components.length===i&&this.components===ia.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else r=s.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class na extends ta{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,r=this.getNodeType(e),n=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(s.length,n),o=i.build(e,a),h=t.build(e,r),u=e.getTypeLength(r),l=[];for(let e=0;e<u;e++){const t=Yn[e];t===s[0]?(l.push(o),e+=s.length-1):l.push(h+"."+t)}return`${e.getType(r)}( ${l.join(", ")} )`}}class aa extends ta{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:s}=this,i=this.getNodeType(e),r=s.build(e),n=e.getVarFromNode(this),a=e.getPropertyName(n);e.addLineFlowCode(a+" = "+r,this);const o=e.getTypeLength(i),h=[];let u=0;for(let e=0;e<o;e++){const s=Yn[e];s===t[u]?(h.push("1.0 - "+a+"."+s),u++):h.push(a+"."+s)}return`${e.getType(i)}( ${h.join(", ")} )`}}class oa extends Zn{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return null===this.nodeType?Ln(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=Ln(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=function(e){let t="";const s=new Uint8Array(e);for(let e=0;e<s.length;e++)t+=String.fromCharCode(s[e]);return btoa(t)}(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?On(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){yt("Abstract function.")}}const ha=/float|u?int/;class ua extends oa{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const s=this.getNodeType(e);return ha.test(s)&&ha.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class la extends Zn{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return(!this.structNode.isMemberNode||!1!==this.structNode.hasMember(e))&&"void"!==this.structNode.getMemberType(e,this.property)}getNodeType(e){return!1===this.hasMember(e)?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(!1===this.hasMember(e))return"float";const s=this.getNodeType(e);return e.getStructTypeNode(s).getMemberType(e,t)}generate(e){if(!1===this.hasMember(e)){yt(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+"."+this.property}}let ca=null;const da=new Map;function pa(e,t){if(da.has(e))yt(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);da.set(e,t),"assign"!==e&&(Zn.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},Zn.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const ma=e=>(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");Zn.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==ca?ca.assign(this,...e):bt("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new An),this;{const t=da.get("assign");return this.addToStack(t(...e))}},Zn.prototype.toVarIntent=function(){return this},Zn.prototype.get=function(e){return new la(this,e)};const ga={};function fa(e,t,s){ga[e]=ga[t]=ga[s]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new ra(this,e),this._cache[e]=t),t},set(t){this[e].assign(Va(t))}};const i=e.toUpperCase(),r=t.toUpperCase(),n=s.toUpperCase();Zn.prototype["set"+i]=Zn.prototype["set"+r]=Zn.prototype["set"+n]=function(t){const s=ma(e);return new na(this,s,Va(t))},Zn.prototype["flip"+i]=Zn.prototype["flip"+r]=Zn.prototype["flip"+n]=function(){const t=ma(e);return new aa(this,t)}}const ya=["x","y","z","w"],ba=["r","g","b","a"],_a=["s","t","p","q"];for(let e=0;e<4;e++){let t=ya[e],s=ba[e],i=_a[e];fa(t,s,i);for(let r=0;r<4;r++){t=ya[e]+ya[r],s=ba[e]+ba[r],i=_a[e]+_a[r],fa(t,s,i);for(let n=0;n<4;n++){t=ya[e]+ya[r]+ya[n],s=ba[e]+ba[r]+ba[n],i=_a[e]+_a[r]+_a[n],fa(t,s,i);for(let a=0;a<4;a++)t=ya[e]+ya[r]+ya[n]+ya[a],s=ba[e]+ba[r]+ba[n]+ba[a],i=_a[e]+_a[r]+_a[n]+_a[a],fa(t,s,i)}}}for(let e=0;e<32;e++)ga[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Jn(this,new ua(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(Va(t))}};Object.defineProperties(Zn.prototype,ga);const xa=new WeakMap,va=function(e,t=null){for(const s in e)e[s]=Va(e[s],t);return e},Ta=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=Va(e[i],t);return e},Sa=function(e,t=null,s=null,i=null){function r(e){return null!==i?(e=Va(Object.assign(e,i)),!0===i.intent&&(e=e.toVarIntent())):e=Va(e),e}let n,a,o,h=t;function u(t){let s;return s=h?/[a-z]/i.test(h)?h+"()":h:e.type,void 0!==a&&t.length<a?(bt(`TSL: "${s}" parameter length is less than minimum required.`,new An),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(bt(`TSL: "${s}" parameter length exceeds limit.`,new An),t.slice(0,o)):t}return null===t?n=(...t)=>r(new e(...$a(u(t)))):null!==s?(s=Va(s),n=(...i)=>r(new e(t,...$a(u(i)),s))):n=(...s)=>r(new e(t,...$a(u(s)))),n.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),n),n.setName=e=>(h=e,n),n},wa=function(e,...t){return new e(...$a(t))};class Ma extends Zn{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:s}=this,i=e.getNodeProperties(t),r=e.getClosestSubBuild(t.subBuilds)||"",n=r||"default";if(i[n])return i[n];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=r,e.fnCall=this;let h=null;if(t.layout){let i=xa.get(e.constructor);void 0===i&&(i=new WeakMap,xa.set(e.constructor,i));let r=i.get(t);void 0===r&&(r=Va(e.buildFunctionNode(t)),i.set(t,r)),e.addInclude(r);const n=s?function(e){let t;ja(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(s):null;h=Va(r.call(n))}else{const i=new Proxy(e,{get:(e,t,s)=>{let i;return i=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,s),i}}),r=s?function(e){let t=0;return ja(e),new Proxy(e,{get:(s,i,r)=>{let n;if("length"===i)return n=e.length,n;if(Symbol.iterator===i)n=function*(){for(const t of e)yield Va(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const s=e[0];n=void 0===s[i]?s[t++]:Reflect.get(s,i,r)}else e[0]instanceof Zn&&(n=void 0===e[i]?e[t++]:Reflect.get(e,i,r));else n=Reflect.get(s,i,r);n=Va(n)}return n}})}(s):null,n=Array.isArray(s)?s.length>0:null!==s,a=t.jsFunc,o=n||a.length>1?a(r,i):a(i);h=Va(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(i[n]=h),h}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),s=e.getSubBuildOutput(this);return t[s]=t[s]||this.setupOutput(e),t[s].subBuild=e.getClosestSubBuild(this),t[s]}build(e,t=null){let s=null;const i=e.getBuildStage(),r=e.getNodeProperties(this),n=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===i){const t=e.getSubBuildProperty("initialized",this);if(!0!==r[t]&&(r[t]=!0,r[n]=this.getOutputNode(e),r[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const s=e.getDataFromNode(t,"any");s.subBuilds=s.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)s.subBuilds.add(e)}s=r[n]}else"analyze"===i?a.build(e,t):"generate"===i&&(s=a.build(e,t)||"");return e.fnCall=o,s}}class Na extends Zn{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new Ma(this,e)}setup(){return this.call()}}const Ea=[!1,!0],Aa=[0,1,2,3],Ca=[-1,-2],Ra=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],Pa=new Map;for(const e of Ea)Pa.set(e,new ua(e));const Ba=new Map;for(const e of Aa)Ba.set(e,new ua(e,"uint"));const Fa=new Map([...Ba].map(e=>new ua(e.value,"int")));for(const e of Ca)Fa.set(e,new ua(e,"int"));const Da=new Map([...Fa].map(e=>new ua(e.value)));for(const e of Ra)Da.set(e,new ua(e));for(const e of Ra)Da.set(-e,new ua(-e));const Ia={bool:Pa,uint:Ba,ints:Fa,float:Da},La=new Map([...Pa,...Da]),Oa=(e,t)=>La.has(e)?La.get(e):!0===e.isNode?e:new ua(e,t),Ua=function(e,t=null){return(...s)=>{for(const t of s)if(void 0===t)return bt(`TSL: Invalid parameter for the type "${e}".`,new An),new ua(0,e);if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(s=[On(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return Ga(t.get(s[0]));if(1===s.length){const t=Oa(s[0],e);return t.nodeType===e?Ga(t):Ga(new ea(t,e))}const i=s.map(e=>Oa(e));return Ga(new sa(i,e))}},ka=e=>"object"==typeof e&&null!==e?e.value:e;function za(e,t){return new Na(e,t)}const Va=(e,t=null)=>function(e,t=null){const s=Ln(e);return"node"===s?e:null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?Va(Oa(e,t)):"shader"===s?e.isFn?e:Ka(e):e}(e,t),Ga=(e,t=null)=>Va(e,t).toVarIntent(),ja=(e,t=null)=>new va(e,t),$a=(e,t=null)=>new Ta(e,t),Wa=(e,t=null,s=null,i=null)=>new Sa(e,t,s,i),Ha=(e,...t)=>new wa(e,...t),qa=(e,t=null,s=null,i={})=>new Sa(e,t,s,{...i,intent:!0});let Xa=0;class Ya extends Zn{constructor(e,t=null){super();let s=null;null!==t&&("object"==typeof t?s=t.return:("string"==typeof t?s=t:bt("TSL: Invalid layout type.",new An),t=null)),this.shaderNode=new za(e,s),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const s={name:"fn"+Xa++,type:t,inputs:[]};for(const t in e)"return"!==t&&s.inputs.push({name:t,type:e[t]});e=s}return this.shaderNode.setLayout(e),this}getNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return bt('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function Ka(e,t=null){const s=new Ya(e,t);return new Proxy(()=>{},{apply:(e,t,i)=>s.call(...i),get:(e,t,i)=>Reflect.get(s,t,i),set:(e,t,i,r)=>Reflect.set(s,t,i,r)})}const Qa=e=>{ca=e},Za=()=>ca,Ja=(...e)=>ca.If(...e);function eo(e){return ca&&ca.addToStack(e),e}pa("toStack",eo);const to=new Ua("color"),so=new Ua("float",Ia.float),io=new Ua("int",Ia.ints),ro=new Ua("uint",Ia.uint),no=new Ua("bool",Ia.bool),ao=new Ua("vec2"),oo=new Ua("ivec2"),ho=new Ua("uvec2"),uo=new Ua("bvec2"),lo=new Ua("vec3"),co=new Ua("ivec3"),po=new Ua("uvec3"),mo=new Ua("bvec3"),go=new Ua("vec4"),fo=new Ua("ivec4"),yo=new Ua("uvec4"),bo=new Ua("bvec4"),_o=new Ua("mat2"),xo=new Ua("mat3"),vo=new Ua("mat4");pa("toColor",to),pa("toFloat",so),pa("toInt",io),pa("toUint",ro),pa("toBool",no),pa("toVec2",ao),pa("toIVec2",oo),pa("toUVec2",ho),pa("toBVec2",uo),pa("toVec3",lo),pa("toIVec3",co),pa("toUVec3",po),pa("toBVec3",mo),pa("toVec4",go),pa("toIVec4",fo),pa("toUVec4",yo),pa("toBVec4",bo),pa("toMat2",_o),pa("toMat3",xo),pa("toMat4",vo);pa("element",Wa(Jn).setParameterLength(2)),pa("convert",(e,t)=>new ea(Va(e),t)),pa("append",e=>(yt("TSL: .append() has been renamed to .toStack().",new An),eo(e)));class To extends Zn{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return Rn(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const So=(e,t)=>new To(e,t),wo=(e,t)=>new To(e,t,!0),Mo=Ha(To,"vec4","DiffuseColor"),No=Ha(To,"vec3","DiffuseContribution"),Eo=Ha(To,"vec3","EmissiveColor"),Ao=Ha(To,"float","Roughness"),Co=Ha(To,"float","Metalness"),Ro=Ha(To,"float","Clearcoat"),Po=Ha(To,"float","ClearcoatRoughness"),Bo=Ha(To,"vec3","Sheen"),Fo=Ha(To,"float","SheenRoughness"),Do=Ha(To,"float","Iridescence"),Io=Ha(To,"float","IridescenceIOR"),Lo=Ha(To,"float","IridescenceThickness"),Oo=Ha(To,"float","AlphaT"),Uo=Ha(To,"float","Anisotropy"),ko=Ha(To,"vec3","AnisotropyT"),zo=Ha(To,"vec3","AnisotropyB"),Vo=Ha(To,"color","SpecularColor"),Go=Ha(To,"color","SpecularColorBlended"),jo=Ha(To,"float","SpecularF90"),$o=Ha(To,"float","Shininess"),Wo=Ha(To,"vec4","Output"),Ho=Ha(To,"float","dashSize"),qo=Ha(To,"float","gapSize"),Xo=Ha(To,"float","IOR"),Yo=Ha(To,"float","Transmission"),Ko=Ha(To,"float","Thickness"),Qo=Ha(To,"float","AttenuationDistance"),Zo=Ha(To,"color","AttenuationColor"),Jo=Ha(To,"float","Dispersion");class eh extends Zn{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.shared=t,this.order=s,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const th=e=>new eh(e),sh=(e,t=0)=>new eh(e,!0,t),ih=sh("frame"),rh=sh("render"),nh=th("object");class ah extends oa{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=nh}setName(e){return this.name=e,this}label(e){return yt('TSL: "label()" has been deprecated. Use "setName()" instead.',new An),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const s=e(t,this);void 0!==s&&(this.value=s)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const n=r.getInputType(e),a=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let h=o;if("bool"===s){const t=e.getDataFromNode(this);let i=t.propertyName;if(void 0===i){const r=e.getVarFromNode(this,null,"bool");i=e.getPropertyName(r),t.propertyName=i,h=e.format(o,n,s),e.addLineFlowCode(`${i} = ${h}`,this)}h=i}return e.format(h,s,t)}}const oh=(e,t)=>{const s=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e);if(s===e&&(e=On(s)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new ah(e,s)};class hh extends ta{static get type(){return"ArrayNode"}constructor(e,t,s=null){super(e),this.count=t,this.values=s,this.isArrayNode=!0}getArrayCount(){return this.count}getNodeType(e){return null===this.nodeType?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return null===this.nodeType?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}pa("toArray",(e,t)=>((...e)=>{let t;if(1===e.length){const s=e[0];t=new hh(null,s.length,s)}else{const s=e[0],i=e[1];t=new hh(s,i)}return Va(t)})(Array(t).fill(e)));class uh extends ta{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const s=e.getTypeLength(t.node.getNodeType(e));return Yn.join("").slice(0,s)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:s}=this,i=t.getScope();e.getDataFromNode(i).assign=!0;const r=e.getNodeProperties(this);r.sourceNode=s,r.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:s,sourceNode:i}=e.getNodeProperties(this),r=this.needsSplitAssign(e),n=s.build(e),a=s.getNodeType(e),o=i.build(e,a),h=i.getNodeType(e),u=e.getDataFromNode(this);let l;if(!0===u.initialized)"void"!==t&&(l=n);else if(r){const i=e.getVarFromNode(this,null,a),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`,this);const h=s.node,u=h.node.context({assign:!0}).build(e);for(let t=0;t<h.components.length;t++){const s=h.components[t];e.addLineFlowCode(`${u}.${s} = ${r}[ ${t} ]`,this)}"void"!==t&&(l=n)}else l=`${n} = ${o}`,"void"!==t&&"void"!==h||(e.addLineFlowCode(l,this),"void"!==t&&(l=n));return u.initialized=!0,e.format(l,a,t)}}pa("assign",Wa(uh).setParameterLength(2));class lh extends ta{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],s=this.functionNode,i=s.getInputs(e),r=this.parameters,n=(t,s)=>{const i=s.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r)){if(r.length>i.length)bt("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),r.length=i.length;else if(r.length<i.length)for(bt("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(so(0));for(let e=0;e<r.length;e++)t.push(n(r[e],i[e]))}else for(const e of i){const s=r[e.name];void 0!==s?t.push(n(s,e)):(bt(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(n(so(0),e)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}pa("call",(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?$a(t):ja(t[0]),new lh(Va(e),t)));const ch={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class dh extends ta{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new dh(e,t,s);for(let t=0;t<i.length-1;t++)r=new dh(e,r,i[t]);t=r,s=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=s,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(ch[this.op],t)}getNodeType(e,t=null){const s=this.op,i=this.aNode,r=this.bNode,n=i.getNodeType(e),a=r?r.getNodeType(e):null;if("void"===n||"void"===a)return t||"void";if("%"===s)return n;if("~"===s||"&"===s||"|"===s||"^"===s||">>"===s||"<<"===s)return e.getIntegerType(n);if("!"===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s){const t=Math.max(e.getTypeLength(n),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const s=this.op,{aNode:i,bNode:r}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=i.getNodeType(e),o=r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s||"!="===s?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===s||"<<"===s?(a=n,o=e.changeComponentType(o,"uint")):"%"===s?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const h=i.build(e,a),u=r?r.build(e,o):null,l=e.getFunctionOperator(s);if("void"!==t){const i=e.renderer.coordinateSystem===ot;if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s)return i&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${h}, ${u} )`,n,t):e.format(`( ${h} ${s} ${u} )`,n,t);if("%"===s)return e.isInteger(o)?e.format(`( ${h} % ${u} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${h}, ${u} )`,n,t);if("!"===s||"~"===s)return e.format(`(${s}${h})`,a,t);if(l)return e.format(`${l}( ${h}, ${u} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${u} ${s} ${h} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${h} ${s} ${u}`,n,t);{let r=`( ${h} ${s} ${u} )`;return!i&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(r=`all${r}`),e.format(r,n,t)}}if("void"!==a)return l?e.format(`${l}( ${h}, ${u} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${u} ${s} ${h}`,n,t):e.format(`${h} ${s} ${u}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const ph=qa(dh,"+").setParameterLength(2,1/0).setName("add"),mh=qa(dh,"-").setParameterLength(2,1/0).setName("sub"),gh=qa(dh,"*").setParameterLength(2,1/0).setName("mul"),fh=qa(dh,"/").setParameterLength(2,1/0).setName("div"),yh=qa(dh,"%").setParameterLength(2).setName("mod"),bh=qa(dh,"==").setParameterLength(2).setName("equal"),_h=qa(dh,"!=").setParameterLength(2).setName("notEqual"),xh=qa(dh,"<").setParameterLength(2).setName("lessThan"),vh=qa(dh,">").setParameterLength(2).setName("greaterThan"),Th=qa(dh,"<=").setParameterLength(2).setName("lessThanEqual"),Sh=qa(dh,">=").setParameterLength(2).setName("greaterThanEqual"),wh=qa(dh,"&&").setParameterLength(2,1/0).setName("and"),Mh=qa(dh,"||").setParameterLength(2,1/0).setName("or"),Nh=qa(dh,"!").setParameterLength(1).setName("not"),Eh=qa(dh,"^^").setParameterLength(2).setName("xor"),Ah=qa(dh,"&").setParameterLength(2).setName("bitAnd"),Ch=qa(dh,"~").setParameterLength(1).setName("bitNot"),Rh=qa(dh,"|").setParameterLength(2).setName("bitOr"),Ph=qa(dh,"^").setParameterLength(2).setName("bitXor"),Bh=qa(dh,"<<").setParameterLength(2).setName("shiftLeft"),Fh=qa(dh,">>").setParameterLength(2).setName("shiftRight"),Dh=Ka(([e])=>(e.addAssign(1),e)),Ih=Ka(([e])=>(e.subAssign(1),e)),Lh=Ka(([e])=>{const t=io(e).toConst();return e.addAssign(1),t}),Oh=Ka(([e])=>{const t=io(e).toConst();return e.subAssign(1),t});pa("add",ph),pa("sub",mh),pa("mul",gh),pa("div",fh),pa("mod",yh),pa("equal",bh),pa("notEqual",_h),pa("lessThan",xh),pa("greaterThan",vh),pa("lessThanEqual",Th),pa("greaterThanEqual",Sh),pa("and",wh),pa("or",Mh),pa("not",Nh),pa("xor",Eh),pa("bitAnd",Ah),pa("bitNot",Ch),pa("bitOr",Rh),pa("bitXor",Ph),pa("shiftLeft",Bh),pa("shiftRight",Fh),pa("incrementBefore",Dh),pa("decrementBefore",Ih),pa("increment",Lh),pa("decrement",Oh);pa("modInt",(e,t)=>(yt('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new An),yh(io(e),io(t))));class Uh extends ta{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===Uh.MAX||e===Uh.MIN)&&arguments.length>3){let r=new Uh(e,t,s);for(let t=2;t<arguments.length-1;t++)r=new Uh(e,r,arguments[t]);t=r,s=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=s,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s),a=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>a?t:n>a?s:a>r?i:t}getNodeType(e){const t=this.method;return t===Uh.LENGTH||t===Uh.DISTANCE||t===Uh.DOT?"float":t===Uh.CROSS?"vec3":t===Uh.ALL||t===Uh.ANY?"bool":t===Uh.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:s,method:i}=this;let r=null;if(i===Uh.ONE_MINUS)r=mh(1,t);else if(i===Uh.RECIPROCAL)r=fh(1,t);else if(i===Uh.DIFFERENCE)r=ou(mh(t,s));else if(i===Uh.TRANSFORM_DIRECTION){let i=t,n=s;e.isMatrix(i.getNodeType(e))?n=go(lo(n),0):i=go(lo(i),0);const a=gh(i,n).xyz;r=Jh(a)}return null!==r?r:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let s=this.method;const i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,a=this.bNode,o=this.cNode,h=e.renderer.coordinateSystem;if(s===Uh.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);{const u=[];return s===Uh.CROSS?u.push(n.build(e,i),a.build(e,i)):h===ot&&s===Uh.STEP?u.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),a.build(e,r)):h!==ot||s!==Uh.MIN&&s!==Uh.MAX?s===Uh.REFRACT?u.push(n.build(e,r),a.build(e,r),o.build(e,"float")):s===Uh.MIX?u.push(n.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(h===ht&&s===Uh.ATAN&&null!==a&&(s="atan2"),"fragment"===e.shaderStage||s!==Uh.DFDX&&s!==Uh.DFDY||(yt(`TSL: '${s}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),s="/*"+s+"*/"),u.push(n.build(e,r)),null!==a&&u.push(a.build(e,r)),null!==o&&u.push(o.build(e,r))):u.push(n.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)),e.format(`${e.getMethod(s,i)}( ${u.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Uh.ALL="all",Uh.ANY="any",Uh.RADIANS="radians",Uh.DEGREES="degrees",Uh.EXP="exp",Uh.EXP2="exp2",Uh.LOG="log",Uh.LOG2="log2",Uh.SQRT="sqrt",Uh.INVERSE_SQRT="inversesqrt",Uh.FLOOR="floor",Uh.CEIL="ceil",Uh.NORMALIZE="normalize",Uh.FRACT="fract",Uh.SIN="sin",Uh.COS="cos",Uh.TAN="tan",Uh.ASIN="asin",Uh.ACOS="acos",Uh.ATAN="atan",Uh.ABS="abs",Uh.SIGN="sign",Uh.LENGTH="length",Uh.NEGATE="negate",Uh.ONE_MINUS="oneMinus",Uh.DFDX="dFdx",Uh.DFDY="dFdy",Uh.ROUND="round",Uh.RECIPROCAL="reciprocal",Uh.TRUNC="trunc",Uh.FWIDTH="fwidth",Uh.TRANSPOSE="transpose",Uh.DETERMINANT="determinant",Uh.INVERSE="inverse",Uh.EQUALS="equals",Uh.MIN="min",Uh.MAX="max",Uh.STEP="step",Uh.REFLECT="reflect",Uh.DISTANCE="distance",Uh.DIFFERENCE="difference",Uh.DOT="dot",Uh.CROSS="cross",Uh.POW="pow",Uh.TRANSFORM_DIRECTION="transformDirection",Uh.MIX="mix",Uh.CLAMP="clamp",Uh.REFRACT="refract",Uh.SMOOTHSTEP="smoothstep",Uh.FACEFORWARD="faceforward";const kh=so(1e-6),zh=so(Math.PI),Vh=qa(Uh,Uh.ALL).setParameterLength(1),Gh=qa(Uh,Uh.ANY).setParameterLength(1),jh=qa(Uh,Uh.RADIANS).setParameterLength(1),$h=qa(Uh,Uh.DEGREES).setParameterLength(1),Wh=qa(Uh,Uh.EXP).setParameterLength(1),Hh=qa(Uh,Uh.EXP2).setParameterLength(1),qh=qa(Uh,Uh.LOG).setParameterLength(1),Xh=qa(Uh,Uh.LOG2).setParameterLength(1),Yh=qa(Uh,Uh.SQRT).setParameterLength(1),Kh=qa(Uh,Uh.INVERSE_SQRT).setParameterLength(1),Qh=qa(Uh,Uh.FLOOR).setParameterLength(1),Zh=qa(Uh,Uh.CEIL).setParameterLength(1),Jh=qa(Uh,Uh.NORMALIZE).setParameterLength(1),eu=qa(Uh,Uh.FRACT).setParameterLength(1),tu=qa(Uh,Uh.SIN).setParameterLength(1),su=qa(Uh,Uh.COS).setParameterLength(1),iu=qa(Uh,Uh.TAN).setParameterLength(1),ru=qa(Uh,Uh.ASIN).setParameterLength(1),nu=qa(Uh,Uh.ACOS).setParameterLength(1),au=qa(Uh,Uh.ATAN).setParameterLength(1,2),ou=qa(Uh,Uh.ABS).setParameterLength(1),hu=qa(Uh,Uh.SIGN).setParameterLength(1),uu=qa(Uh,Uh.LENGTH).setParameterLength(1),lu=qa(Uh,Uh.NEGATE).setParameterLength(1),cu=qa(Uh,Uh.ONE_MINUS).setParameterLength(1),du=qa(Uh,Uh.DFDX).setParameterLength(1),pu=qa(Uh,Uh.DFDY).setParameterLength(1),mu=qa(Uh,Uh.ROUND).setParameterLength(1),gu=qa(Uh,Uh.RECIPROCAL).setParameterLength(1),fu=qa(Uh,Uh.TRUNC).setParameterLength(1),yu=qa(Uh,Uh.FWIDTH).setParameterLength(1),bu=qa(Uh,Uh.TRANSPOSE).setParameterLength(1),_u=qa(Uh,Uh.DETERMINANT).setParameterLength(1),xu=qa(Uh,Uh.INVERSE).setParameterLength(1),vu=qa(Uh,Uh.MIN).setParameterLength(2,1/0),Tu=qa(Uh,Uh.MAX).setParameterLength(2,1/0),Su=qa(Uh,Uh.STEP).setParameterLength(2),wu=qa(Uh,Uh.REFLECT).setParameterLength(2),Mu=qa(Uh,Uh.DISTANCE).setParameterLength(2),Nu=qa(Uh,Uh.DIFFERENCE).setParameterLength(2),Eu=qa(Uh,Uh.DOT).setParameterLength(2),Au=qa(Uh,Uh.CROSS).setParameterLength(2),Cu=qa(Uh,Uh.POW).setParameterLength(2),Ru=e=>gh(e,e),Pu=e=>gh(e,e,e,e),Bu=qa(Uh,Uh.TRANSFORM_DIRECTION).setParameterLength(2),Fu=e=>Eu(e,e),Du=qa(Uh,Uh.MIX).setParameterLength(3),Iu=(e,t=0,s=1)=>new Uh(Uh.CLAMP,Va(e),Va(t),Va(s)),Lu=e=>Iu(e),Ou=qa(Uh,Uh.REFRACT).setParameterLength(3),Uu=qa(Uh,Uh.SMOOTHSTEP).setParameterLength(3),ku=qa(Uh,Uh.FACEFORWARD).setParameterLength(3),zu=Ka(([e])=>{const t=Eu(e.xy,ao(12.9898,78.233)),s=yh(t,zh);return eu(tu(s).mul(43758.5453))});pa("all",Vh),pa("any",Gh),pa("radians",jh),pa("degrees",$h),pa("exp",Wh),pa("exp2",Hh),pa("log",qh),pa("log2",Xh),pa("sqrt",Yh),pa("inverseSqrt",Kh),pa("floor",Qh),pa("ceil",Zh),pa("normalize",Jh),pa("fract",eu),pa("sin",tu),pa("cos",su),pa("tan",iu),pa("asin",ru),pa("acos",nu),pa("atan",au),pa("abs",ou),pa("sign",hu),pa("length",uu),pa("lengthSq",Fu),pa("negate",lu),pa("oneMinus",cu),pa("dFdx",du),pa("dFdy",pu),pa("round",mu),pa("reciprocal",gu),pa("trunc",fu),pa("fwidth",yu),pa("min",vu),pa("max",Tu),pa("step",(e,t)=>Su(t,e)),pa("reflect",wu),pa("distance",Mu),pa("dot",Eu),pa("cross",Au),pa("pow",Cu),pa("pow2",Ru),pa("pow3",e=>gh(e,e,e)),pa("pow4",Pu),pa("transformDirection",Bu),pa("mix",(e,t,s)=>Du(t,s,e)),pa("clamp",Iu),pa("refract",Ou),pa("smoothstep",(e,t,s)=>Uu(t,s,e)),pa("faceForward",ku),pa("difference",Nu),pa("saturate",Lu),pa("cbrt",e=>gh(hu(e),Cu(ou(e),1/3))),pa("transpose",bu),pa("determinant",_u),pa("inverse",xu),pa("rand",zu);class Vu extends Zn{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const{ifNode:t,elseNode:s}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const i=t.getNodeType(e);if(null!==s){const t=s.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(i))return t}return i}setup(e){const t=this.condNode,s=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,r=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const n=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?s:s.context({nodeBlock:s}),a.elseNode=i?n?i:i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:n,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,h="void"!==t,u=h?So(s).build(e):"";i.nodeProperty=u;const l=r.build(e,"bool");if(e.context.uniformFlow&&null!==a){const i=n.build(e,s),r=a.build(e,s),o=e.getTernary(l,i,r);return e.format(o,s,t)}e.addFlowCode(`\n${e.tab}if ( ${l} ) {\n\n`).addFlowTab();let c=n.build(e,s);if(c&&(h?c=u+" = "+c+";":(c="return "+c+";",null===o&&(yt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,s);t&&(h?t=u+" = "+t+";":(t="return "+t+";",null===o&&(yt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(u,s,t)}}const Gu=Wa(Vu).setParameterLength(2,3);pa("select",Gu);class ju extends Zn{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const s=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(s),i}}const $u=(e=null,t={})=>{let s=e;return null!==s&&!0===s.isNode||(t=s||t,s=null),new ju(s,t)},Wu=(e,t)=>$u(e,{nodeName:t});pa("context",$u),pa("label",function(e,t){return yt('TSL: "label()" has been deprecated. Use "setName()" instead.'),Wu(e,t)}),pa("uniformFlow",e=>$u(e,{uniformFlow:!0})),pa("setName",Wu),pa("builtinShadowContext",(e,t,s)=>function(e,t,s=null){return $u(s,{getShadow:({light:s,shadowColorNode:i})=>t===s?i.mul(e):i})}(t,s,e)),pa("builtinAOContext",(e,t)=>function(e,t=null){return $u(t,{getAO:(t,{material:s})=>!0===s.transparent?t:null!==t?t.mul(e):e})}(t,e));class Hu extends Zn{static get type(){return"VarNode"}constructor(e,t=null,s=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=s,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const s=t.getBaseStack();e?s.addToStackBefore(this):s.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:s,readOnly:i}=this,{renderer:r}=e,n=!0===r.backend.isWebGPUBackend;let a=!1,o=!1;i&&(a=e.isDeterministic(t),o=n?i:a);const h=this.getNodeType(e);if("void"==h){!0!==this.isIntent(e)&&bt('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const u=e.getVectorType(h),l=t.build(e,u),c=e.getVarFromNode(this,s,u,void 0,o),d=e.getPropertyName(c);let p=d;if(o)if(n)p=a?`const ${d}`:`let ${d}`;else{const s=t.getArrayCount(e);p=`const ${e.getVar(c.type,d,s)}`}return e.addLineFlowCode(`${p} = ${l}`,this),d}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const qu=Wa(Hu);pa("toVar",(e,t=null)=>qu(e,t).toStack()),pa("toConst",(e,t=null)=>qu(e,t,!0).toStack()),pa("toVarIntent",e=>qu(e).setIntent(!0).toStack());class Xu extends Zn{static get type(){return"SubBuild"}constructor(e,t,s=null){super(s),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const s=this.node.build(e,...t);return e.removeSubBuild(),s}}const Yu=(e,t,s=null)=>new Xu(Va(e),t,s);class Ku extends Zn{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=Yu(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(void 0===s){const i=this.name,r=this.getNodeType(e),n=this.interpolationType,a=this.interpolationSampling;t.varying=s=e.getVaryingFromNode(this,i,r,n,a),t.node=Yu(this.node,"VERTEX")}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(kn,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(kn,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),s=e.getNodeProperties(this),i=this.setupVarying(e);if(void 0===s[t]){const r=this.getNodeType(e),n=e.getPropertyName(i,kn);e.flowNodeFromShaderStage(kn,s.node,r,n),s[t]=n}return e.getPropertyName(i)}}const Qu=Wa(Ku).setParameterLength(1,2);pa("toVarying",Qu),pa("toVertexStage",e=>Qu(e));const Zu=Ka(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return Du(t,s,i)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Ju=Ka(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return Du(t,s,i)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),el="WorkingColorSpace";class tl extends ta{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}resolveColorSpace(e,t){return t===el?jt.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,s=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let r=t;return!1!==jt.enabled&&s!==i&&s&&i?(jt.getTransfer(s)===Ye&&(r=go(Zu(r.rgb),r.a)),jt.getPrimaries(s)!==jt.getPrimaries(i)&&(r=go(xo(jt._getMatrix(new Ut,s,i)).mul(r.rgb),r.a)),jt.getTransfer(i)===Ye&&(r=go(Ju(r.rgb),r.a)),r):r}}const sl=(e,t)=>new tl(Va(e),t,el);pa("workingToColorSpace",(e,t)=>new tl(Va(e),el,t)),pa("colorSpaceToWorking",sl);let il=class extends Jn{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class rl extends Zn{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=jn}setGroup(e){return this.group=e,this}element(e){return new il(this,Va(e))}setNodeType(e){const t=oh(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;e<t.length;e++)s=s[t[e]];return s}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}class nl extends rl{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(rh)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const al=(e,t,s=null)=>new nl(e,t,s);class ol extends ta{static get type(){return"ToneMappingNode"}constructor(e,t=hl,s=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return Bn(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,s=this._toneMapping;if(0===s)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(s);return null!==r?i=go(r(t.rgb,this.exposureNode),t.a):(bt("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const hl=al("toneMappingExposure","float");pa("toneMapping",(e,t,s)=>((e,t,s)=>new ol(e,Va(t),Va(s)))(t,s,e));const ul=new WeakMap;function ll(e,t){let s=ul.get(e);return void 0===s&&(s=new zi(e,t),ul.set(e,s)),s}class cl extends oa{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=nt,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),s=e.getTypeLength(t),i=this.value,r=this.bufferStride||s,n=this.bufferOffset;let a;a=!0===i.isInterleavedBuffer?i:!0===i.isBufferAttribute?ll(i.array,r):ll(i,r);const o=new Gi(a,s,n);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=Qu(this).build(e,t)}return r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function dl(e,t=null,s=0,i=0,r=35044,n=!1){return"mat3"===t||null===t&&9===e.itemSize?xo(new cl(e,"vec3",9,0).setUsage(r).setInstanced(n),new cl(e,"vec3",9,3).setUsage(r).setInstanced(n),new cl(e,"vec3",9,6).setUsage(r).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?vo(new cl(e,"vec4",16,0).setUsage(r).setInstanced(n),new cl(e,"vec4",16,4).setUsage(r).setInstanced(n),new cl(e,"vec4",16,8).setUsage(r).setInstanced(n),new cl(e,"vec4",16,12).setUsage(r).setInstanced(n)):new cl(e,t,s,i).setUsage(r)}const pl=(e,t=null,s=0,i=0)=>dl(e,t,s,i),ml=(e,t=null,s=0,i=0)=>dl(e,t,s,i,nt,!0),gl=(e,t=null,s=0,i=0)=>dl(e,t,s,i,at,!0);pa("toAttribute",e=>pl(e.value));class fl extends Zn{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.version=1,this.name="",this.updateBeforeType=jn,this.onInitFunction=null}setCount(e){return this.count=e,this}getCount(){return this.count}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return yt('TSL: "label()" has been deprecated. Use "setName()" instead.',new An),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:s}=e;if("compute"===s){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}else{const s=e.getNodeProperties(this).outputComputeNode;if(s)return s.build(e,t)}}}const yl=(e,t=[64])=>{(0===t.length||t.length>3)&&bt("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new An);for(let e=0;e<t.length;e++){const s=t[e];("number"!=typeof s||s<=0||!Number.isInteger(s))&&bt(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`,new An)}for(;t.length<3;)t.push(1);return new fl(Va(e),t)};pa("compute",(e,t,s)=>yl(e,s).setCount(t)),pa("computeKernel",yl);class bl extends Zn{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}getNodeType(e){const t=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(s),r}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const _l=e=>new bl(Va(e));pa("cache",function(e,t=!0){return yt('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),_l(e).setParent(t)}),pa("isolate",_l);class xl extends Zn{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}pa("bypass",Wa(xl).setParameterLength(2));class vl extends Zn{static get type(){return"RemapNode"}constructor(e,t,s,i=so(0),r=so(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:i,outHighNode:r,doClamp:n}=this;let a=e.sub(t).div(s.sub(t));return!0===n&&(a=a.clamp()),a.mul(r.sub(i)).add(i)}}const Tl=Wa(vl,null,null,{doClamp:!1}).setParameterLength(3,5),Sl=Wa(vl).setParameterLength(3,5);pa("remap",Tl),pa("remapClamp",Sl);class wl extends Zn{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if("void"!==s)return e.format(i,s,t);e.addLineFlowCode(i,this)}}const Ml=Wa(wl).setParameterLength(1,2);pa("discard",e=>(e?Gu(e,Ml("discard")):Ml("discard")).toStack());class Nl extends ta{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=s,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const s=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||We;return 0!==s&&(t=t.toneMapping(s)),i!==We&&i!==jt.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}pa("renderOutput",(e,t=null,s=null)=>new Nl(Va(e),t,s));class El extends ta{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,s=this.node.build(e);if(null!==t)t(e,s);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(t.length);let r="";r+="// #"+t+"#\n",r+=e.flow.code.replace(/^\t/gm,"")+"\n",r+="/* ... */ "+s+" /* ... */\n",r+="// #"+i+"#\n",gt(r)}return s}}pa("debug",(e,t=null)=>new El(Va(e),t).toStack());class Al{constructor(){this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class Cl extends Zn{static get type(){return"InspectorNode"}constructor(e,t="",s=null){super(),this.node=e,this.name=t,this.callback=s,this.updateType=Vn,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}getNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return!0===e.context.inspector&&null!==this.callback&&(t=this.callback(t)),!0!==e.renderer.backend.isWebGPUBackend&&e.renderer.inspector.constructor!==Al&&_t('TSL: ".toInspector()" is only available with WebGPU.'),t}}pa("toInspector",function(e,t="",s=null){return(e=Va(e)).before(new Cl(e,t,s))});class Rl extends Zn{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const i=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),n=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(n.name,r,s);return Qu(this).build(e,s)}return yt(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(s)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Pl=(e,t=null)=>new Rl(e,t),Bl=(e=0)=>Pl("uv"+(e>0?e:""),"vec2");class Fl extends Zn{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const Dl=Wa(Fl).setParameterLength(1,2);class Il extends ah{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Vn}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&void 0!==s.width){const{width:e,height:t}=s;this.value=Math.log2(Math.max(e,t))}}}const Ll=Wa(Il).setParameterLength(1);class Ol extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const Ul=new Jt;class kl extends ah{static get type(){return"TextureNode"}constructor(e=Ul,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=zn,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===X?"uvec4":this.value.type===q?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Bl(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=oh(this.value.matrix)),this._matrixUniform.mul(lo(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=oh(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(io(Dl(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const s=this.value;if(!s||!0!==s.isTexture)throw new Ol("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const i=Ka(()=>{let t=this.uvNode;return null!==t&&!0!==e.context.forceUVContext||!e.context.getUV||(t=e.context.getUV(this,e)),t||(t=this.getDefaultUV()),!0===this.updateMatrix&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=null!==this._matrixUniform||null!==this._flipYUniform?jn:zn,t})();let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this));let n=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(ct))n=this.compareNode;else{const e=s.compareFunction;null===e||513===e||e===et||e===tt||e===it?a=this.compareNode:(n=this.compareNode,_t('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=n,t.compareStepNode=a,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,s,i,r,n,a,o,h){const u=this.value;let l;return l=r?e.generateTextureBias(u,t,s,r,n,h):o?e.generateTextureGrad(u,t,s,o,n,h):a?e.generateTextureCompare(u,t,s,a,n,h):!1===this.sampler?e.generateTextureLoad(u,t,s,i,n,h):i?e.generateTextureLevel(u,t,s,i,n,h):e.generateTexture(u,t,s,n,h),l}generate(e,t){const s=this.value,i=e.getNodeProperties(this),r=super.generate(e,"property");if(/^sampler/.test(t))return r+"_sampler";if(e.isReference(t))return r;{const n=e.getDataFromNode(this),a=this.getNodeType(e);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:h,biasNode:u,compareNode:l,compareStepNode:c,depthNode:d,gradNode:p,offsetNode:m}=i,g=this.generateUV(e,t),f=h?h.build(e,"float"):null,y=u?u.build(e,"float"):null,b=d?d.build(e,"int"):null,_=l?l.build(e,"float"):null,x=c?c.build(e,"float"):null,v=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,T=m?this.generateOffset(e,m):null,S=e.getVarFromNode(this);o=e.getPropertyName(S);let w=this.generateSnippet(e,r,g,f,y,b,_,v,T);if(null!==x){const t=s.compareFunction;w=t===tt||t===it?Su(Ml(w,a),Ml(x,"float")).build(e,a):Su(Ml(x,"float"),Ml(w,a)).build(e,a)}e.addLineFlowCode(`${o} = ${w}`,this),n.snippet=w,n.propertyName=o}let h=o;return e.needsToWorkingColorSpace(s)&&(h=sl(Ml(h,a),s.colorSpace).setup(e).build(e,a)),e.format(h,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=Va(e),t.referenceNode=this.getBase(),Va(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=Va(e).mul(Ll(t)),t.referenceNode=this.getBase();const s=t.value;return!1===t.generateMipmaps&&(s&&!1===s.generateMipmaps||s.minFilter===O||s.magFilter===O)&&(yt("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Va(t)}level(e){const t=this.clone();return t.levelNode=Va(e),t.referenceNode=this.getBase(),Va(t)}size(e){return Dl(this,e)}bias(e){const t=this.clone();return t.biasNode=Va(e),t.referenceNode=this.getBase(),Va(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=Va(e),t.referenceNode=this.getBase(),Va(t)}grad(e,t){const s=this.clone();return s.gradNode=[Va(e),Va(t)],s.referenceNode=this.getBase(),Va(s)}depth(e){const t=this.clone();return t.depthNode=Va(e),t.referenceNode=this.getBase(),Va(t)}offset(e){const t=this.clone();return t.offsetNode=Va(e),t.referenceNode=this.getBase(),Va(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix();const s=this._flipYUniform;null!==s&&(s.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const zl=Wa(kl).setParameterLength(1,4).setName("texture"),Vl=(e=Ul,t=null,s=null,i=null)=>{let r;return e&&!0===e.isTextureNode?(r=Va(e.clone()),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=Va(t)),null!==s&&(r.levelNode=Va(s)),null!==i&&(r.biasNode=Va(i))):r=zl(e,t,s,i),r},Gl=(...e)=>Vl(...e).setSampler(!1);class jl extends ah{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const $l=(e,t,s)=>new jl(e,t,s);class Wl extends Jn{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType(),i=this.node.getPaddedType();return e.format(t,i,s)}}class Hl extends jl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ln(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Gn,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,s=this.elementType;if("float"===s||"int"===s||"uint"===s)for(let s=0;s<e.length;s++){t[4*s]=e[s]}else if("color"===s)for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.r,t[i+1]=r.g,t[i+2]=r.b||0}else if("mat2"===s)for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+3]=r.elements[3]}else if("mat3"===s)for(let s=0;s<e.length;s++){const i=16*s,r=e[s];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+4]=r.elements[3],t[i+5]=r.elements[4],t[i+6]=r.elements[5],t[i+8]=r.elements[6],t[i+9]=r.elements[7],t[i+10]=r.elements[8],t[i+15]=1}else if("mat4"===s)for(let s=0;s<e.length;s++){const i=16*s,r=e[s];for(let e=0;e<r.elements.length;e++)t[i+e]=r.elements[e]}else for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.x,t[i+1]=r.y,t[i+2]=r.z||0,t[i+3]=r.w||0}}setup(e){const t=this.array.length,s=this.elementType;let i=Float32Array;const r=this.paddedType,n=e.getTypeLength(r);return"i"===s.charAt(0)&&(i=Int32Array),"u"===s.charAt(0)&&(i=Uint32Array),this.value=new i(t*n),this.bufferCount=t,this.bufferType=r,this.update(),super.setup(e)}element(e){return new Wl(this,Va(e))}}const ql=(e,t)=>new Hl(e,t);const Xl=Wa(class extends Zn{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let Yl,Kl;class Ql extends Zn{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===Ql.DPR?"float":this.scope===Ql.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=zn;return this.scope!==Ql.SIZE&&this.scope!==Ql.VIEWPORT&&this.scope!==Ql.DPR||(e=Gn),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Ql.VIEWPORT?null!==t?Kl.copy(t.viewport):(e.getViewport(Kl),Kl.multiplyScalar(e.getPixelRatio())):this.scope===Ql.DPR?this._output.value=e.getPixelRatio():null!==t?(Yl.width=t.width,Yl.height=t.height):e.getDrawingBufferSize(Yl)}setup(){const e=this.scope;let t=null;return t=e===Ql.SIZE?oh(Yl||(Yl=new Ft)):e===Ql.VIEWPORT?oh(Kl||(Kl=new es)):e===Ql.DPR?oh(1):ao(tc.div(ec)),this._output=t,t}generate(e){if(this.scope===Ql.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(ec).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}Ql.COORDINATE="coordinate",Ql.VIEWPORT="viewport",Ql.SIZE="size",Ql.UV="uv",Ql.DPR="dpr";const Zl=Ha(Ql,Ql.DPR),Jl=Ha(Ql,Ql.UV),ec=Ha(Ql,Ql.SIZE),tc=Ha(Ql,Ql.COORDINATE),sc=Ha(Ql,Ql.VIEWPORT),ic=sc.zw;sc.xy;let rc=null,nc=null,ac=null,oc=null,hc=null,uc=null,lc=null,cc=null;const dc=oh(0,"uint").setName("u_cameraIndex").setGroup(sh("cameraIndex")).toVarying("v_cameraIndex"),pc=oh("float").setName("cameraNear").setGroup(rh).onRenderUpdate(({camera:e})=>e.near),mc=oh("float").setName("cameraFar").setGroup(rh).onRenderUpdate(({camera:e})=>e.far),gc=Ka(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrix);null===nc?nc=ql(s).setGroup(rh).setName("cameraProjectionMatrices"):nc.array=s,t=nc.element(e.isMultiViewCamera?Xl("gl_ViewID_OVR"):dc).toConst("cameraProjectionMatrix")}else null===rc&&(rc=oh(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(rh).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=rc;return t}).once()(),fc=Ka(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrixInverse);null===oc?oc=ql(s).setGroup(rh).setName("cameraProjectionMatricesInverse"):oc.array=s,t=oc.element(e.isMultiViewCamera?Xl("gl_ViewID_OVR"):dc).toConst("cameraProjectionMatrixInverse")}else null===ac&&(ac=oh(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(rh).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=ac;return t}).once()(),yc=Ka(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorldInverse);null===uc?uc=ql(s).setGroup(rh).setName("cameraViewMatrices"):uc.array=s,t=uc.element(e.isMultiViewCamera?Xl("gl_ViewID_OVR"):dc).toConst("cameraViewMatrix")}else null===hc&&(hc=oh(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(rh).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=hc;return t}).once()(),bc=Ka(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(let t=0,i=e.cameras.length;t<i;t++)s.push(new It);null===cc?cc=ql(s).setGroup(rh).setName("cameraPositions").onRenderUpdate(({camera:e},t)=>{const s=e.cameras,i=t.array;for(let e=0,t=s.length;e<t;e++)i[e].setFromMatrixPosition(s[e].matrixWorld)}):cc.array=s,t=cc.element(e.isMultiViewCamera?Xl("gl_ViewID_OVR"):dc).toConst("cameraPosition")}else null===lc&&(lc=oh(new It).setName("cameraPosition").setGroup(rh).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),t=lc;return t}).once()(),_c=new Pi;class xc extends Zn{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=jn,this.uniformNode=new ah(null)}getNodeType(){const e=this.scope;return e===xc.WORLD_MATRIX?"mat4":e===xc.POSITION||e===xc.VIEW_POSITION||e===xc.DIRECTION||e===xc.SCALE?"vec3":e===xc.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===xc.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===xc.POSITION)s.value=s.value||new It,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===xc.SCALE)s.value=s.value||new It,s.value.setFromMatrixScale(t.matrixWorld);else if(i===xc.DIRECTION)s.value=s.value||new It,t.getWorldDirection(s.value);else if(i===xc.VIEW_POSITION){const i=e.camera;s.value=s.value||new It,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===xc.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),_c.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),s.value=_c.radius}}generate(e){const t=this.scope;return t===xc.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===xc.POSITION||t===xc.VIEW_POSITION||t===xc.DIRECTION||t===xc.SCALE?this.uniformNode.nodeType="vec3":t===xc.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}xc.WORLD_MATRIX="worldMatrix",xc.POSITION="position",xc.SCALE="scale",xc.VIEW_POSITION="viewPosition",xc.DIRECTION="direction",xc.RADIUS="radius";class vc extends xc{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Tc=Ha(vc,vc.WORLD_MATRIX),Sc=oh(new Ut).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),wc=Ka(e=>e.context.modelViewMatrix||Mc).once()().toVar("modelViewMatrix"),Mc=yc.mul(Tc),Nc=Ka(e=>(e.context.isHighPrecisionModelViewMatrix=!0,oh("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),Ec=Ka(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return oh("mat3").onObjectUpdate(({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),Ac=Ka(e=>"fragment"!==e.shaderStage?(_t("TSL: `clipSpace` is only available in fragment stage."),go()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),Cc=Pl("position","vec3"),Rc=Cc.toVarying("positionLocal"),Pc=Cc.toVarying("positionPrevious"),Bc=Ka(e=>Tc.mul(Rc).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Fc=Ka(()=>Rc.transformDirection(Tc).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Dc=Ka(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=fc.mul(Ac);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),Ic=Ka(e=>{let t;return t=e.camera.isOrthographicCamera?lo(0,0,1):Dc.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class Lc extends Zn{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return 1===t.side?"false":e.getFrontFacing()}}const Oc=so(Ha(Lc)).mul(2).sub(1),Uc=Ka(([e],{material:t})=>{const s=t.side;return 1===s?e=e.mul(-1):2===s&&(e=e.mul(Oc)),e}),kc=Pl("normal","vec3"),zc=Ka(e=>!1===e.geometry.hasAttribute("normal")?(yt('TSL: Vertex attribute "normal" not found on geometry.'),lo(0,1,0)):kc,"vec3").once()().toVar("normalLocal"),Vc=Dc.dFdx().cross(Dc.dFdy()).normalize().toVar("normalFlat"),Gc=Ka(e=>{let t;return t=e.isFlatShading()?Vc:Xc(zc).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),jc=Ka(e=>{let t=Gc.transformDirection(yc);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),$c=Ka(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=Gc,!0!==e.isFlatShading()&&(t=Uc(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Wc=$c.transformDirection(yc).toVar("normalWorld"),Hc=Ka(({subBuildFn:e,context:t})=>{let s;return s="NORMAL"===e||"VERTEX"===e?$c:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),s},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),qc=Ka(([e,t=Tc])=>{const s=xo(t),i=e.div(lo(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz}),Xc=Ka(([e],t)=>{const s=t.context.modelNormalViewMatrix;if(s)return s.transformDirection(e);const i=Sc.mul(e);return yc.transformDirection(i)});Ka(()=>(yt('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),$c)).once(["NORMAL","VERTEX"])(),Ka(()=>(yt('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Wc)).once(["NORMAL","VERTEX"])(),Ka(()=>(yt('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Hc)).once(["NORMAL","VERTEX"])();const Yc=new ps,Kc=new is,Qc=oh(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Zc=oh(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Jc=oh(new is).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const s=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return s?(Yc.copy(s),Kc.makeRotationFromEuler(Yc)):Kc.identity(),Kc}),ed=Ic.negate().reflect($c),td=Ic.negate().refract($c,Qc),sd=ed.transformDirection(yc).toVar("reflectVector"),id=td.transformDirection(yc).toVar("reflectVector"),rd=new Rr;class nd extends kl{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===B?sd:e.mapping===F?id:(bt('CubeTextureNode: Mapping "%s" not supported.',e.mapping),lo(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return!0===s.isDepthTexture?e.renderer.coordinateSystem===ht?lo(t.x,t.y.negate(),t.z):t:(e.renderer.coordinateSystem!==ht&&s.isRenderTargetTexture||(t=lo(t.x.negate(),t.yz)),Jc.mul(t))}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const ad=Wa(nd).setParameterLength(1,4).setName("cubeTexture"),od=(e=rd,t=null,s=null,i=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=Va(e.clone()),r.referenceNode=e,null!==t&&(r.uvNode=Va(t)),null!==s&&(r.levelNode=Va(s)),null!==i&&(r.biasNode=Va(i))):r=ad(e,t,s,i),r};class hd extends Jn{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}}class ud extends Zn{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=jn}element(e){return new hd(this,Va(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return yt('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?$l(null,e,this.count):Array.isArray(this.getValueFromReference())?ql(null,e):"texture"===e?Vl(null):"cubeTexture"===e?od(null):oh(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;e<t.length;e++)s=s[t[e]];return s}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const ld=(e,t,s)=>new ud(e,t,s),cd=(e,t,s,i)=>new ud(e,t,i,s);class dd extends ud{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const pd=(e,t,s=null)=>new dd(e,t,s),md=Bl(),gd=Dc.dFdx(),fd=Dc.dFdy(),yd=md.dFdx(),bd=md.dFdy(),_d=$c,xd=fd.cross(_d),vd=_d.cross(gd),Td=xd.mul(yd.x).add(vd.mul(bd.x)),Sd=xd.mul(yd.y).add(vd.mul(bd.y)),wd=Td.dot(Td).max(Sd.dot(Sd)),Md=wd.equal(0).select(0,wd.inverseSqrt()),Nd=Td.mul(Md).toVar("tangentViewFrame"),Ed=Sd.mul(Md).toVar("bitangentViewFrame"),Ad=Pl("tangent","vec4"),Cd=Ad.xyz.toVar("tangentLocal"),Rd=Ka(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?wc.mul(go(Cd,0)).xyz.toVarying("v_tangentView").normalize():Nd,!0!==e.isFlatShading()&&(t=Uc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),Pd=Ka(([e,t],s)=>{let i=e.mul(Ad.w).xyz;return"NORMAL"===s.subBuildFn&&!0!==s.isFlatShading()&&(i=i.toVarying(t)),i}).once(["NORMAL"]),Bd=xo(Rd,Ka(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Pd($c.cross(Rd),"v_bitangentView").normalize():Ed,!0!==e.isFlatShading()&&(t=Uc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),$c).toVar("TBNViewMatrix"),Fd=Ka(()=>{let e=zo.cross(Ic);return e=e.cross(zo).normalize(),e=Du(e,$c,Uo.mul(Ao.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),Dd=e=>lo(e,Yh(Lu(so(1).sub(Eu(e,e)))));class Id extends ta{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=""}setup(e){const{normalMapType:t,scaleNode:s,unpackNormalMode:i}=this;let r=this.node.mul(2).sub(1);if(0===t?"rg"===i?r=Dd(r.xy):"ga"===i?r=Dd(r.yw):""!==i&&console.error(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):""!==i&&console.error(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),null!==s){let t=s;!0===e.isFlatShading()&&(t=Uc(t)),r=lo(r.xy.mul(t),r.z)}let n=null;return 1===t?n=Xc(r):0===t?n=Bd.mul(r).normalize():(bt(`NodeMaterial: Unsupported normal map type: ${t}`),n=$c),n}}const Ld=Wa(Id).setParameterLength(1,2),Od=Ka(({textureNode:e,bumpScale:t})=>{const s=t=>e.isolate().context({getUV:e=>t(e.uvNode||Bl()),forceUVContext:!0}),i=so(s(e=>e));return ao(so(s(e=>e.add(e.dFdx()))).sub(i),so(s(e=>e.add(e.dFdy()))).sub(i)).mul(t)}),Ud=Ka(e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,a=t.dFdy().normalize().cross(n),o=n.cross(r),h=r.dot(a).mul(Oc),u=h.sign().mul(i.x.mul(a).add(i.y.mul(o)));return h.abs().mul(s).sub(u).normalize()});class kd extends ta{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Od({textureNode:this.textureNode,bumpScale:e});return Ud({surf_pos:Dc,surf_norm:$c,dHdxy:t})}}const zd=Wa(kd).setParameterLength(1,2),Vd=new Map;class Gd extends Zn{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=Vd.get(e);return void 0===s&&(s=pd(e,t),Vd.set(e,s)),s}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,s=this.scope;let i=null;if(s===Gd.COLOR){const e=void 0!==t.color?this.getColor(s):lo();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===Gd.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===Gd.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:so(1);else if(s===Gd.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(s).a):e}else if(s===Gd.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===Gd.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===Gd.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===Gd.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(s)):r}else if(s===Gd.NORMAL)t.normalMap?(i=Ld(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,t.normalMap.format!=he&&t.normalMap.format!=je&&t.normalMap.format!=we||(i.unpackNormalMode="rg")):i=t.bumpMap?zd(this.getTexture("bump").r,this.getFloat("bumpScale")):$c;else if(s===Gd.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Gd.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Gd.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?Ld(this.getTexture(s),this.getCache(s+"Scale","vec2")):$c;else if(s===Gd.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(s===Gd.SHEEN_ROUGHNESS){const e=this.getFloat(s);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,i=i.clamp(1e-4,1)}else if(s===Gd.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=_o(Mp.x,Mp.y,Mp.y.negate(),Mp.x).mul(e.rg.mul(2).sub(ao(1)).normalize().mul(e.b))}else i=Mp;else if(s===Gd.IRIDESCENCE_THICKNESS){const e=ld("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=ld("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===Gd.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===Gd.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===Gd.IOR)i=this.getFloat(s);else if(s===Gd.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===Gd.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(s===Gd.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):so(0);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}Gd.ALPHA_TEST="alphaTest",Gd.COLOR="color",Gd.OPACITY="opacity",Gd.SHININESS="shininess",Gd.SPECULAR="specular",Gd.SPECULAR_STRENGTH="specularStrength",Gd.SPECULAR_INTENSITY="specularIntensity",Gd.SPECULAR_COLOR="specularColor",Gd.REFLECTIVITY="reflectivity",Gd.ROUGHNESS="roughness",Gd.METALNESS="metalness",Gd.NORMAL="normal",Gd.CLEARCOAT="clearcoat",Gd.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Gd.CLEARCOAT_NORMAL="clearcoatNormal",Gd.EMISSIVE="emissive",Gd.ROTATION="rotation",Gd.SHEEN="sheen",Gd.SHEEN_ROUGHNESS="sheenRoughness",Gd.ANISOTROPY="anisotropy",Gd.IRIDESCENCE="iridescence",Gd.IRIDESCENCE_IOR="iridescenceIOR",Gd.IRIDESCENCE_THICKNESS="iridescenceThickness",Gd.IOR="ior",Gd.TRANSMISSION="transmission",Gd.THICKNESS="thickness",Gd.ATTENUATION_DISTANCE="attenuationDistance",Gd.ATTENUATION_COLOR="attenuationColor",Gd.LINE_SCALE="scale",Gd.LINE_DASH_SIZE="dashSize",Gd.LINE_GAP_SIZE="gapSize",Gd.LINE_WIDTH="linewidth",Gd.LINE_DASH_OFFSET="dashOffset",Gd.POINT_SIZE="size",Gd.DISPERSION="dispersion",Gd.LIGHT_MAP="light",Gd.AO="ao";const jd=Ha(Gd,Gd.ALPHA_TEST),$d=Ha(Gd,Gd.COLOR),Wd=Ha(Gd,Gd.SHININESS),Hd=Ha(Gd,Gd.EMISSIVE),qd=Ha(Gd,Gd.OPACITY),Xd=Ha(Gd,Gd.SPECULAR),Yd=Ha(Gd,Gd.SPECULAR_INTENSITY),Kd=Ha(Gd,Gd.SPECULAR_COLOR),Qd=Ha(Gd,Gd.SPECULAR_STRENGTH),Zd=Ha(Gd,Gd.REFLECTIVITY),Jd=Ha(Gd,Gd.ROUGHNESS),ep=Ha(Gd,Gd.METALNESS),tp=Ha(Gd,Gd.NORMAL),sp=Ha(Gd,Gd.CLEARCOAT),ip=Ha(Gd,Gd.CLEARCOAT_ROUGHNESS),rp=Ha(Gd,Gd.CLEARCOAT_NORMAL),np=Ha(Gd,Gd.ROTATION),ap=Ha(Gd,Gd.SHEEN),op=Ha(Gd,Gd.SHEEN_ROUGHNESS),hp=Ha(Gd,Gd.ANISOTROPY),up=Ha(Gd,Gd.IRIDESCENCE),lp=Ha(Gd,Gd.IRIDESCENCE_IOR),cp=Ha(Gd,Gd.IRIDESCENCE_THICKNESS),dp=Ha(Gd,Gd.TRANSMISSION),pp=Ha(Gd,Gd.THICKNESS),mp=Ha(Gd,Gd.IOR),gp=Ha(Gd,Gd.ATTENUATION_DISTANCE),fp=Ha(Gd,Gd.ATTENUATION_COLOR),yp=Ha(Gd,Gd.LINE_SCALE),bp=Ha(Gd,Gd.LINE_DASH_SIZE),_p=Ha(Gd,Gd.LINE_GAP_SIZE);Gd.LINE_WIDTH;const xp=Ha(Gd,Gd.LINE_DASH_OFFSET),vp=Ha(Gd,Gd.POINT_SIZE),Tp=Ha(Gd,Gd.DISPERSION),Sp=Ha(Gd,Gd.LIGHT_MAP),wp=Ha(Gd,Gd.AO),Mp=oh(new Ft).onReference(function(e){return e.material}).onRenderUpdate(function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))}),Np=Ka(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class Ep extends Jn{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const s=this.storageBufferNode.structTypeNode;return s?s.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let s;const i=e.context.assign;if(s=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===i||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}const Ap=Wa(Ep).setParameterLength(2);class Cp extends jl{static get type(){return"StorageBufferNode"}constructor(e,t=null,s=0){let i,r=null;t&&t.isStruct?(i="struct",r=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(s=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=In(e.itemSize),s=e.count):i=t,super(e,i,s),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=Hn,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return Ap(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess($n)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=pl(this.value),this._varying=Qu(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:s}=this.getAttributeData(),i=s.build(e);return e.registerTransform(i,t),i}}const Rp=(e,t=null,s=0)=>new Cp(e,t,s);class Pp extends Zn{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i,r;if(s===Pp.VERTEX)i=e.getVertexIndex();else if(s===Pp.INSTANCE)i=e.getInstanceIndex();else if(s===Pp.DRAW)i=e.getDrawIndex();else if(s===Pp.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===Pp.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==Pp.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=Qu(this).build(e,t)}return r}}Pp.VERTEX="vertex",Pp.INSTANCE="instance",Pp.SUBGROUP="subgroup",Pp.INVOCATION_LOCAL="invocationLocal",Pp.INVOCATION_SUBGROUP="invocationSubgroup",Pp.DRAW="draw";const Bp=Ha(Pp,Pp.VERTEX),Fp=Ha(Pp,Pp.INSTANCE);Pp.SUBGROUP,Pp.INVOCATION_SUBGROUP,Pp.INVOCATION_LOCAL;const Dp=Ha(Pp,Pp.DRAW);class Ip extends Zn{static get type(){return"InstanceNode"}constructor(e,t,s=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=s,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=Vn,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){let{instanceMatrixNode:t,instanceColorNode:s}=this;null===t&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:i,isStorageColor:r}=this;if(i&&null===s){if(r)s=Rp(i,"vec3",Math.max(i.count,1)).element(Fp);else{const e=new gr(i.array,3),t=i.usage===at?gl:ml;this.bufferColor=e,s=lo(t(e,"vec3",3,0))}this.instanceColorNode=s}const n=t.mul(Rc).xyz;if(Rc.assign(n),e.needsPreviousData()&&Pc.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const e=qc(zc,t);zc.assign(e)}null!==this.instanceColorNode&&wo("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),null!==this.previousInstanceMatrixNode&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return null===this.previousInstanceMatrixNode&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(Pc).xyz}_createInstanceMatrixNode(e,t){let s;const{instanceMatrix:i}=this,{count:r}=i;if(this.isStorageMatrix)s=Rp(i,"mat4",Math.max(r,1)).element(Fp);else{if(16*r*4<=t.getUniformBufferLimit())s=$l(i.array,"mat4",Math.max(r,1)).element(Fp);else{const t=new vn(i.array,16,1);!0===e&&(this.buffer=t);const r=i.usage===at?gl:ml,n=[r(t,"vec4",16,0),r(t,"vec4",16,4),r(t,"vec4",16,8),r(t,"vec4",16,12)];s=vo(...n)}}return s}}class Lp extends Ip{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const Op=Wa(Lp).setParameterLength(1);class Up extends Zn{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=Fp:this.batchingIdNode=Dp);const t=Ka(([e])=>{const t=io(Dl(Gl(this.batchMesh._indirectTexture),0).x).toConst(),s=io(e).mod(t).toConst(),i=io(e).div(t).toConst();return Gl(this.batchMesh._indirectTexture,oo(s,i)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(io(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=io(Dl(Gl(i),0).x).toConst(),n=so(s).mul(4).toInt().toConst(),a=n.mod(r).toConst(),o=n.div(r).toConst(),h=vo(Gl(i,oo(a,o)),Gl(i,oo(a.add(1),o)),Gl(i,oo(a.add(2),o)),Gl(i,oo(a.add(3),o))),u=this.batchMesh._colorsTexture;if(null!==u){const e=Ka(([e])=>{const t=io(Dl(Gl(u),0).x).toConst(),s=e,i=s.mod(t).toConst(),r=s.div(t).toConst();return Gl(u,oo(i,r)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);wo("vec3","vBatchColor").assign(t)}const l=xo(h);Rc.assign(h.mul(Rc));const c=zc.div(lo(l[0].dot(l[0]),l[1].dot(l[1]),l[2].dot(l[2]))),d=l.mul(c).xyz;zc.assign(d),e.hasGeometryAttribute("tangent")&&Cd.mulAssign(l)}}const kp=Wa(Up).setParameterLength(1),zp=new WeakMap;class Vp extends Zn{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=jn,this.skinIndexNode=Pl("skinIndex","uvec4"),this.skinWeightNode=Pl("skinWeight","vec4"),this.bindMatrixNode=ld("bindMatrix","mat4"),this.bindMatrixInverseNode=ld("bindMatrixInverse","mat4"),this.boneMatricesNode=cd("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Rc,this.toPositionNode=Rc,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,a=e.element(s.x),o=e.element(s.y),h=e.element(s.z),u=e.element(s.w),l=r.mul(t),c=ph(a.mul(i.x).mul(l),o.mul(i.y).mul(l),h.mul(i.z).mul(l),u.mul(i.w).mul(l));return n.mul(c).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=zc,s=Cd){const{skinIndexNode:i,skinWeightNode:r,bindMatrixNode:n,bindMatrixInverseNode:a}=this,o=e.element(i.x),h=e.element(i.y),u=e.element(i.z),l=e.element(i.w);let c=ph(r.x.mul(o),r.y.mul(h),r.z.mul(u),r.w.mul(l));c=a.mul(c).mul(n);return{skinNormal:c.transformDirection(t).xyz,skinTangent:c.transformDirection(s).xyz}}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=cd("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Pc)}setup(e){e.needsPreviousData()&&Pc.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:t,skinTangent:s}=this.getSkinnedNormalAndTangent();zc.assign(t),e.hasGeometryAttribute("tangent")&&Cd.assign(s)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;zp.get(t)!==e.frameId&&(zp.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}class Gp extends Zn{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const s={};for(let e=0,t=this.params.length-1;e<t;e++){const t=this.params[e],i=!0!==t.isNode&&t.name||this.getVarName(e),r=!0!==t.isNode&&t.type||"int";s[i]=Ml(i,r)}const i=e.addStack(),r=this.params[this.params.length-1](s);t.returnsNode=r.context({nodeLoop:r}),t.stackNode=i;const n=this.params[0];if(!0!==n.isNode&&"function"==typeof n.update){const e=Ka(this.params[0].update)(s);t.updateNode=e.context({nodeLoop:e})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){e.getDataFromNode(e.fnCall.shaderNode).hasLoop=!0}}generate(e){const t=this.getProperties(e),s=this.params,i=t.stackNode;for(let i=0,r=s.length-1;i<r;i++){const r=s[i];let n,a=!1,o=null,h=null,u=null,l=null,c=null,d=null;if(r.isNode?"bool"===r.getNodeType(e)?(a=!0,l="bool",h=r.build(e,l)):(l="int",u=this.getVarName(i),o="0",h=r.build(e,l),c="<"):(l=r.type||"int",u=r.name||this.getVarName(i),o=r.start,h=r.end,c=r.condition,d=r.update,"number"==typeof o?o=e.generateConst(l,o):o&&o.isNode&&(o=o.build(e,l)),"number"==typeof h?h=e.generateConst(l,h):h&&h.isNode&&(h=h.build(e,l)),void 0!==o&&void 0===h?(o+=" - 1",h="0",c=">="):void 0!==h&&void 0===o&&(o="0",c="<"),void 0===c&&(c=Number(o)>Number(h)?">=":"<")),a)n=`while ( ${h} )`;else{const s={start:o,end:h},i=s.start,r=s.end;let a;const p=()=>c.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=u+" "+p()+" "+e.generateConst(l,d);break;case"string":a=u+" "+d;break;default:d.isNode?a=u+" "+p()+" "+d.build(e):(bt("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else d="int"===l||"uint"===l?c.includes("<")?"++":"--":p()+" 1.",a=u+" "+d;n=`for ( ${e.getVar(l,u)+" = "+i}; ${u+" "+c+" "+r}; ${a} )`}e.addFlowCode((0===i?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const r=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,s=this.params.length-1;t<s;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();e.addFlowTab()}}const jp=(...e)=>new Gp($a(e,"int")).toStack(),$p=new WeakMap,Wp=new es,Hp=Ka(({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const a=io(Bp).mul(s).add(n),o=a.div(i),h=a.sub(o.mul(i));return Gl(e,oo(h,o)).depth(r).xyz.mul(t)});class qp extends Zn{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=oh(1),this.updateType=jn}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,n=void 0!==r?r.length:0,{texture:a,stride:o,size:h}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,n=void 0!==r?r.length:0;let a=$p.get(e);if(void 0===a||a.count!==n){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],h=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let l=0;!0===t&&(l=1),!0===s&&(l=2),!0===i&&(l=3);let c=e.attributes.position.count*l,d=1;const p=4096;c>p&&(d=Math.ceil(c/p),c=p);const m=new Float32Array(c*d*4*n),g=new ss(m,c,d,n);g.type=Y,g.needsUpdate=!0;const f=4*l;for(let b=0;b<n;b++){const _=o[b],x=h[b],v=u[b],T=c*d*4*b;for(let S=0;S<_.count;S++){const w=S*f;!0===t&&(Wp.fromBufferAttribute(_,S),m[T+w+0]=Wp.x,m[T+w+1]=Wp.y,m[T+w+2]=Wp.z,m[T+w+3]=0),!0===s&&(Wp.fromBufferAttribute(x,S),m[T+w+4]=Wp.x,m[T+w+5]=Wp.y,m[T+w+6]=Wp.z,m[T+w+7]=0),!0===i&&(Wp.fromBufferAttribute(v,S),m[T+w+8]=Wp.x,m[T+w+9]=Wp.y,m[T+w+10]=Wp.z,m[T+w+11]=4===v.itemSize?Wp.w:1)}}function y(){g.dispose(),$p.delete(e),e.removeEventListener("dispose",y)}a={count:n,texture:g,stride:l,size:new Ft(c,d)},$p.set(e,a),e.addEventListener("dispose",y)}return a}(t);!0===s&&Rc.mulAssign(this.morphBaseInfluence),!0===i&&zc.mulAssign(this.morphBaseInfluence);const u=io(h.width);jp(n,({i:e})=>{const t=so(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Gl(this.mesh.morphTexture,oo(io(e).add(1),io(Fp))).r):t.assign(ld("morphTargetInfluences","float").element(e).toVar()),Ja(t.notEqual(0),()=>{!0===s&&Rc.addAssign(Hp({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:io(0)})),!0===i&&zc.addAssign(Hp({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:io(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const Xp=Wa(qp).setParameterLength(1);class Yp extends Zn{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Kp extends Yp{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Qp extends ju{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s={directDiffuse:lo().toVar("directDiffuse"),directSpecular:lo().toVar("directSpecular"),indirectDiffuse:lo().toVar("indirectDiffuse"),indirectSpecular:lo().toVar("indirectSpecular")};return{radiance:lo().toVar("radiance"),irradiance:lo().toVar("irradiance"),iblIrradiance:lo().toVar("iblIrradiance"),ambientOcclusion:so(1).toVar("ambientOcclusion"),reflectedLight:s,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const Zp=Wa(Qp);class Jp extends Yp{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const em=new Ft;class tm extends kl{static get type(){return"ViewportTextureNode"}constructor(e=Jl,t=null,s=null){let i=null;null===s?(i=new Cr,i.minFilter=G,s=i):i=s,super(s,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=Gn,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,s;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,s=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,s=this._cacheTextures),null===e)return t;if(!1===s.has(e)){const i=t.clone();s.set(e,i)}return s.get(e)}updateReference(e){const t=e.renderer.getRenderTarget();return this.value=this.getTextureForReference(t),this.value}updateBefore(e){const t=e.renderer,s=t.getRenderTarget();null===s?t.getDrawingBufferSize(em):em.set(s.width,s.height);const i=this.getTextureForReference(s);i.image.width===em.width&&i.image.height===em.height||(i.image.width=em.width,i.image.height=em.height,i.needsUpdate=!0);const r=i.generateMipmaps;i.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(i),i.generateMipmaps=r}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const sm=Wa(tm,null,null,{generateMipmaps:!0}).setParameterLength(0,3),im=sm(),rm=(e=Jl,t=null)=>im.sample(e,t);let nm=null;class am extends tm{static get type(){return"ViewportDepthTextureNode"}constructor(e=Jl,t=null){null===nm&&(nm=new Pr),super(e,t,nm)}getTextureForReference(){return nm}}const om=Wa(am).setParameterLength(0,2);class hm extends Zn{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===hm.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===hm.DEPTH_BASE)null!==s&&(i=pm().assign(s));else if(t===hm.DEPTH)i=e.isPerspectiveCamera?lm(Dc.z,pc,mc):um(Dc.z,pc,mc);else if(t===hm.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=cm(s,pc,mc);i=um(e,pc,mc)}else i=s;else i=um(Dc.z,pc,mc);return i}}hm.DEPTH_BASE="depthBase",hm.DEPTH="depth",hm.LINEAR_DEPTH="linearDepth";const um=(e,t,s)=>e.add(t).div(t.sub(s)),lm=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),cm=Ka(([e,t,s],i)=>!0===i.renderer.reversedDepthBuffer?t.mul(s).div(t.sub(s).mul(e).sub(t)):t.mul(s).div(s.sub(t).mul(e).sub(s))),dm=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Xh(e.negate().div(t)),r=Xh(s.div(t));return i.div(r)},pm=Wa(hm,hm.DEPTH_BASE),mm=Ha(hm,hm.DEPTH);om(),mm.assign=e=>pm(e);class gm extends Zn{static get type(){return"ClippingNode"}constructor(e=gm.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:s,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===gm.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===gm.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return Ka(()=>{const s=so().toVar("distanceToPlane"),i=so().toVar("distanceToGradient"),r=so(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=ql(t).setGroup(rh);jp(n,({i:t})=>{const n=e.element(t);s.assign(Dc.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(Uu(i.negate(),i,s))})}const a=e.length;if(a>0){const t=ql(e).setGroup(rh),n=so(1).toVar("intersectionClipOpacity");jp(a,({i:e})=>{const r=t.element(e);s.assign(Dc.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(Uu(i.negate(),i,s).oneMinus())}),r.mulAssign(n.oneMinus())}Mo.a.mulAssign(r),Mo.a.equal(0).discard()})()}setupDefault(e,t){return Ka(()=>{const s=t.length;if(!1===this.hardwareClipping&&s>0){const e=ql(t).setGroup(rh);jp(s,({i:t})=>{const s=e.element(t);Dc.dot(s.xyz).greaterThan(s.w).discard()})}const i=e.length;if(i>0){const t=ql(e).setGroup(rh),s=no(!0).toVar("clipped");jp(i,({i:e})=>{const i=t.element(e);s.assign(Dc.dot(i.xyz).greaterThan(i.w).and(s))}),s.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),Ka(()=>{const i=ql(e).setGroup(rh),r=Xl(t.getClipDistance());jp(s,({i:e})=>{const t=i.element(e),s=Dc.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)})})()}}gm.ALPHA_TO_COVERAGE="alphaToCoverage",gm.DEFAULT="default",gm.HARDWARE="hardware";const fm=Ka(([e])=>eu(gh(1e4,tu(gh(17,e.x).add(gh(.1,e.y)))).mul(ph(.1,ou(tu(gh(13,e.y).add(e.x))))))),ym=Ka(([e])=>fm(ao(fm(e.xy),e.z))),bm=Ka(([e])=>{const t=Tu(uu(du(e.xyz)),uu(pu(e.xyz))),s=so(1).div(so(.05).mul(t)).toVar("pixScale"),i=ao(Hh(Qh(Xh(s))),Hh(Zh(Xh(s)))),r=ao(ym(Qh(i.x.mul(e.xyz))),ym(Qh(i.y.mul(e.xyz)))),n=eu(Xh(s)),a=ph(gh(n.oneMinus(),r.x),gh(n,r.y)),o=vu(n,n.oneMinus()),h=lo(a.mul(a).div(gh(2,o).mul(mh(1,o))),a.sub(gh(.5,o)).div(mh(1,o)),mh(1,mh(1,a).mul(mh(1,a)).div(gh(2,o).mul(mh(1,o))))),u=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(h.x,h.y),h.z);return Iu(u,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class _m extends Rl{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let s;return s=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new es(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const xm=Ka(([e])=>go(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"});class vm extends $i{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const s=this[t];s&&!0===s.isNode&&e.push({property:t,childNode:s})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:s}of this._getNodeChildren())e.push(Rn(t.slice(0,-4)),s.getCacheKey());return this.type+Pn(e)}build(e){this.setup(e)}setupObserver(e){return new Nn(e)}setup(e){e.context.setupNormal=()=>Yu(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();!0===t.contextNode.isContextNode?e.context={...e.context,...t.contextNode.getFlowContextData()}:bt('NodeMaterial: "renderer.contextNode" must be an instance of `context()`.'),null!==this.contextNode&&(!0===this.contextNode.isContextNode?e.context={...e.context,...this.contextNode.getFlowContextData()}:bt('NodeMaterial: "material.contextNode" must be an instance of `context()`.')),e.addStack();const i=this.setupVertex(e),r=Yu(this.vertexNode||i,"VERTEX");let n;e.context.clipSpace=r,e.stack.outputNode=r,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==s?!0===s.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const r=go(i,Mo.a).max(0);n=this.setupOutput(e,r),Wo.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==s){const e=t.getMRT(),s=this.mrtNode;null!==e?(o&&Wo.assign(n),n=e,null!==s&&(n=e.merge(s))):null!==s&&(n=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=go(t)),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:s}=e.clippingContext;let i=null;if(t.length>0||s.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?i=new gm(gm.ALPHA_TO_COVERAGE):e.stack.addToStack(new gm)}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new gm(gm.HARDWARE)),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=s.isPerspectiveCamera?dm(Dc.z,pc,mc):um(Dc.z,pc,mc))}null!==i&&mm.assign(i).toStack()}setupPositionView(){return wc.mul(Rc).xyz}setupModelViewProjection(){return gc.mul(Dc)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),Np}setupPosition(e){const{object:t,geometry:s}=e;var i;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&Xp(t).toStack(),!0===t.isSkinnedMesh&&(i=t,new Vp(i)).toStack(),this.displacementMap){const e=pd("displacementMap","texture"),t=pd("displacementScale","float"),s=pd("displacementBias","float");Rc.addAssign(zc.normalize().mul(e.x.mul(t).add(s)))}return t.isBatchedMesh&&kp(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Op(t).toStack(),null!==this.positionNode&&Rc.assign(Yu(this.positionNode,"POSITION","vec3")),Rc}setupDiffuseColor(e){const{object:t,geometry:s}=e;null!==this.maskNode&&no(this.maskNode).not().discard();let i=this.colorNode?go(this.colorNode):$d;if(!0===this.vertexColors&&s.hasAttribute("color")&&(i=i.mul(((e=0)=>new _m(e))())),t.instanceColor){i=wo("vec3","vInstanceColor").mul(i)}if(t.isBatchedMesh&&t._colorsTexture){i=wo("vec3","vBatchColor").mul(i)}Mo.assign(i);const r=this.opacityNode?so(this.opacityNode):qd;Mo.a.assign(Mo.a.mul(r));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?so(this.alphaTestNode):jd,!0===this.alphaToCoverage?(Mo.a=Uu(n,n.add(yu(Mo.a)),Mo.a),Mo.a.lessThanEqual(0).discard()):Mo.a.lessThanEqual(n).discard()),!0===this.alphaHash&&Mo.a.lessThan(bm(Rc)).discard(),e.isOpaque()&&Mo.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?lo(0):Mo.rgb}setupNormal(){return this.normalNode?lo(this.normalNode):tp}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?pd("envMap","cubeTexture"):pd("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Jp(Sp)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);i&&i.isLightingNode&&t.push(i);let r=this.aoNode;null===r&&e.material.aoMap&&(r=wp),e.context.getAO&&(r=e.context.getAO(r,e)),r&&t.push(new Kp(r));let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:r}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=Zp(n,t,s,i)}else null!==s&&(a=lo(null!==i?Du(a,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Eo.assign(lo(r||Hd)),a=a.add(Eo)),a}setupFog(e,t){const s=e.fogNode;return s&&(Wo.assign(t),t=go(s.toVar())),t}setupPremultipliedAlpha(e,t){return xm(t)}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),!0===this.premultipliedAlpha&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const t in e){const s=e[t];void 0===this[t]&&(this[t]=s,s&&s.clone&&(this[t]=s.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const s=$i.prototype.toJSON.call(this,e);s.inputNodes={};for(const{property:t,childNode:i}of this._getNodeChildren())s.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(t){const t=i(e.textures),r=i(e.images),n=i(e.nodes);t.length>0&&(s.textures=t),r.length>0&&(s.images=r),n.length>0&&(s.nodes=n)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const Tm=new Er;class Sm extends vm{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Tm),this.setValues(e)}}const wm=new Wr;class Mm extends vm{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(wm),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?so(this.offsetNode):xp,t=this.dashScaleNode?so(this.dashScaleNode):yp,s=this.dashSizeNode?so(this.dashSizeNode):bp,i=this.gapSizeNode?so(this.gapSizeNode):_p;Ho.assign(s),qo.assign(i);const r=Qu(Pl("lineDistance").mul(t));(e?r.add(e):r).mod(Ho.add(qo)).greaterThan(Ho).discard()}}const Nm=new Gr;class Em extends vm{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Nm),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?so(this.opacityNode):qd;Mo.assign(sl(go(Va($c).mul(.5).add(.5),e),He))}}const Am=Ka(([e=Fc])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return ao(t,s)});class Cm extends ts{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Rr(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r=new Fr(5,5,5),n=Am(Fc),a=new vm;a.colorNode=Vl(t,n,0),a.side=1,a.blending=0;const o=new dr(r,a),h=new zs;h.add(o),t.minFilter===G&&(t.minFilter=z);const u=new _n(1,10,this),l=e.getMRT();return e.setMRT(null),u.update(e,h),e.setMRT(l),t.minFilter=s,t.currentGenerateMipmaps=i,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,s=!0,i=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(r)}}const Rm=new WeakMap;class Pm extends ta{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=od(null);const t=new Rr;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Gn}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:s[i.property];if(e&&e.isTexture){const s=e.mapping;if(303===s||304===s){if(Rm.has(e)){const t=Rm.get(e);Fm(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new Cm(s.height);i.fromEquirectangularTexture(t,e),Fm(i.texture,e.mapping),this._cubeTexture=i.texture,Rm.set(e,i.texture),e.addEventListener("dispose",Bm)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Bm(e){const t=e.target;t.removeEventListener("dispose",Bm);const s=Rm.get(t);void 0!==s&&(Rm.delete(t),s.dispose())}function Fm(e,t){303===t?e.mapping=B:304===t&&(e.mapping=F)}const Dm=Wa(Pm).setParameterLength(1);class Im extends Yp{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Dm(this.envNode)}}class Lm extends Yp{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=so(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Om{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Um extends Om{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(go(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(go(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Mo.rgb)}finish(e){const{material:t,context:s}=e,i=s.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case 0:i.rgb.assign(Du(i.rgb,i.rgb.mul(r.rgb),Qd.mul(Zd)));break;case 1:i.rgb.assign(Du(i.rgb,r.rgb,Qd.mul(Zd)));break;case 2:i.rgb.addAssign(r.rgb.mul(Qd.mul(Zd)));break;default:yt("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const km=new er;class zm extends vm{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(km),this.setValues(e)}setupNormal(){return Uc(Gc)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Im(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Lm(Sp)),t}setupOutgoingLight(){return Mo.rgb}setupLightingModel(){return new Um}}const Vm=Ka(({f0:e,f90:t,dotVH:s})=>{const i=s.mul(-5.55473).sub(6.98316).mul(s).exp2();return e.mul(i.oneMinus()).add(t.mul(i))}),Gm=Ka(e=>e.diffuseColor.mul(1/Math.PI)),jm=Ka(({dotNH:e})=>$o.mul(so(.5)).add(1).mul(so(1/Math.PI)).mul(e.pow($o))),$m=Ka(({lightDirection:e})=>{const t=e.add(Ic).normalize(),s=$c.dot(t).clamp(),i=Ic.dot(t).clamp(),r=Vm({f0:Vo,f90:1,dotVH:i}),n=so(.25),a=jm({dotNH:s});return r.mul(n).mul(a)});class Wm extends Um{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=$c.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(Gm({diffuseColor:Mo.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul($m({lightDirection:e})).mul(Qd))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(Gm({diffuseColor:Mo}))),i.indirectDiffuse.mulAssign(t)}}const Hm=new jr;class qm extends vm{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Hm),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Im(t):null}setupLightingModel(){return new Wm(!1)}}const Xm=new zr;class Ym extends vm{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Xm),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Im(t):null}setupLightingModel(){return new Wm}setupVariants(){const e=(this.shininessNode?so(this.shininessNode):Wd).max(1e-4);$o.assign(e);const t=this.specularNode||Xd;Vo.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Km=Ka(e=>{if(!1===e.geometry.hasAttribute("normal"))return so(0);const t=Gc.dFdx().abs().max(Gc.dFdy().abs());return t.x.max(t.y).max(t.z)}),Qm=Ka(e=>{const{roughness:t}=e,s=Km();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i}),Zm=Ka(({alpha:e,dotNL:t,dotNV:s})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(s.pow2())).sqrt()),n=s.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return fh(.5,r.add(n).max(kh))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Jm=Ka(({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:a,dotNL:o})=>{const h=o.mul(lo(e.mul(s),t.mul(i),a).length()),u=a.mul(lo(e.mul(r),t.mul(n),o).length());return fh(.5,h.add(u))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),eg=Ka(({alpha:e,dotNH:t})=>{const s=e.pow2(),i=t.pow2().mul(s.oneMinus()).oneMinus();return s.div(i.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),tg=so(1/Math.PI),sg=Ka(({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),a=lo(t.mul(i),e.mul(r),n.mul(s)),o=a.dot(a),h=n.div(o);return tg.mul(n.mul(h.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),ig=Ka(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,normalView:n=$c,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const h=i.pow2(),u=e.add(Ic).normalize(),l=n.dot(e).clamp(),c=n.dot(Ic).clamp(),d=n.dot(u).clamp(),p=Ic.dot(u).clamp();let m,g,f=Vm({f0:t,f90:s,dotVH:p});if(ka(a)&&(f=Do.mix(f,r)),ka(o)){const t=ko.dot(e),s=ko.dot(Ic),i=ko.dot(u),r=zo.dot(e),n=zo.dot(Ic),a=zo.dot(u);m=Jm({alphaT:Oo,alphaB:h,dotTV:s,dotBV:n,dotTL:t,dotBL:r,dotNV:c,dotNL:l}),g=sg({alphaT:Oo,alphaB:h,dotNH:d,dotTH:i,dotBH:a})}else m=Zm({alpha:h,dotNL:l,dotNV:c}),g=eg({alpha:h,dotNH:d});return f.mul(m).mul(g)}),rg=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let ng=null;const ag=Ka(({roughness:e,dotNV:t})=>{null===ng&&(ng=new mr(rg,16,16,he,K),ng.name="DFG_LUT",ng.minFilter=z,ng.magFilter=z,ng.wrapS=I,ng.wrapT=I,ng.generateMipmaps=!1,ng.needsUpdate=!0);const s=ao(e,t);return Vl(ng,s).rg}),og=Ka(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:a})=>{const o=ig({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:a}),h=$c.dot(e).clamp(),u=$c.dot(Ic).clamp(),l=ag({roughness:i,dotNV:u}),c=ag({roughness:i,dotNV:h}),d=t.mul(l.x).add(s.mul(l.y)),p=t.mul(c.x).add(s.mul(c.y)),m=l.x.add(l.y),g=c.x.add(c.y),f=so(1).sub(m),y=so(1).sub(g),b=t.add(t.oneMinus().mul(.047619)),_=d.mul(p).mul(b).div(so(1).sub(f.mul(y).mul(b).mul(b)).add(kh)),x=f.mul(y),v=_.mul(x);return o.add(v)}),hg=Ka(e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=ag({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))}),ug=Ka(({f:e,f90:t,dotVH:s})=>{const i=s.oneMinus().saturate(),r=i.mul(i),n=i.mul(r,r).clamp(0,.9999);return e.sub(lo(t).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),lg=Ka(({roughness:e,dotNH:t})=>{const s=e.pow2(),i=so(1).div(s),r=t.pow2().oneMinus().max(.0078125);return so(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),cg=Ka(({dotNV:e,dotNL:t})=>so(1).div(so(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),dg=Ka(({lightDirection:e})=>{const t=e.add(Ic).normalize(),s=$c.dot(e).clamp(),i=$c.dot(Ic).clamp(),r=$c.dot(t).clamp(),n=lg({roughness:Fo,dotNH:r}),a=cg({dotNV:i,dotNL:s});return Bo.mul(n).mul(a)}),pg=Ka(({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=ao(s,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),mg=Ka(({f:e})=>{const t=e.length();return Tu(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),gg=Ka(({v1:e,v2:t})=>{const s=e.dot(t),i=s.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),n=i.add(4.1616724).mul(i).add(3.417594).toVar(),a=r.div(n),o=s.greaterThan(0).select(a,Tu(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),fg=Ka(({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:a,p3:o})=>{const h=n.sub(r).toVar(),u=o.sub(r).toVar(),l=h.cross(u),c=lo().toVar();return Ja(l.dot(s.sub(r)).greaterThanEqual(0),()=>{const h=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(h).negate(),l=i.mul(xo(h,u,e).transpose()).toVar(),d=l.mul(r.sub(s)).normalize().toVar(),p=l.mul(n.sub(s)).normalize().toVar(),m=l.mul(a.sub(s)).normalize().toVar(),g=l.mul(o.sub(s)).normalize().toVar(),f=lo(0).toVar();f.addAssign(gg({v1:d,v2:p})),f.addAssign(gg({v1:p,v2:m})),f.addAssign(gg({v1:m,v2:g})),f.addAssign(gg({v1:g,v2:d})),c.assign(lo(mg({f:f})))}),c}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),yg=1/6,bg=e=>gh(yg,gh(e,gh(e,e.negate().add(3)).sub(3)).add(1)),_g=e=>gh(yg,gh(e,gh(e,gh(3,e).sub(6))).add(4)),xg=e=>gh(yg,gh(e,gh(e,gh(-3,e).add(3)).add(3)).add(1)),vg=e=>gh(yg,Cu(e,3)),Tg=e=>bg(e).add(_g(e)),Sg=e=>xg(e).add(vg(e)),wg=e=>ph(-1,_g(e).div(bg(e).add(_g(e)))),Mg=e=>ph(1,vg(e).div(xg(e).add(vg(e)))),Ng=(e,t,s)=>{const i=e.uvNode,r=gh(i,t.zw).add(.5),n=Qh(r),a=eu(r),o=Tg(a.x),h=Sg(a.x),u=wg(a.x),l=Mg(a.x),c=wg(a.y),d=Mg(a.y),p=ao(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),m=ao(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),g=ao(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),f=ao(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),y=Tg(a.y).mul(ph(o.mul(e.sample(p).level(s)),h.mul(e.sample(m).level(s)))),b=Sg(a.y).mul(ph(o.mul(e.sample(g).level(s)),h.mul(e.sample(f).level(s))));return y.add(b)},Eg=Ka(([e,t])=>{const s=ao(e.size(io(t))),i=ao(e.size(io(t.add(1)))),r=fh(1,s),n=fh(1,i),a=Ng(e,go(r,s),Qh(t)),o=Ng(e,go(n,i),Zh(t));return eu(t).mix(a,o)}),Ag=Ka(([e,t,s,i,r])=>{const n=lo(Ou(t.negate(),Jh(e),fh(1,i))),a=lo(uu(r[0].xyz),uu(r[1].xyz),uu(r[2].xyz));return Jh(n).mul(s.mul(a))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),Cg=Ka(([e,t])=>e.mul(Iu(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Rg=sm(),Pg=rm(),Bg=Ka(([e,t,s],{material:i})=>{const r=(1===i.side?Rg:Pg).sample(e),n=Xh(ec.x).mul(Cg(t,s));return Eg(r,n)}),Fg=Ka(([e,t,s])=>(Ja(s.notEqual(0),()=>{const i=qh(t).negate().div(s);return Wh(i.negate().mul(e))}),lo(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Dg=Ka(([e,t,s,i,r,n,a,o,h,u,l,c,d,p,m])=>{let g,f;if(m){g=go().toVar(),f=lo().toVar();const r=l.sub(1).mul(m.mul(.025)),n=lo(l.sub(r),l,l.add(r));jp({start:0,end:3},({i:r})=>{const l=n.element(r),m=Ag(e,t,c,l,o),y=a.add(m),b=u.mul(h.mul(go(y,1))),_=ao(b.xy.div(b.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(ao(_.x,_.y.oneMinus()));const x=Bg(_,s,l);g.element(r).assign(x.element(r)),g.a.addAssign(x.a),f.element(r).assign(i.element(r).mul(Fg(uu(m),d,p).element(r)))}),g.a.divAssign(3)}else{const r=Ag(e,t,c,l,o),n=a.add(r),m=u.mul(h.mul(go(n,1))),y=ao(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(ao(y.x,y.y.oneMinus())),g=Bg(y,s,l),f=i.mul(Fg(uu(r),d,p))}const y=f.rgb.mul(g.rgb),b=e.dot(t).clamp(),_=lo(hg({dotNV:b,specularColor:r,specularF90:n,roughness:s})),x=f.r.add(f.g,f.b).div(3);return go(_.oneMinus().mul(y),g.a.oneMinus().mul(x).oneMinus())}),Ig=xo(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Lg=(e,t)=>e.sub(t).div(e.add(t)).pow2(),Og=Ka(({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=Du(e,t,Uu(0,.03,i)),a=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();Ja(a.lessThan(0),()=>lo(1));const o=a.sqrt(),h=Lg(n,e),u=Vm({f0:h,f90:1,dotVH:s}),l=u.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=so(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return lo(1).add(t).div(lo(1).sub(t))})(r.clamp(0,.9999)),m=Lg(p,n.toVec3()),g=Vm({f0:m,f90:1,dotVH:o}),f=lo(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(i,o,2),b=lo(d).add(f),_=u.mul(g).clamp(1e-5,.9999),x=_.sqrt(),v=l.pow2().mul(g).div(lo(1).sub(_)),T=u.add(v).toVar(),S=v.sub(l).toVar();return jp({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{S.mulAssign(x);const t=((e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=lo(54856e-17,44201e-17,52481e-17),r=lo(1681e3,1795300,2208400),n=lo(43278e5,93046e5,66121e5),a=so(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let o=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());return o=lo(o.x.add(a),o.y,o.z).div(1.0685e-7),Ig.mul(o)})(so(e).mul(y),so(e).mul(b)).mul(2);T.addAssign(S.mul(t))}),T.max(lo(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),Ug=Ka(({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.mul(s),n=s.add(.1).reciprocal(),a=so(-1.9362).add(s.mul(1.0678)).add(r.mul(.4573)).sub(n.mul(.8469)),o=so(-.6014).add(s.mul(.5538)).sub(r.mul(.467)).sub(n.mul(.1255));return a.mul(i).add(o).exp().saturate()}),kg=lo(.04),zg=so(1);class Vg extends Om{constructor(e=!1,t=!1,s=!1,i=!1,r=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=r,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=lo().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=lo().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=lo().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=lo().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=lo().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=$c.dot(Ic).clamp(),t=Og({outsideIOR:so(1),eta2:Io,cosTheta1:e,thinFilmThickness:Lo,baseF0:Vo}),s=Og({outsideIOR:so(1),eta2:Io,cosTheta1:e,thinFilmThickness:Lo,baseF0:Mo.rgb});this.iridescenceFresnel=Du(t,s,Co),this.iridescenceF0Dielectric=ug({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=ug({f:s,f90:1,dotVH:e}),this.iridescenceF0=Du(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Co)}if(!0===this.transmission){const t=Bc,s=bc.sub(Bc).normalize(),i=Wc,r=e.context;r.backdrop=Dg(i,s,Ao,No,Go,jo,t,Tc,yc,gc,Xo,Ko,Zo,Qo,this.dispersion?Jo:null),r.backdropAlpha=Yo,Mo.a.mulAssign(Du(1,r.backdrop.a,Yo))}super.start(e)}computeMultiscattering(e,t,s,i,r=null){const n=$c.dot(Ic).clamp(),a=ag({roughness:Ao,dotNV:n}),o=r?Do.mix(i,r):i,h=o.mul(a.x).add(s.mul(a.y)),u=a.x.add(a.y).oneMinus(),l=o.add(o.oneMinus().mul(.047619)),c=h.mul(l).div(u.mul(l).oneMinus());e.addAssign(h),t.addAssign(c.mul(u))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=$c.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(i.mul(dg({lightDirection:e})));const t=Ug({normal:$c,viewDir:Ic,roughness:Fo}),s=Ug({normal:$c,viewDir:e,roughness:Fo}),r=Bo.r.max(Bo.g).max(Bo.b).mul(t.max(s)).oneMinus();i.mulAssign(r)}if(!0===this.clearcoat){const s=Hc.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(ig({lightDirection:e,f0:kg,f90:zg,roughness:Po,normalView:Hc})))}s.directDiffuse.addAssign(i.mul(Gm({diffuseColor:No}))),s.directSpecular.addAssign(i.mul(og({lightDirection:e,f0:Go,f90:1,roughness:Ao,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:r,ltc_1:n,ltc_2:a}){const o=t.add(s).sub(i),h=t.sub(s).sub(i),u=t.sub(s).add(i),l=t.add(s).add(i),c=$c,d=Ic,p=Dc.toVar(),m=pg({N:c,V:d,roughness:Ao}),g=n.sample(m).toVar(),f=a.sample(m).toVar(),y=xo(lo(g.x,0,g.y),lo(0,1,0),lo(g.z,0,g.w)).toVar(),b=Go.mul(f.x).add(jo.sub(Go).mul(f.y)).toVar();if(r.directSpecular.addAssign(e.mul(b).mul(fg({N:c,V:d,P:p,mInv:y,p0:o,p1:h,p2:u,p3:l}))),r.directDiffuse.addAssign(e.mul(No).mul(fg({N:c,V:d,P:p,mInv:xo(1,0,0,0,1,0,0,0,1),p0:o,p1:h,p2:u,p3:l}))),!0===this.clearcoat){const t=Hc,s=pg({N:t,V:d,roughness:Po}),i=n.sample(s),r=a.sample(s),c=xo(lo(i.x,0,i.y),lo(0,1,0),lo(i.z,0,i.w)),m=kg.mul(r.x).add(zg.sub(kg).mul(r.y));this.clearcoatSpecularDirect.addAssign(e.mul(m).mul(fg({N:t,V:d,P:p,mInv:c,p0:o,p1:h,p2:u,p3:l})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:s}=e.context,i=t.mul(Gm({diffuseColor:No})).toVar();if(!0===this.sheen){const e=Ug({normal:$c,viewDir:Ic,roughness:Fo}),t=Bo.r.max(Bo.g).max(Bo.b).mul(e).oneMinus();i.mulAssign(t)}s.indirectDiffuse.addAssign(i)}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(s.mul(Bo,Ug({normal:$c,viewDir:Ic,roughness:Fo}))),!0===this.clearcoat){const e=Hc.dot(Ic).clamp(),t=hg({dotNV:e,specularColor:kg,specularF90:zg,roughness:Po});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=lo().toVar("singleScatteringDielectric"),n=lo().toVar("multiScatteringDielectric"),a=lo().toVar("singleScatteringMetallic"),o=lo().toVar("multiScatteringMetallic");this.computeMultiscattering(r,n,jo,Vo,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,jo,Mo.rgb,this.iridescenceF0Metallic);const h=Du(r,a,Co),u=Du(n,o,Co),l=r.add(n),c=No.mul(l.oneMinus()),d=s.mul(1/Math.PI),p=t.mul(h).add(u.mul(d)).toVar(),m=c.mul(d).toVar();if(!0===this.sheen){const e=Ug({normal:$c,viewDir:Ic,roughness:Fo}),t=Bo.r.max(Bo.g).max(Bo.b).mul(e).oneMinus();p.mulAssign(t),m.mulAssign(t)}i.indirectSpecular.addAssign(p),i.indirectDiffuse.addAssign(m)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:s}=e.context,i=$c.dot(Ic).clamp().add(t),r=Ao.mul(-16).oneMinus().negate().exp2(),n=t.sub(i.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),s.indirectDiffuse.mulAssign(t),s.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Hc.dot(Ic).clamp(),s=Vm({dotVH:e,f0:kg,f90:zg}),i=t.mul(Ro.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Ro));t.assign(i)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const Gg=so(1),jg=so(-2),$g=so(.8),Wg=so(-1),Hg=so(.4),qg=so(2),Xg=so(.305),Yg=so(3),Kg=so(.21),Qg=so(4),Zg=so(4),Jg=so(16),ef=Ka(([e])=>{const t=lo(ou(e)).toVar(),s=so(-1).toVar();return Ja(t.x.greaterThan(t.z),()=>{Ja(t.x.greaterThan(t.y),()=>{s.assign(Gu(e.x.greaterThan(0),0,3))}).Else(()=>{s.assign(Gu(e.y.greaterThan(0),1,4))})}).Else(()=>{Ja(t.z.greaterThan(t.y),()=>{s.assign(Gu(e.z.greaterThan(0),2,5))}).Else(()=>{s.assign(Gu(e.y.greaterThan(0),1,4))})}),s}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),tf=Ka(([e,t])=>{const s=ao().toVar();return Ja(t.equal(0),()=>{s.assign(ao(e.z,e.y).div(ou(e.x)))}).ElseIf(t.equal(1),()=>{s.assign(ao(e.x.negate(),e.z.negate()).div(ou(e.y)))}).ElseIf(t.equal(2),()=>{s.assign(ao(e.x.negate(),e.y).div(ou(e.z)))}).ElseIf(t.equal(3),()=>{s.assign(ao(e.z.negate(),e.y).div(ou(e.x)))}).ElseIf(t.equal(4),()=>{s.assign(ao(e.x.negate(),e.z).div(ou(e.y)))}).Else(()=>{s.assign(ao(e.x,e.y).div(ou(e.z)))}),gh(.5,s.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),sf=Ka(([e])=>{const t=so(0).toVar();return Ja(e.greaterThanEqual($g),()=>{t.assign(Gg.sub(e).mul(Wg.sub(jg)).div(Gg.sub($g)).add(jg))}).ElseIf(e.greaterThanEqual(Hg),()=>{t.assign($g.sub(e).mul(qg.sub(Wg)).div($g.sub(Hg)).add(Wg))}).ElseIf(e.greaterThanEqual(Xg),()=>{t.assign(Hg.sub(e).mul(Yg.sub(qg)).div(Hg.sub(Xg)).add(qg))}).ElseIf(e.greaterThanEqual(Kg),()=>{t.assign(Xg.sub(e).mul(Qg.sub(Yg)).div(Xg.sub(Kg)).add(Yg))}).Else(()=>{t.assign(so(-2).mul(Xh(gh(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),rf=Ka(([e,t])=>{const s=e.toVar();s.assign(gh(2,s).sub(1));const i=lo(s,1).toVar();return Ja(t.equal(0),()=>{i.assign(i.zyx)}).ElseIf(t.equal(1),()=>{i.assign(i.xzy),i.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{i.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{i.assign(i.zyx),i.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{i.assign(i.xzy),i.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{i.z.mulAssign(-1)}),i}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),nf=Ka(([e,t,s,i,r,n])=>{const a=so(s),o=lo(t),h=Iu(sf(a),jg,n),u=eu(h),l=Qh(h),c=lo(af(e,o,l,i,r,n)).toVar();return Ja(u.notEqual(0),()=>{const t=lo(af(e,o,l.add(1),i,r,n)).toVar();c.assign(Du(c,t,u))}),c}),af=Ka(([e,t,s,i,r,n])=>{const a=so(s).toVar(),o=lo(t),h=so(ef(o)).toVar(),u=so(Tu(Zg.sub(a),0)).toVar();a.assign(Tu(a,Zg));const l=so(Hh(a)).toVar(),c=ao(tf(o,h).mul(l.sub(2)).add(1)).toVar();return Ja(h.greaterThan(2),()=>{c.y.addAssign(l),h.subAssign(3)}),c.x.addAssign(h.mul(l)),c.x.addAssign(u.mul(gh(3,Jg))),c.y.addAssign(gh(4,Hh(n).sub(l))),c.x.mulAssign(i),c.y.mulAssign(r),e.sample(c).grad(ao(),ao())}),of=Ka(({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const h=su(i),u=s.mul(h).add(r.cross(s).mul(tu(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return af(e,u,t,n,a,o)}),hf=Ka(({n:e,latitudinal:t,poleAxis:s,outputDirection:i,weights:r,samples:n,dTheta:a,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c})=>{const d=lo(Gu(t,s,Au(s,i))).toVar();Ja(d.equal(lo(0)),()=>{d.assign(lo(i.z,0,i.x.negate()))}),d.assign(Jh(d));const p=lo().toVar();return p.addAssign(r.element(0).mul(of({theta:0,axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c}))),jp({start:io(1),end:e},({i:e})=>{Ja(e.greaterThanEqual(n),()=>{Ml("break").toStack()});const t=so(a.mul(so(e))).toVar();p.addAssign(r.element(e).mul(of({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c}))),p.addAssign(r.element(e).mul(of({theta:t,axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:l,CUBEUV_MAX_MIP:c})))}),go(p,1)}),uf=Ka(([e])=>{const t=ro(e).toVar();return t.assign(t.shiftLeft(ro(16)).bitOr(t.shiftRight(ro(16)))),t.assign(t.bitAnd(ro(1431655765)).shiftLeft(ro(1)).bitOr(t.bitAnd(ro(2863311530)).shiftRight(ro(1)))),t.assign(t.bitAnd(ro(858993459)).shiftLeft(ro(2)).bitOr(t.bitAnd(ro(3435973836)).shiftRight(ro(2)))),t.assign(t.bitAnd(ro(252645135)).shiftLeft(ro(4)).bitOr(t.bitAnd(ro(4042322160)).shiftRight(ro(4)))),t.assign(t.bitAnd(ro(16711935)).shiftLeft(ro(8)).bitOr(t.bitAnd(ro(4278255360)).shiftRight(ro(8)))),so(t).mul(2.3283064365386963e-10)}),lf=Ka(([e,t])=>ao(so(e).div(so(t)),uf(e))),cf=Ka(([e,t,s])=>{const i=s.mul(s).toConst(),r=lo(1,0,0).toConst(),n=Au(t,r).toConst(),a=Yh(e.x).toConst(),o=gh(2,3.14159265359).mul(e.y).toConst(),h=a.mul(su(o)).toConst(),u=a.mul(tu(o)).toVar(),l=gh(.5,t.z.add(1)).toConst();u.assign(l.oneMinus().mul(Yh(h.mul(h).oneMinus())).add(l.mul(u)));const c=r.mul(h).add(n.mul(u)).add(t.mul(Yh(Tu(0,h.mul(h).add(u.mul(u)).oneMinus()))));return Jh(lo(i.mul(c.x),i.mul(c.y),Tu(0,c.z)))}),df=Ka(({roughness:e,mipInt:t,envMap:s,N_immutable:i,GGX_SAMPLES:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const h=lo(i).toVar(),u=lo(0).toVar(),l=so(0).toVar();return Ja(e.lessThan(.001),()=>{u.assign(af(s,h,t,n,a,o))}).Else(()=>{const i=Gu(ou(h.z).lessThan(.999),lo(0,0,1),lo(1,0,0)),c=Jh(Au(i,h)).toVar(),d=Au(h,c).toVar();jp({start:ro(0),end:r},({i:i})=>{const p=lf(i,r),m=cf(p,lo(0,0,1),e),g=Jh(c.mul(m.x).add(d.mul(m.y)).add(h.mul(m.z))),f=Jh(g.mul(Eu(h,g).mul(2)).sub(h)),y=Tu(Eu(h,f),0);Ja(y.greaterThan(0),()=>{const e=af(s,f,t,n,a,o);u.addAssign(e.mul(y)),l.addAssign(y)})}),Ja(l.greaterThan(0),()=>{u.assign(u.div(l))})}),go(u,1)}),pf=[.125,.215,.35,.446,.526,.582],mf=20,gf=new cn(-1,1,1,-1,0,1),ff=new an(90,1),yf=new Us;let bf=null,_f=0,xf=0;const vf=new It,Tf=new WeakMap,Sf=[3,1,5,0,4,2],wf=rf(Bl(),Pl("faceIndex")).normalize(),Mf=lo(wf.x,wf.y,wf.z);class Nf{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,s=.1,i=100,r={}){const{size:n=256,position:a=vf,renderTarget:o=null}=r;if(this._setSize(n),!1===this._hasInitialized){yt('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const n=o||this._allocateTarget();return r.renderTarget=n,this.fromSceneAsync(e,t,s,i,r),n}bf=this._renderer.getRenderTarget(),_f=this._renderer.getActiveCubeFace(),xf=this._renderer.getActiveMipmapLevel();const h=o||this._allocateTarget();return h.depthBuffer=!0,this._init(h),this._sceneToCubeUV(e,s,i,h,a),t>0&&this._blur(h,0,0,t),this._applyPMREM(h),this._cleanup(h),h}async fromSceneAsync(e,t=0,s=.1,i=100,r={}){return _t('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,s,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){yt('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromEquirectangularAsync(e,s),s}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return _t('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){yt("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromCubemapAsync(e,t),s}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return _t('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Rf(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Pf(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===B||e.mapping===F?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(bf,_f,xf),e.scissorTest=!1,Af(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),bf=this._renderer.getRenderTarget(),_f=this._renderer.getActiveCubeFace(),xf=this._renderer.getActiveMipmapLevel();const s=t||this._allocateTarget();return this._init(s),this._textureToCubeUV(e,s),this._applyPMREM(s),this._cleanup(s),s}_allocateTarget(){return Ef(3*Math.max(this._cubeSize,112),4*this._cubeSize)}_init(e){if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=Ef(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=function(e){const t=[],s=[],i=[];let r=e;const n=e-4+1+pf.length;for(let a=0;a<n;a++){const n=Math.pow(2,r);t.push(n);let o=1/n;a>e-4?o=pf[a-e+4-1]:0===a&&(o=0),s.push(o);const h=1/(n-2),u=-h,l=1+h,c=[u,u,l,u,l,l,u,u,l,l,u,l],d=6,p=6,m=3,g=2,f=1,y=new Float32Array(m*p*d),b=new Float32Array(g*p*d),_=new Float32Array(f*p*d);for(let e=0;e<d;e++){const t=e%3*2/3-1,s=e>2?0:-1,i=[t,s,0,t+2/3,s,0,t+2/3,s+1,0,t,s,0,t+2/3,s+1,0,t,s+1,0],r=Sf[e];y.set(i,m*p*r),b.set(c,g*p*r);const n=[r,r,r,r,r,r];_.set(n,f*p*r)}const x=new ki;x.setAttribute("position",new Si(y,m)),x.setAttribute("uv",new Si(b,g)),x.setAttribute("faceIndex",new Si(_,f)),i.push(new dr(x,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:s}}(t)),this._blurMaterial=function(e,t,s){const i=ql(new Array(mf).fill(0)),r=oh(new It(0,1,0)),n=oh(0),a=so(mf),o=oh(0),h=oh(1),u=Vl(),l=oh(0),c=so(1/t),d=so(1/s),p=so(e),m={n:a,latitudinal:o,weights:i,poleAxis:r,outputDirection:Mf,dTheta:n,samples:h,envMap:u,mipInt:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=Cf("blur");return g.fragmentNode=hf({...m,latitudinal:o.equal(1)}),Tf.set(g,m),g}(t,e.width,e.height),this._ggxMaterial=function(e,t,s){const i=Vl(),r=oh(0),n=oh(0),a=so(1/t),o=so(1/s),h=so(e),u={envMap:i,roughness:r,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:h},l=Cf("ggx");return l.fragmentNode=df({...u,N_immutable:Mf,GGX_SAMPLES:ro(512)}),Tf.set(l,u),l}(t,e.width,e.height)}}async _compileMaterial(e){const t=new dr(new ki,e);await this._renderer.compile(t,gf)}_sceneToCubeUV(e,t,s,i,r){const n=ff;n.near=t,n.far=s;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],h=this._renderer,u=h.autoClear;h.getClearColor(yf),h.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new dr(new Fr,new er({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const l=this._backgroundBox,c=l.material;let d=!1;const p=e.background;p?p.isColor&&(c.color.copy(p),e.background=null,d=!0):(c.color.copy(yf),d=!0),h.setRenderTarget(i),h.clear(),d&&h.render(l,n);for(let t=0;t<6;t++){const s=t%3;0===s?(n.up.set(0,a[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x+o[t],r.y,r.z)):1===s?(n.up.set(0,0,a[t]),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y+o[t],r.z)):(n.up.set(0,a[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;Af(i,s*u,t>2?u:0,u,u),h.render(e,n)}h.autoClear=u,e.background=p}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===B||e.mapping===F;i?null===this._cubemapMaterial&&(this._cubemapMaterial=Rf(e)):null===this._equirectMaterial&&(this._equirectMaterial=Pf(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const a=this._cubeSize;Af(t,0,0,3*a,2*a),s.setRenderTarget(t),s.render(n,gf)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let t=1;t<i;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=s}_applyGGXFilter(e,t,s){const i=this._renderer,r=this._pingPongRenderTarget,n=this._ggxMaterial,a=this._lodMeshes[s];a.material=n;const o=Tf.get(n),h=s/(this._lodMeshes.length-1),u=t/(this._lodMeshes.length-1),l=Math.sqrt(h*h-u*u)*(0+1.25*h),{_lodMax:c}=this,d=this._sizeLods[s],p=3*d*(s>c-4?s-c+4:0),m=4*(this._cubeSize-d);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=l,o.mipInt.value=c-t,Af(r,p,m,3*d,2*d),i.setRenderTarget(r),i.render(a,gf),r.texture.frame=(r.texture.frame||0)+1,o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=c-s,Af(e,p,m,3*d,2*d),i.setRenderTarget(e),i.render(a,gf)}_blur(e,t,s,i,r){const n=this._pingPongRenderTarget;this._halfBlur(e,n,t,s,i,"latitudinal",r),this._halfBlur(n,e,s,s,i,"longitudinal",r)}_halfBlur(e,t,s,i,r,n,a){const o=this._renderer,h=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&bt("blur direction must be either latitudinal or longitudinal!");const u=this._lodMeshes[i];u.material=h;const l=Tf.get(h),c=this._sizeLods[s]-1,d=isFinite(r)?Math.PI/(2*c):2*Math.PI/39,p=r/d,m=isFinite(r)?1+Math.floor(3*p):mf;m>mf&&yt(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const g=[];let f=0;for(let e=0;e<mf;++e){const t=e/p,s=Math.exp(-t*t/2);g.push(s),0===e?f+=s:e<m&&(f+=2*s)}for(let e=0;e<g.length;e++)g[e]=g[e]/f;e.texture.frame=(e.texture.frame||0)+1,l.envMap.value=e.texture,l.samples.value=m,l.weights.array=g,l.latitudinal.value="latitudinal"===n?1:0,a&&(l.poleAxis.value=a);const{_lodMax:y}=this;l.dTheta.value=d,l.mipInt.value=y-s;const b=this._sizeLods[i];Af(t,3*b*(i>y-4?i-y+4:0),4*(this._cubeSize-b),3*b,2*b),o.setRenderTarget(t),o.render(u,gf)}}function Ef(e,t){const s=new ts(e,t,{magFilter:z,minFilter:z,generateMipmaps:!1,type:K,format:ie,colorSpace:qe});return s.texture.mapping=306,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function Af(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function Cf(e){const t=new vm;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function Rf(e){const t=Cf("cubemap");return t.fragmentNode=od(e,Mf),t}function Pf(e){const t=Cf("equirect");return t.fragmentNode=Vl(e,Am(Mf),0),t}const Bf=new WeakMap;function Ff(e,t,s){const i=function(e){let t=Bf.get(e);void 0===t&&(t=new WeakMap,Bf.set(e,t));return t}(t);let r=i.get(e);if((void 0!==r?r.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const s=6;for(let i=0;i<s;i++)void 0!==e[i]&&t++;return t===s}(t))return null;r=s.fromCubemap(e,r)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;r=s.fromEquirectangular(e,r)}r.pmremVersion=e.pmremVersion,i.set(e,r)}return r.texture}class Df extends ta{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new Jt;i.isRenderTargetTexture=!0,this._texture=Vl(i),this._width=oh(0),this._height=oh(0),this._maxMip=oh(0),this.updateBeforeType=Gn}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,s=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:s,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const s=t?t.pmremVersion:-1,i=this._value;s!==i.pmremVersion&&(t=!0===i.isPMREMTexture?i:Ff(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Nf(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Jc.mul(lo(t.x,t.y.negate(),t.z));let s=this.levelNode;return null===s&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),nf(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const If=Wa(Df).setParameterLength(1,3),Lf=new WeakMap;class Of extends Yp{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const i=s.isTextureNode?s.value:t[s.property],r=this._getPMREMNodeCache(e.renderer);let n=r.get(i);void 0===n&&(n=If(i),r.set(i,n)),s=n}const i=!0===t.useAnisotropy||t.anisotropy>0?Fd:$c,r=s.context(Uf(Ao,i)).mul(Zc),n=s.context(kf(Wc)).mul(Math.PI).mul(Zc),a=_l(r),o=_l(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const h=e.context.lightingModel.clearcoatRadiance;if(h){const e=s.context(Uf(Po,Hc)).mul(Zc),t=_l(e);h.addAssign(t)}}_getPMREMNodeCache(e){let t=Lf.get(e);return void 0===t&&(t=new WeakMap,Lf.set(e,t)),t}}const Uf=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=Ic.negate().reflect(t),s=Pu(e).mix(s,t).normalize(),s=s.transformDirection(yc)),s),getTextureLevel:()=>e}},kf=e=>({getUV:()=>e,getTextureLevel:()=>so(1)}),zf=new Ur;class Vf extends vm{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(zf),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Of(t):null}setupLightingModel(){return new Vg}setupSpecular(){const e=Du(lo(.04),Mo.rgb,Co);Vo.assign(lo(.04)),Go.assign(e),jo.assign(1)}setupVariants(){const e=this.metalnessNode?so(this.metalnessNode):ep;Co.assign(e);let t=this.roughnessNode?so(this.roughnessNode):Jd;t=Qm({roughness:t}),Ao.assign(t),this.setupSpecular(),No.assign(Mo.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Gf=new kr;class jf extends Vf{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(Gf),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?so(this.iorNode):mp;Xo.assign(e),Vo.assign(vu(Ru(Xo.sub(1).div(Xo.add(1))).mul(Kd),lo(1)).mul(Yd)),Go.assign(Du(Vo,Mo.rgb,Co)),jo.assign(Du(Yd,1,Co))}setupLightingModel(){return new Vg(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?so(this.clearcoatNode):sp,t=this.clearcoatRoughnessNode?so(this.clearcoatRoughnessNode):ip;Ro.assign(e),Po.assign(Qm({roughness:t}))}if(this.useSheen){const e=this.sheenNode?lo(this.sheenNode):ap,t=this.sheenRoughnessNode?so(this.sheenRoughnessNode):op;Bo.assign(e),Fo.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?so(this.iridescenceNode):up,t=this.iridescenceIORNode?so(this.iridescenceIORNode):lp,s=this.iridescenceThicknessNode?so(this.iridescenceThicknessNode):cp;Do.assign(e),Io.assign(t),Lo.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?ao(this.anisotropyNode):hp).toVar();Uo.assign(e.length()),Ja(Uo.equal(0),()=>{e.assign(ao(1,0))}).Else(()=>{e.divAssign(ao(Uo)),Uo.assign(Uo.saturate())}),Oo.assign(Uo.pow2().mix(Ao.pow2(),1)),ko.assign(Bd[0].mul(e.x).add(Bd[1].mul(e.y))),zo.assign(Bd[1].mul(e.x).sub(Bd[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?so(this.transmissionNode):dp,t=this.thicknessNode?so(this.thicknessNode):pp,s=this.attenuationDistanceNode?so(this.attenuationDistanceNode):gp,i=this.attenuationColorNode?lo(this.attenuationColorNode):fp;if(Yo.assign(e),Ko.assign(t),Qo.assign(s),Zo.assign(i),this.useDispersion){const e=this.dispersionNode?so(this.dispersionNode):Tp;Jo.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?lo(this.clearcoatNormalNode):rp}setup(e){e.context.setupClearcoatNormal=()=>Yu(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const $f=Ka(({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=ao(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=pd("gradientMap","texture").context({getUV:()=>r});return lo(e.r)}{const e=r.fwidth().mul(.5);return Du(lo(.7),lo(1),Uu(so(.7).sub(e.x),so(.7).add(e.x),r.x))}});class Wf extends Om{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const r=$f({normal:kc,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(r.mul(Gm({diffuseColor:Mo.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(Gm({diffuseColor:Mo}))),i.indirectDiffuse.mulAssign(t)}}const Hf=new Vr;class qf extends vm{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Hf),this.setValues(e)}setupLightingModel(){return new Wf}}const Xf=Ka(()=>{const e=lo(Ic.z,0,Ic.x.negate()).normalize(),t=Ic.cross(e);return ao(e.dot($c),t.dot($c)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),Yf=new $r;class Kf extends vm{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Yf),this.setValues(e)}setupVariants(e){const t=Xf;let s;s=e.material.matcap?pd("matcap","texture").context({getUV:()=>t}):lo(Du(.2,.8,t.y)),Mo.rgb.mulAssign(s.rgb)}}class Qf extends ta{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:s}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return _o(e,i,i.negate(),e).mul(s)}{const e=t,i=vo(go(1,0,0,0),go(0,su(e.x),tu(e.x).negate(),0),go(0,tu(e.x),su(e.x),0),go(0,0,0,1)),r=vo(go(su(e.y),0,tu(e.y),0),go(0,1,0,0),go(tu(e.y).negate(),0,su(e.y),0),go(0,0,0,1)),n=vo(go(su(e.z),tu(e.z).negate(),0,0),go(tu(e.z),su(e.z),0,0),go(0,0,1,0),go(0,0,0,1));return i.mul(r).mul(n).mul(go(s,1)).xyz}}}const Zf=Wa(Qf).setParameterLength(2),Jf=new Wi;class ey extends vm{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(Jf),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,{positionNode:i,rotationNode:r,scaleNode:n,sizeAttenuation:a}=this,o=wc.mul(lo(i||0));let h=ao(Tc[0].xyz.length(),Tc[1].xyz.length());null!==n&&(h=h.mul(ao(n))),s.isPerspectiveCamera&&!1===a&&(h=h.mul(o.z.negate()));let u=Cc.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,s)=>new rl(e,t,s))("center","vec2",t);u=u.sub(e.sub(.5))}u=u.mul(h);const l=so(r||np),c=Zf(u,l);return go(o.xy.add(c),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const ty=new Ar,sy=new Ft;class iy extends ey{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(ty),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return wc.mul(lo(e||Rc)).xyz}setupVertexSprite(e){const{material:t,camera:s}=e,{rotationNode:i,scaleNode:r,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let h=null!==n?ao(n):vp;h=h.mul(Zl),s.isPerspectiveCamera&&!0===a&&(h=h.mul(ry.div(Dc.z.negate()))),r&&r.isNode&&(h=h.mul(ao(r)));let u=Cc.xy;if(i&&i.isNode){const e=so(i);u=Zf(u,e)}return u=u.mul(h),u=u.div(ic.div(2)),u=u.mul(o.w),o=o.add(go(u,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const ry=oh(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(sy);this.value=.5*t.y});class ny extends Om{constructor(){super(),this.shadowNode=so(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Mo.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Mo.rgb)}}const ay=new Or;class oy extends vm{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(ay),this.setValues(e)}setupLightingModel(){return new ny}}So("vec3"),So("vec3"),So("vec3");class hy{constructor(e,t,s){this.renderer=e,this.nodes=t,this.info=s,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,s)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,s),this.renderer._inspector.finish()};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class uy{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let s=this.weakMaps[t];return void 0===s&&(s=new WeakMap,this.weakMaps[t]=s),s}get(e){let t=this._getWeakMap(e);for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let s=this._getWeakMap(e);for(let t=0;t<e.length-1;t++){const i=e[t];!1===s.has(i)&&s.set(i,new WeakMap),s=s.get(i)}return s.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),void 0===t)return!1;return t.delete(e[e.length-1])}}let ly=0;class cy{constructor(e,t,s,i,r,n,a,o,h,u){this.id=ly++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=r,this.scene=n,this.camera=a,this.lightsNode=o,this.context=h,this.geometry=i.geometry,this.version=r.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=u,this.clippingContextCacheKey=null!==u?u.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set,r={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),r[n.name]=e.id),void 0===e)continue;s.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;i.add(a)}return this.attributes=s,this.attributesId=r,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:r}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let h=1;if(!0===s.isInstancedBufferGeometry?h=s.instanceCount:void 0!==e.count&&(h=Math.max(0,e.count)),0===h)return null;if(n.instanceCount=h,!0===e.isBatchedMesh)return n;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let l=r.start*u,c=(r.start+r.count)*u;null!==i&&(l=Math.max(l,i.start*u),c=Math.min(c,(i.start+i.count)*u));const d=s.attributes.position;let p=1/0;o?p=a.count:null!=d&&(p=d.count),l=Math.max(l,0),c=Math.min(c,p);const m=c-l;return m<0||m===1/0?null:(n.vertexCount=m,n.firstVertex=l,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const s of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[s];t+="morph-"+s+",";for(let e=0,s=i.length;e<s;e++){t+=i[e].id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:s}=this;let i=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let s=Object.getPrototypeOf(e);for(;s;){const e=Object.getOwnPropertyDescriptors(s);for(const s in e)if(void 0!==e[s]){const i=e[s];i&&"function"==typeof i.get&&t.push(s)}s=Object.getPrototypeOf(s)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const r=t[e];let n;if(null!==r){const e=typeof r;"number"===e?n=0!==r?"1":"0":"object"===e?(n="{",r.isTexture&&(n+=r.mapping,!0===s.backend.isWebGPUBackend&&(n+=r.magFilter,n+=r.minFilter,n+=r.wrapS,n+=r.wrapT,n+=r.wrapR)),n+="}"):n=String(r)}else n=String(r);i+=n+","}return i+=this.clippingContextCacheKey+",",e.geometry&&(i+=this.getGeometryCacheKey()),e.skeleton&&(i+=e.skeleton.bones.length+","),e.isBatchedMesh&&(i+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(i+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1||Array.isArray(e.morphTargetInfluences))&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",Rn(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(null!==this.attributes){const e=this.attributesId;for(const t in e){const s=this.geometry.getAttribute(t);if(void 0===s||e[t]!==s.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Bn(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Bn(e,1)),e=Bn(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const dy=[];class py{constructor(e,t,s,i,r,n){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=r,this.info=n,this.chainMaps={}}get(e,t,s,i,r,n,a,o){const h=this.getChainMap(o);dy[0]=e,dy[1]=t,dy[2]=n,dy[3]=r;let u=h.get(dy);return void 0===u?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,a,o),h.set(dy,u)):(u.camera=i,u.updateClipping(a),u.needsGeometryUpdate&&u.setGeometry(e.geometry),(u.version!==t.version||u.needsUpdate)&&(u.initialCacheKey!==u.getCacheKey()?(u.dispose(),u=this.get(e,t,s,i,r,n,a,o)):u.version=t.version)),dy[0]=null,dy[1]=null,dy[2]=null,dy[3]=null,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new uy)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,a,o,h,u,l){const c=this.getChainMap(l),d=new cy(e,t,s,i,r,n,a,o,h,u);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),c.delete(d.getChainArray())},d}}class my{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const gy=1,fy=2,yy=3,by=4,_y=16;class xy extends my{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===gy?this.backend.createAttribute(e):t===fy?this.backend.createIndexAttribute(e):t===yy?this.backend.createStorageAttribute(e):t===by&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version<t.version||t.usage===at)&&(this.backend.updateAttribute(e),s.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function vy(e){return null!==e.index?e.index.version:e.attributes.position.version}function Ty(e){return null!==e.index?e.index.id:e.attributes.position.id}function Sy(e){const t=[],s=e.index,i=e.attributes.position;if(null!==s){const e=s.array;for(let s=0,i=e.length;s<i;s+=3){const i=e[s+0],r=e[s+1],n=e[s+2];t.push(i,r,r,n,n,i)}}else{for(let e=0,s=i.array.length/3-1;e<s;e+=3){const s=e+0,i=e+1,r=e+2;t.push(s,i,i,r,r,s)}}const r=new(i.count>=65535?Mi:wi)(t,1);return r.version=vy(e),r.__id=Ty(e),r}class wy extends my{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",s),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",s),this._geometryDisposeListeners.set(t,s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,yy):this.updateAttribute(e,gy);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,fy);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,by)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(!0===s.wireframe){const e=this.wireframes;let s=e.get(t);void 0===s?(s=Sy(t),e.set(t,s)):s.version===vy(t)&&s.__id===Ty(t)||(this.attributes.delete(s),s=Sy(t),e.set(t,s)),i=s}return i}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class My{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):bt("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class Ny{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Ey extends Ny{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class Ay extends Ny{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Cy=0;class Ry{constructor(e,t,s,i=null,r=null){this.id=Cy++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=r,this.usedTimes=0}}class Py extends my{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let a=this.programs.compute.get(n.computeShader);void 0===a&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),a=new Ry(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),s.createProgram(a));const o=this._getComputeCacheKey(e,a);let h=this.caches.get(o);void 0===h&&(r&&0===r.usedTimes&&this._releasePipeline(r),h=this._getComputePipeline(e,a,o,t)),h.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=h}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new Ry(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),s.createProgram(o));let h=this.programs.fragment.get(n.fragmentShader);void 0===h&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),h=new Ry(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,h),s.createProgram(h));const u=this._getRenderCacheKey(e,o,h);let l=this.caches.get(u);void 0===l?(r&&0===r.usedTimes&&this._releasePipeline(r),l=this._getRenderPipeline(e,o,h,u,t)):e.pipeline=l,l.usedTimes++,o.usedTimes++,h.usedTimes++,i.pipeline=l}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,s,i){s=s||this._getComputeCacheKey(e,t);let r=this.caches.get(s);return void 0===r&&(r=new Ay(s,t),this.caches.set(s,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,s,i,r){i=i||this._getRenderCacheKey(e,t,s);let n=this.caches.get(i);return void 0===n&&(n=new Ey(i,t,s),this.caches.set(i,n),e.pipeline=n,this.backend.createRenderPipeline(e,r)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class By extends my{constructor(e,t,s,i,r,n){super(),this.backend=e,this.textures=s,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),s.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),s.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,s=e.isIndirectStorageBufferAttribute?by:yy;this.attributes.update(e,s)}}_update(e,t){const{backend:s}=this;let i=!1,r=!0,n=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?by:yy,n=s.get(t);this.attributes.update(e,r),n.attribute!==e&&(n.attribute=e,i=!0)}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),h=t.texture,u=this.textures.get(h);o&&(this.textures.updateTexture(h),t.generation!==u.generation&&(t.generation=u.generation,i=!0),u.bindGroups.add(e));if(void 0!==s.get(h).externalTexture||u.isDefaultTexture?r=!1:(n=10*n+h.id,a+=h.version),!0===h.isStorageTexture&&!0===h.mipmapsAutoUpdate){const e=this.get(h);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(h)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(h),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,i=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===i&&this.backend.updateBindings(e,t,r?n:0,a)}}function Fy(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?e.z-t.z:e.id-t.id}function Dy(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function Iy(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class Ly{constructor(e,t,s){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,s),this.lightsArray=[],this.scene=t,this.camera=s,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,i,r,n,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:r,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=s,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,s,i,r,n,a){const o=this.getNextRenderItem(e,t,s,i,r,n,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(Iy(s)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,s,i,r,n,a){const o=this.getNextRenderItem(e,t,s,i,r,n,a);!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(Iy(s)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||Fy),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Dy),this.transparent.length>1&&this.transparent.sort(t||Dy)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.groupOrder=null,t.renderOrder=null,t.z=null,t.group=null,t.clippingContext=null}}}const Oy=[];class Uy{constructor(e){this.lighting=e,this.lists=new uy}get(e,t){const s=this.lists;Oy[0]=e,Oy[1]=t;let i=s.get(Oy);return void 0===i&&(i=new Ly(this.lighting,e,t),s.set(Oy,i)),Oy[0]=null,Oy[1]=null,i}dispose(){this.lists=new uy}}let ky=0;class zy{constructor(){this.id=ky++,this.mrt=null,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new es,this.scissor=!1,this.scissorValue=new es,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.isRenderContext=!0}getCacheKey(){return Vy(this)}}function Vy(e){const{textures:t,activeCubeFace:s,activeMipmapLevel:i}=e,r=[s,i];for(const e of t)r.push(e.id);return Pn(r)}class Gy{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,s=0){let i;if(null===e)i="default";else{const t=e.texture.format,s=e.texture.type;i=`${e.textures.length}:${t}:${s}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const r=i+"-"+(null!==t?t.id:"default")+"-"+s;let n=this._renderContexts[r];return void 0===n&&(n=new zy,n.mrt=t,this._renderContexts[r]=n),null!==e&&(n.sampleCount=0===e.samples?1:e.samples),n.clearDepthValue=this.renderer.getClearDepth(),n.clearStencilValue=this.renderer.getClearStencil(),n}dispose(){this._renderContexts={}}}const jy=new It;class $y extends my{constructor(e,t,s){super(),this.renderer=e,this.backend=t,this.info=s}updateRenderTarget(e,t=0){const s=this.get(e),i=0===e.samples?1:e.samples,r=s.depthTextureMips||(s.depthTextureMips={}),n=e.textures,a=this.getSize(n[0]),o=a.width>>t,h=a.height>>t;let u=e.depthTexture||r[t];const l=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===u&&l&&(u=new Pr,u.format=e.stencilBuffer?ne:re,u.type=e.stencilBuffer?J:X,u.image.width=o,u.image.height=h,u.image.depth=a.depth,u.renderTarget=e,u.isArrayTexture=!0===e.multiview&&a.depth>1,r[t]=u),s.width===a.width&&a.height===s.height||(c=!0,u&&(u.needsUpdate=!0,u.image.width=o,u.image.height=h,u.image.depth=u.isArrayTexture?u.image.depth:1)),s.width=a.width,s.height=a.height,s.textures=n,s.depthTexture=u||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(c=!0,u&&(u.needsUpdate=!0),s.sampleCount=i);const d={sampleCount:i};if(!0!==e.isXRRenderTarget){for(let e=0;e<n.length;e++){const t=n[e];c&&(t.needsUpdate=!0),this.updateTexture(t,d)}u&&this.updateTexture(u,d)}!0!==s.initialized&&(s.initialized=!0,s.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",s.onDispose))}updateTexture(e,t={}){const s=this.get(e);if(!0===s.initialized&&s.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,r=this.backend;if(i&&!0===s.initialized&&r.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:j}const{width:n,height:a,depth:o}=this.getSize(e);if(t.width=n,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,i||!0===e.isStorageTexture||!0===e.isExternalTexture)r.createTexture(e,t),s.generation=e.version;else if(e.version>0){const i=e.image;if(void 0===i)yt("Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)yt("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const s=[];for(const t of e.images)s.push(t);t.images=s}else t.image=i;void 0!==s.isDefaultTexture&&!0!==s.isDefaultTexture||(r.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t);const n=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!n&&r.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else r.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version;!0!==s.initialized&&(s.initialized=!0,s.generation=e.version,s.bindGroups=new Set,this.info.memory.textures++,e.isVideoTexture&&!0===jt.enabled&&jt.getTransfer(e.colorSpace)!==Ye&&yt("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),s.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",s.onDispose)),s.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=jy){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),"undefined"!=typeof HTMLVideoElement&&s instanceof HTMLVideoElement?(t.width=s.videoWidth||1,t.height=s.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&s instanceof VideoFrame?(t.width=s.displayWidth||1,t.height=s.displayHeight||1,t.depth=1):(t.width=s.width||1,t.height=s.height||1,t.depth=e.isCubeTexture?6:s.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return i=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),s=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e<s.length;e++)this._destroyTexture(s[e]);i&&this._destroyTexture(i),this.delete(e),this.backend.delete(e)}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const s=t.isDefaultTexture;if(this.backend.destroyTexture(e,s),t.bindGroups)for(const e of t.bindGroups){const t=this.backend.get(e);t.groups=void 0,t.versions=void 0}this.delete(e),this.info.memory.textures--}}}class Wy extends Us{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class Hy extends To{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const s=this.getNodeType(e),i=e.getStructTypeNode(s);let r;return null!==i?r=i.getMemberType(e,t):(bt(`TSL: Member "${t}" not found in struct "${s}".`,new An),r="float"),r}getHash(){return this.uuid}generate(){return this.name}}class qy extends Zn{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this.isStackNode=!0}getElementType(e){return this.hasOutput(e)?this.outputNode.getElementType(e):"void"}getNodeType(e){return this.hasOutput(e)?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput(e)?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=this.nodes.length){return!0!==e.isNode?(bt("TSL: Invalid node added to stack.",new An),this):(this.nodes.splice(t,0,e),this)}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const s=new za(t);return this._currentCond=Gu(e,s),this.addToStack(this._currentCond)}ElseIf(e,t){const s=new za(t),i=Gu(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new za(e),this}Switch(e){return this._expressionNode=Va(e),this}Case(...e){const t=[];if(e.length>=2)for(let s=0;s<e.length-1;s++)t.push(this._expressionNode.equal(Va(e[s])));else bt("TSL: Invalid parameter length. Case() requires at least two parameters.",new An);const s=new za(e[e.length-1]);let i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);const r=Gu(i,s);return null===this._currentCond?(this._currentCond=r,this.addToStack(this._currentCond)):(this._currentCond.elseNode=r,this._currentCond=r,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let s=0;for(const i of this.getChildren())i.isVarNode&&i.isIntent(e)&&!0!==i.isAssign(e)||(t["node"+s++]=i);return t.outputNode||null}hasOutput(e){return this.outputNode&&this.outputNode.isNode&&"void"!==this.outputNode.getNodeType(e)}build(e,...t){const s=Za(),i=e.buildStage;Qa(this),e.setActiveStack(this);const r=t=>{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===i)t.build(e);else if("analyze"===i)t.build(e,this);else if("generate"===i){const s=e.getDataFromNode(t,"any").stages,i=s&&s[e.shaderStage];if(t.isVarNode&&i&&1===i.length&&i[0]&&i[0].isStackNode)return;t.build(e,"void")}},n=[...this.nodes];for(const e of n)r(e);this._currentNode=null;const a=this.nodes.filter(e=>-1===n.indexOf(e));for(const e of a)r(e);let o;return o=this.hasOutput(e)?this.outputNode.build(e,...t):super.build(e,...t),Qa(s),e.removeActiveStack(this),o}}const Xy=Wa(qy).setParameterLength(0,1);class Yy extends ta{static get type(){return"BitcastNode"}constructor(e,t,s=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=s,this.isBitcastNode=!0}getNodeType(e){if(null!==this.inputType){const t=this.valueNode.getNodeType(e),s=e.getTypeLength(t);return e.getTypeFromLength(s,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let s="";if(null!==this.inputType){const t=this.valueNode.getNodeType(e);s=1===e.getTypeLength(t)?this.inputType:e.changeComponentType(t,this.inputType)}else s=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,s)}( ${this.valueNode.build(e,s)} )`}}const Ky=qa(Yy).setParameterLength(2),Qy={};class Zy extends Uh{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,s){"int"===s?t.assign(Ky(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return ro;case"int":return io;case"uvec2":return ho;case"uvec3":return po;case"uvec4":return yo;case"ivec2":return oo;case"ivec3":return co;case"ivec4":return fo}}_createTrailingZerosBaseLayout(e,t){const s=this._returnDataNode(t),i=Ka(([e])=>{const i=ro(0);this._resolveElementType(e,i,t);const r=(e=>new Yy(e,"uint","float"))(so(i.bitAnd(lu(i)))),n=r.shiftRight(23).sub(127);return s(n)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createLeadingZerosBaseLayout(e,t){const s=this._returnDataNode(t),i=Ka(([e])=>{Ja(e.equal(ro(0)),()=>ro(32));const i=ro(0),r=ro(0);return this._resolveElementType(e,i,t),Ja(i.shiftRight(16).equal(0),()=>{r.addAssign(16),i.shiftLeftAssign(16)}),Ja(i.shiftRight(24).equal(0),()=>{r.addAssign(8),i.shiftLeftAssign(8)}),Ja(i.shiftRight(28).equal(0),()=>{r.addAssign(4),i.shiftLeftAssign(4)}),Ja(i.shiftRight(30).equal(0),()=>{r.addAssign(2),i.shiftLeftAssign(2)}),Ja(i.shiftRight(31).equal(0),()=>{r.addAssign(1)}),s(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createOneBitsBaseLayout(e,t){const s=this._returnDataNode(t),i=Ka(([e])=>{const i=ro(0);this._resolveElementType(e,i,t),i.assign(i.sub(i.shiftRight(ro(1)).bitAnd(ro(1431655765)))),i.assign(i.bitAnd(ro(858993459)).add(i.shiftRight(ro(2)).bitAnd(ro(858993459))));const r=i.add(i.shiftRight(ro(4))).bitAnd(ro(252645135)).mul(ro(16843009)).shiftRight(ro(24));return s(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createMainLayout(e,t,s,i){const r=this._returnDataNode(t),n=Ka(([e])=>{if(1===s)return r(i(e));{const t=r(0),n=["x","y","z","w"];for(let r=0;r<s;r++){const s=n[r];t[s].assign(i(e[s]))}return t}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return n}setup(e){const{method:t,aNode:s}=this,{renderer:i}=e;if(i.backend.isWebGPUBackend)return super.setup(e);const r=this.getInputType(e),n=e.getElementType(r),a=e.getTypeLength(r),o=`${t}_base_${n}`,h=`${t}_${r}`;let u=Qy[o];if(void 0===u){switch(t){case Zy.COUNT_LEADING_ZEROS:u=this._createLeadingZerosBaseLayout(o,n);break;case Zy.COUNT_TRAILING_ZEROS:u=this._createTrailingZerosBaseLayout(o,n);break;case Zy.COUNT_ONE_BITS:u=this._createOneBitsBaseLayout(o,n)}Qy[o]=u}let l=Qy[h];void 0===l&&(l=this._createMainLayout(h,r,a,u),Qy[h]=l);return Ka(()=>l(s))()}}Zy.COUNT_TRAILING_ZEROS="countTrailingZeros",Zy.COUNT_LEADING_ZEROS="countLeadingZeros",Zy.COUNT_ONE_BITS="countOneBits",new _r,new It,new It,new It,new is,new It(0,0,-1),new es,new It,new It,new es,new Ft;const Jy=new ts;Jl.flipX(),Jy.depthTexture=new Pr(1,1);const eb=new cn(-1,1,1,-1,0,1);class tb extends ki{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Ei([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Ei(t,2))}}const sb=new tb;class ib extends dr{constructor(e=null){super(sb,e),this.camera=eb,this.isQuadMesh=!0}async renderAsync(e){_t('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,eb)}render(e){e.render(this,eb)}}const rb=Ka(([e])=>eu(so(52.9829189).mul(eu(Eu(e,ao(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),nb=Ka(([e,t,s])=>{const i=so(2.399963229728653),r=Yh(so(e).add(.5).div(so(t))),n=so(e).mul(i).add(s);return ao(su(n),tu(n)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class ab extends Zn{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===ab.OBJECT?this.updateType=jn:e===ab.MATERIAL?this.updateType=Gn:e===ab.BEFORE_OBJECT?this.updateBeforeType=jn:e===ab.BEFORE_MATERIAL&&(this.updateBeforeType=Gn)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}ab.OBJECT="object",ab.MATERIAL="material",ab.BEFORE_OBJECT="beforeObject",ab.BEFORE_MATERIAL="beforeMaterial";const ob=new ps,hb=new is,ub=oh(0).setGroup(rh).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),lb=oh(1).setGroup(rh).onRenderUpdate(({scene:e})=>e.backgroundIntensity),cb=oh(new is).setGroup(rh).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&300!==t.mapping?(ob.copy(e.backgroundRotation),ob.x*=-1,ob.y*=-1,ob.z*=-1,hb.makeRotationFromEuler(ob)):hb.identity(),hb}),db=Ka(({texture:e,uv:t})=>{const s=1e-4,i=lo().toVar();return Ja(t.x.lessThan(s),()=>{i.assign(lo(1,0,0))}).ElseIf(t.y.lessThan(s),()=>{i.assign(lo(0,1,0))}).ElseIf(t.z.lessThan(s),()=>{i.assign(lo(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{i.assign(lo(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{i.assign(lo(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{i.assign(lo(0,0,-1))}).Else(()=>{const s=.01,r=e.sample(t.add(lo(-.01,0,0))).r.sub(e.sample(t.add(lo(s,0,0))).r),n=e.sample(t.add(lo(0,-.01,0))).r.sub(e.sample(t.add(lo(0,s,0))).r),a=e.sample(t.add(lo(0,0,-.01))).r.sub(e.sample(t.add(lo(0,0,s))).r);i.assign(lo(r,n,a))}),i.normalize()});class pb extends kl{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return lo(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return db({texture:this,uv:e})}}const mb=Wa(pb).setParameterLength(1,3);Ka(([e,t])=>e.mul(t).floor().div(t));const gb=new Ft;class fb extends kl{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){return e.getNodeProperties(this).passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class yb extends fb{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class bb extends ta{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new Pr;r.isRenderTargetTexture=!0,r.name="depth";const n=new ts(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:K,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=oh(0),this._cameraFar=oh(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=Vn,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return yt("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return yt("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new yb(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new yb(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=cm(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=um(r,s,i)}return t}async compileAsync(e){const t=e.getRenderTarget(),s=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(s)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),this.scope===bb.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s}=this;let i,r;const n=t.getOutputRenderTarget();n&&!0===n.isXRRenderTarget?(r=1,i=t.xr.getCamera(),t.xr.updateCamera(i),gb.set(n.width,n.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(gb)),this._pixelRatio=r,this.setSize(gb.width,gb.height);const a=t.getRenderTarget(),o=t.getMRT(),h=t.autoClear,u=t.transparent,l=t.opaque,c=i.layers.mask,d=t.contextNode,p=s.overrideMaterial;this._cameraNear.value=i.near,this._cameraFar.value=i.far,null!==this._layers&&(i.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(s.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:$u({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const m=s.name;s.name=this.name?this.name:s.name,t.render(s,i),s.name=m,s.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(o),t.autoClear=h,t.transparent=u,t.opaque=l,t.contextNode=d,i.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const s=Math.floor(this._width*this._pixelRatio*this._resolutionScale),i=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(s,i),null!==this._scissor&&this.renderTarget.scissor.copy(this._scissor),null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport)}setScissor(e,t,s,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new es),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,s,i),this._scissor.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setViewport(e,t,s,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new es),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,s,i),this._viewport.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}bb.COLOR="color",bb.DEPTH="depth";const _b=Ka(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),xb=Ka(([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp()).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),vb=Ka(([e,t])=>{const s=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return s.div(i).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Tb=Ka(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),s=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(s)}),Sb=Ka(([e,t])=>{const s=xo(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=xo(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=Tb(e),(e=i.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),wb=xo(lo(1.6605,-.1246,-.0182),lo(-.5876,1.1329,-.1006),lo(-.0728,-.0083,1.1187)),Mb=xo(lo(.6274,.0691,.0164),lo(.3293,.9195,.088),lo(.0433,.0113,.8956)),Nb=Ka(([e])=>{const t=lo(e).toVar(),s=lo(t.mul(t)).toVar(),i=lo(s.mul(s)).toVar();return so(15.5).mul(i.mul(s)).sub(gh(40.14,i.mul(t))).add(gh(31.96,i).sub(gh(6.868,s.mul(t))).add(gh(.4298,s).add(gh(.1191,t).sub(.00232))))}),Eb=Ka(([e,t])=>{const s=lo(e).toVar(),i=xo(lo(.856627153315983,.137318972929847,.11189821299995),lo(.0951212405381588,.761241990602591,.0767994186031903),lo(.0482516061458583,.101439036467562,.811302368396859)),r=xo(lo(1.1271005818144368,-.1413297634984383,-.14132976349843826),lo(-.11060664309660323,1.157823702216272,-.11060664309660294),lo(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=so(-12.47393),a=so(4.026069);return s.mulAssign(t),s.assign(Mb.mul(s)),s.assign(i.mul(s)),s.assign(Tu(s,1e-10)),s.assign(Xh(s)),s.assign(s.sub(n).div(a.sub(n))),s.assign(Iu(s,0,1)),s.assign(Nb(s)),s.assign(r.mul(s)),s.assign(Cu(Tu(lo(0),s),lo(2.2))),s.assign(wb.mul(s)),s.assign(Iu(s,0,1)),s}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Ab=Ka(([e,t])=>{const s=so(.76),i=so(.15);e=e.mul(t);const r=vu(e.r,vu(e.g,e.b)),n=Gu(r.lessThan(.08),r.sub(gh(6.25,r.mul(r))),.04);e.subAssign(n);const a=Tu(e.r,Tu(e.g,e.b));Ja(a.lessThan(s),()=>e);const o=mh(1,s),h=mh(1,o.mul(o).div(a.add(o.sub(s))));e.mulAssign(h.div(a));const u=mh(1,fh(1,i.mul(a.sub(h)).add(1)));return Du(e,lo(h),u)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Cb extends Zn{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=s}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}class Rb extends Cb{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const s=this.getNodeType(e);return e.getStructTypeNode(s).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return void 0===s&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,r=s.type,n=e.getCodeFromNode(this,r);""!==i&&(n.name=i);const a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}function Pb(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||Dc.z).negate()}const Bb=Ka(([e,t],s)=>{const i=Pb(s);return Uu(e,t,i)}),Fb=Ka(([e],t)=>{const s=Pb(t);return e.mul(e,s,s).negate().exp().oneMinus()});Ka(([e,t],s)=>{const i=Pb(s),r=t.sub(Bc.y).max(0).toConst().mul(i).toConst();return e.mul(e,r,r).negate().exp().oneMinus()});const Db=Ka(([e,t])=>go(t.toFloat().mix(Wo.rgb,e.toVec3()),Wo.a));Wa(class extends Zn{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:s}=e;!0===s.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class Ib extends Zn{static get type(){return"AtomicFunctionNode"}constructor(e,t,s){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),s=t.parents,i=this.method,r=this.getNodeType(e),n=this.getInputType(e),a=this.pointerNode,o=this.valueNode,h=[];h.push(`&${a.build(e,n)}`),null!==o&&h.push(o.build(e,n));const u=`${e.getMethod(i,r)}( ${h.join(", ")} )`;if(!(!!s&&(1===s.length&&!0===s[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Ml(u,r).toConst()),t.constNode.build(e);e.addLineFlowCode(u,this)}}Ib.ATOMIC_LOAD="atomicLoad",Ib.ATOMIC_STORE="atomicStore",Ib.ATOMIC_ADD="atomicAdd",Ib.ATOMIC_SUB="atomicSub",Ib.ATOMIC_MAX="atomicMax",Ib.ATOMIC_MIN="atomicMin",Ib.ATOMIC_AND="atomicAnd",Ib.ATOMIC_OR="atomicOr",Ib.ATOMIC_XOR="atomicXor",Wa(Ib);class Lb extends ta{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,s=null){super(),this.method=e,this.aNode=t,this.bNode=s}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,s=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(s)?0:e.getTypeLength(s))?t:s}getNodeType(e){const t=this.method;return t===Lb.SUBGROUP_ELECT?"bool":t===Lb.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,a=this.bNode,o=[];if(s===Lb.SUBGROUP_BROADCAST||s===Lb.SUBGROUP_SHUFFLE||s===Lb.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(n.build(e,i),a.build(e,"float"===t?"int":i))}else s===Lb.SUBGROUP_SHUFFLE_XOR||s===Lb.SUBGROUP_SHUFFLE_DOWN||s===Lb.SUBGROUP_SHUFFLE_UP?o.push(n.build(e,i),a.build(e,"uint")):(null!==n&&o.push(n.build(e,r)),null!==a&&o.push(a.build(e,r)));const h=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(s,i)}${h}`,i,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}let Ob;function Ub(e){Ob=Ob||new WeakMap;let t=Ob.get(e);return void 0===t&&Ob.set(e,t={}),t}function kb(e){const t=Ub(e);return t.shadowMatrix||(t.shadowMatrix=oh("mat4").setGroup(rh).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix)))}function zb(e){const t=Ub(e);return t.position||(t.position=oh(new It).setGroup(rh).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld)))}function Vb(e){const t=Ub(e);return t.viewPosition||(t.viewPosition=oh(new It).setGroup(rh).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new It,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}Lb.SUBGROUP_ELECT="subgroupElect",Lb.SUBGROUP_BALLOT="subgroupBallot",Lb.SUBGROUP_ADD="subgroupAdd",Lb.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",Lb.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",Lb.SUBGROUP_MUL="subgroupMul",Lb.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",Lb.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",Lb.SUBGROUP_AND="subgroupAnd",Lb.SUBGROUP_OR="subgroupOr",Lb.SUBGROUP_XOR="subgroupXor",Lb.SUBGROUP_MIN="subgroupMin",Lb.SUBGROUP_MAX="subgroupMax",Lb.SUBGROUP_ALL="subgroupAll",Lb.SUBGROUP_ANY="subgroupAny",Lb.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",Lb.QUAD_SWAP_X="quadSwapX",Lb.QUAD_SWAP_Y="quadSwapY",Lb.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",Lb.SUBGROUP_BROADCAST="subgroupBroadcast",Lb.SUBGROUP_SHUFFLE="subgroupShuffle",Lb.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",Lb.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",Lb.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",Lb.QUAD_BROADCAST="quadBroadcast";const Gb=e=>yc.transformDirection(zb(e).sub(function(e){const t=Ub(e);return t.targetPosition||(t.targetPosition=oh(new It).setGroup(rh).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),jb=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},$b=new WeakMap,Wb=[];class Hb extends Zn{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=So("vec3","totalDiffuse"),this.totalSpecularNode=So("vec3","totalSpecular"),this.outgoingLightNode=So("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;t<e.length;t++){const s=e[t];if(Wb.push(s.id),Wb.push(s.castShadow?1:0),!0===s.isSpotLight){const e=null!==s.map?s.map.id:-1,t=s.colorNode?s.colorNode.getCacheKey():-1;Wb.push(e,t)}}const t=Pn(Wb);return Wb.length=0,t}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const s of t.nodes)s.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=(e=>e.sort((e,t)=>e.id-t.id))(this._lights),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(Va(e));else{let i=null;if(null!==s&&(i=jb(e.id,s)),null===i){const s=r.getLightNodeClass(e.constructor);if(null===s){yt(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;$b.has(e)?i=$b.get(e):(i=new s(e),$b.set(e,i)),t.push(i)}}this._lightNodes=t}setupDirectLight(e,t,s){const{lightingModel:i,reflectedLight:r}=e.context;i.direct({...s,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,s){const{lightingModel:i,reflectedLight:r}=e.context;i.directRectArea({...s,lightNode:t,reflectedLight:r},e)}setupLights(e,t){for(const s of t)s.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let s=this.outgoingLightNode;const i=e.context,r=i.lightingModel,n=e.getNodeProperties(this);if(r){const{totalDiffuseNode:t,totalSpecularNode:a}=this;i.outgoingLight=s;const o=e.addStack();n.nodes=o.nodes,r.start(e);const{backdrop:h,backdropAlpha:u}=i,{directDiffuse:l,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=i.reflectedLight;let m=l.add(d);null!==h&&(m=lo(null!==u?u.mix(m,h):h)),t.assign(m),a.assign(c.add(p)),s.assign(t.add(a)),r.finish(e),s=s.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,s}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class qb extends Zn{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Gn,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){Xb.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Bc)}}const Xb=So("vec3","shadowPositionWorld");function Yb(e,t){return t=function(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new Us),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}const Kb=new WeakMap,Qb=Ka(({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=Vl(e,t.xy).setName("t_basic");return e.isArrayTexture&&(i=i.depth(s)),i.compare(t.z)}),Zb=Ka(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=Vl(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=ld("mapSize","vec2",s).setGroup(rh),a=ld("radius","float",s).setGroup(rh),o=ao(1).div(n),h=a.mul(o.x),u=rb(tc.xy).mul(6.28318530718);return ph(r(t.xy.add(nb(0,5,u).mul(h)),t.z),r(t.xy.add(nb(1,5,u).mul(h)),t.z),r(t.xy.add(nb(2,5,u).mul(h)),t.z),r(t.xy.add(nb(3,5,u).mul(h)),t.z),r(t.xy.add(nb(4,5,u).mul(h)),t.z)).mul(.2)}),Jb=Ka(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=Vl(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=ld("mapSize","vec2",s).setGroup(rh),a=ao(1).div(n),o=a.x,h=a.y,u=t.xy,l=eu(u.mul(n).add(.5));return u.subAssign(l.mul(a)),ph(r(u,t.z),r(u.add(ao(o,0)),t.z),r(u.add(ao(0,h)),t.z),r(u.add(a),t.z),Du(r(u.add(ao(o.negate(),0)),t.z),r(u.add(ao(o.mul(2),0)),t.z),l.x),Du(r(u.add(ao(o.negate(),h)),t.z),r(u.add(ao(o.mul(2),h)),t.z),l.x),Du(r(u.add(ao(0,h.negate())),t.z),r(u.add(ao(0,h.mul(2))),t.z),l.y),Du(r(u.add(ao(o,h.negate())),t.z),r(u.add(ao(o,h.mul(2))),t.z),l.y),Du(Du(r(u.add(ao(o.negate(),h.negate())),t.z),r(u.add(ao(o.mul(2),h.negate())),t.z),l.x),Du(r(u.add(ao(o.negate(),h.mul(2))),t.z),r(u.add(ao(o.mul(2),h.mul(2))),t.z),l.x),l.y)).mul(1/9)}),e_=Ka(({depthTexture:e,shadowCoord:t,depthLayer:s},i)=>{let r=Vl(e).sample(t.xy);e.isArrayTexture&&(r=r.depth(s)),r=r.rg;const n=r.x,a=Tu(1e-7,r.y.mul(r.y)),o=i.renderer.reversedDepthBuffer?Su(n,t.z):Su(t.z,n),h=so(1).toVar();return Ja(o.notEqual(1),()=>{const e=t.z.sub(n);let s=a.div(a.add(e.mul(e)));s=Iu(mh(s,.3).div(.65)),h.assign(Tu(o,s))}),h}),t_=new uy,s_=[],i_=Ka(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=so(0).toVar("meanVertical"),a=so(0).toVar("squareMeanVertical"),o=e.lessThanEqual(so(1)).select(so(0),so(2).div(e.sub(1))),h=e.lessThanEqual(so(1)).select(so(0),so(-1));jp({start:io(0),end:io(e),type:"int",condition:"<"},({i:e})=>{const u=h.add(so(e).mul(o));let l=i.sample(ph(tc.xy,ao(0,u).mul(t)).div(s));i.value.isArrayTexture&&(l=l.depth(r)),l=l.x,n.addAssign(l),a.addAssign(l.mul(l))}),n.divAssign(e),a.divAssign(e);const u=Yh(a.sub(n.mul(n)).max(0));return ao(n,u)}),r_=Ka(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=so(0).toVar("meanHorizontal"),a=so(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(so(1)).select(so(0),so(2).div(e.sub(1))),h=e.lessThanEqual(so(1)).select(so(0),so(-1));jp({start:io(0),end:io(e),type:"int",condition:"<"},({i:e})=>{const u=h.add(so(e).mul(o));let l=i.sample(ph(tc.xy,ao(u,0).mul(t)).div(s));i.value.isArrayTexture&&(l=l.depth(r)),n.addAssign(l.x),a.addAssign(ph(l.y.mul(l.y),l.x.mul(l.x)))}),n.divAssign(e),a.divAssign(e);const u=Yh(a.sub(n.mul(n)).max(0));return ao(n,u)}),n_=[Qb,Zb,Jb,e_];let a_;const o_=new ib;class h_ extends qb{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r,depthLayer:n}){const a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),o=t({depthTexture:s,shadowCoord:i,shadow:r,depthLayer:n});return a.select(o,so(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=s.biasNode||ld("bias","float",s).setGroup(rh);let n,a=t;if(s.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z;else{const e=a.w;a=a.xy.div(e);const t=ld("near","float",s.camera).setGroup(rh),i=ld("far","float",s.camera).setGroup(rh);n=dm(e.negate(),t,i)}return a=lo(a.x,a.y.oneMinus(),i.reversedDepthBuffer?n.sub(r):n.add(r)),a}getShadowFilterFn(e){return n_[e]}setupRenderTarget(e,t){const s=new Pr(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=t.renderer.reversedDepthBuffer?it:et;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=s,{shadowMap:i,depthTexture:s}}setupShadow(e){const{renderer:t,camera:s}=e,{light:i,shadow:r}=this,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(r,e),o=t.shadowMap.type,h=t.hasCompatibility(ct);if(1!==o&&2!==o||!h?(n.minFilter=O,n.magFilter=O):(n.minFilter=z,n.magFilter=z),r.camera.coordinateSystem=s.coordinateSystem,r.camera.updateProjectionMatrix(),3===o&&!0!==r.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:he,type:K,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:he,type:K,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:he,type:K,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:he,type:K,depthBuffer:!1}));let t=Vl(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let s=Vl(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(s=s.depth(this.depthLayer));const i=ld("blurSamples","float",r).setGroup(rh),o=ld("radius","float",r).setGroup(rh),h=ld("mapSize","vec2",r).setGroup(rh);let u=this.vsmMaterialVertical||(this.vsmMaterialVertical=new vm);u.fragmentNode=i_({samples:i,radius:o,size:h,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMVertical",u=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new vm),u.fragmentNode=r_({samples:i,radius:o,size:h,shadowPass:s,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMHorizontal"}const u=ld("intensity","float",r).setGroup(rh),l=ld("normalBias","float",r).setGroup(rh),c=kb(i).mul(Xb.add(Wc.mul(l))),d=this.setupShadowCoord(e,c),p=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===p)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const m=3===o&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,g=this.setupShadowFilter(e,{filterFn:p,shadowTexture:a.texture,depthTexture:m,shadowCoord:d,shadow:r,depthLayer:this.depthLayer});let f,y;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?f=od(a.texture,d.xyz):(f=Vl(a.texture,d),n.isArrayTexture&&(f=f.depth(this.depthLayer)))),y=f?Du(1,g.rgb.mix(f,1),u.mul(f.a)).toVar():Du(1,g,u).toVar(),this.shadowMap=a,this.shadow.map=a;const b=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return f&&y.toInspector(`${b} / Color`,()=>this.shadowMap.texture.isCubeTexture?od(this.shadowMap.texture):Vl(this.shadowMap.texture)),y.toInspector(`${b} / Depth`,()=>this.shadowMap.texture.isCubeTexture?od(this.shadowMap.texture).r.oneMinus():Gl(this.shadowMap.depthTexture,Bl().mul(Dl(Vl(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Ka(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let s=this._node;return this.setupShadowPosition(e),null===s&&(this._node=s=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(s=e.material.receivedShadowNode(s)),s})()}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:r,scene:n}=e;t.updateMatrices(i),s.setSize(t.mapSize.width,t.mapSize.height,s.depth);const a=n.name;n.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,r.render(n,t.camera),n.name=a}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:r,scene:n,camera:a}=e,o=r.shadowMap.type,h=t.depthTexture.version;this._depthVersionCached=h;const u=i.camera.layers.mask;4294967294&i.camera.layers.mask||(i.camera.layers.mask=a.layers.mask);const l=r.getRenderObjectFunction(),c=r.getMRT(),d=!!c&&c.has("velocity");a_=function(e,t,s){return s=function(e,t){return t=function(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}(t,s=Yb(e,s)),s}(r,n,a_),n.overrideMaterial=(e=>{let t=Kb.get(e);return void 0===t&&(t=new vm,t.colorNode=go(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=0,t.fog=!1,Kb.set(e,t)),t})(s),r.setRenderObjectFunction(((e,t,s,i)=>{s_[0]=e,s_[1]=t;let r=t_.get(s_);return void 0!==r&&r.shadowType===s&&r.useVelocity===i||(r=(r,n,a,o,h,u,...l)=>{(!0===r.castShadow||r.receiveShadow&&3===s)&&(i&&(Un(r).useVelocity=!0),r.onBeforeShadow(e,r,a,t.camera,o,n.overrideMaterial,u),e.renderObject(r,n,a,o,h,u,...l),r.onAfterShadow(e,r,a,t.camera,o,n.overrideMaterial,u))},r.shadowType=s,r.useVelocity=i,t_.set(s_,r)),s_[0]=null,s_[1]=null,r})(r,i,o,d)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(l),3===o&&!0!==i.isPointLightShadow&&this.vsmPass(r),i.camera.layers.mask=u,function(e,t,s){!function(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}(e,s),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,s)}(r,n,a_)}vsmPass(e){const{shadow:t}=this,s=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,s),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,s),e.setRenderTarget(this.vsmShadowMapVertical),o_.material=this.vsmMaterialVertical,o_.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),o_.material=this.vsmMaterialHorizontal,o_.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,(e=>{const t=Kb.get(e);void 0!==t&&(t.dispose(),Kb.delete(e))})(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let s=t.needsUpdate||t.autoUpdate;s&&(this._cameraFrameId[e.camera]===e.frameId&&(s=!1),this._cameraFrameId[e.camera]=e.frameId),s&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const u_=new Us,l_=new is,c_=new It,d_=new It,p_=[new It(1,0,0),new It(-1,0,0),new It(0,-1,0),new It(0,1,0),new It(0,0,1),new It(0,0,-1)],m_=[new It(0,-1,0),new It(0,-1,0),new It(0,0,-1),new It(0,0,1),new It(0,-1,0),new It(0,-1,0)],g_=[new It(1,0,0),new It(-1,0,0),new It(0,1,0),new It(0,-1,0),new It(0,0,1),new It(0,0,-1)],f_=[new It(0,-1,0),new It(0,-1,0),new It(0,0,1),new It(0,0,-1),new It(0,-1,0),new It(0,-1,0)],y_=Ka(({depthTexture:e,bd3D:t,dp:s})=>od(e,t).compare(s)),b_=Ka(({depthTexture:e,bd3D:t,dp:s,shadow:i})=>{const r=ld("radius","float",i).setGroup(rh),n=ld("mapSize","vec2",i).setGroup(rh),a=r.div(n.x),o=ou(t),h=Jh(Au(t,o.x.greaterThan(o.z).select(lo(0,1,0),lo(1,0,0)))),u=Au(t,h),l=rb(tc.xy).mul(6.28318530718),c=nb(0,5,l),d=nb(1,5,l),p=nb(2,5,l),m=nb(3,5,l),g=nb(4,5,l);return od(e,t.add(h.mul(c.x).add(u.mul(c.y)).mul(a))).compare(s).add(od(e,t.add(h.mul(d.x).add(u.mul(d.y)).mul(a))).compare(s)).add(od(e,t.add(h.mul(p.x).add(u.mul(p.y)).mul(a))).compare(s)).add(od(e,t.add(h.mul(m.x).add(u.mul(m.y)).mul(a))).compare(s)).add(od(e,t.add(h.mul(g.x).add(u.mul(g.y)).mul(a))).compare(s)).mul(.2)}),__=Ka(({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i},r)=>{const n=s.xyz.toConst(),a=n.abs().toConst(),o=a.x.max(a.y).max(a.z),h=oh("float").setGroup(rh).onRenderUpdate(()=>i.camera.near),u=oh("float").setGroup(rh).onRenderUpdate(()=>i.camera.far),l=ld("bias","float",i).setGroup(rh),c=so(1).toVar();return Ja(o.sub(u).lessThanEqual(0).and(o.sub(h).greaterThanEqual(0)),()=>{let s;r.renderer.reversedDepthBuffer?(s=((e,t,s)=>t.mul(e.add(s)).div(e.mul(t.sub(s))))(o.negate(),h,u),s.subAssign(l)):(s=lm(o.negate(),h,u),s.addAssign(l));const a=n.normalize();c.assign(e({depthTexture:t,bd3D:a,dp:s,shadow:i}))}),c});class x_ extends h_{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?y_:b_}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r}){return __({filterFn:t,depthTexture:s,shadowCoord:i,shadow:r})}setupRenderTarget(e,t){const s=new Br(e.mapSize.width);s.name="PointShadowDepthTexture",s.compareFunction=t.renderer.reversedDepthBuffer?it:et;const i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=s,{shadowMap:i,depthTexture:s}}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:r,scene:n}=e,a=t.camera,o=t.matrix,h=r.coordinateSystem===ht,u=h?p_:g_,l=h?m_:f_;s.setSize(t.mapSize.width,t.mapSize.width);const c=r.autoClear,d=r.getClearColor(u_),p=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){r.setRenderTarget(s,e),r.clear();const h=i.distance||a.far;h!==a.far&&(a.far=h,a.updateProjectionMatrix()),c_.setFromMatrixPosition(i.matrixWorld),a.position.copy(c_),d_.copy(a.position),d_.add(u[e]),a.up.copy(l[e]),a.lookAt(d_),a.updateMatrixWorld(),o.makeTranslation(-c_.x,-c_.y,-c_.z),l_.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(l_,a.coordinateSystem,a.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${e+1}`,r.render(n,a),n.name=c}r.autoClear=c,r.setClearColor(d,p)}}class v_ extends Yp{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Us,this.colorNode=e&&e.colorNode||oh(this.color).setGroup(rh),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Vn,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,null!==this.baseColorNode&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return Vb(this.light).sub(e.context.positionView||Dc)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>new h_(e,t))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let s=this.shadowColorNode;if(null===s){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?Va(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=s=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(s=e.context.getShadow(this,e)),this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),s=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),s&&e.lightsNode.setupDirectRectAreaLight(e,this,s)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const T_=Ka(({lightDistance:e,cutoffDistance:t,decayExponent:s})=>{const i=e.pow(s).max(.01).reciprocal();return t.greaterThan(0).select(i.mul(e.div(t).pow4().oneMinus().clamp().pow2()),i)});class S_ extends v_{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=oh(0).setGroup(rh),this.decayExponentNode=oh(2).setGroup(rh)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>new x_(e,t))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:s,decayExponent:i})=>{const r=t.normalize(),n=t.length(),a=T_({lightDistance:n,cutoffDistance:s,decayExponent:i});return{lightDirection:r,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}Ka(([e=Bl()],{renderer:t,material:s})=>{const i=Fu(e.mul(2).sub(1));let r;if(s.alphaToCoverage&&t.currentSamples>0){const e=so(i.fwidth()).toVar();r=Uu(e.oneMinus(),e.add(1),i).oneMinus()}else r=Gu(i.greaterThan(1),0,1);return r});const w_=Ka(([e,t])=>{const s=e.x,i=e.y,r=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(i)),n=n.add(t.element(2).mul(1.023328).mul(r)),n=n.add(t.element(3).mul(1.023328).mul(s)),n=n.add(t.element(4).mul(.858086).mul(s).mul(i)),n=n.add(t.element(5).mul(.858086).mul(i).mul(r)),n=n.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(s).mul(r)),n=n.add(t.element(8).mul(.429043).mul(gh(s,s).sub(gh(i,i)))),n}),M_=new Wy;class N_ extends my{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===r)i._clearColor.getRGB(M_),M_.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(M_),M_.a=1,n=!0;else if(!0===r.isNode){const o=this.get(e),h=r;M_.copy(i._clearColor);let u=o.backgroundMesh;if(void 0===u){const c=go(h).mul(lb).context({getUV:()=>cb.mul(jc),getTextureLevel:()=>ub}),d=gc.element(3).element(3).equal(1),p=fh(1,gc.element(1).element(1)).mul(3),m=d.select(Rc.mul(p),Rc),g=wc.mul(go(m,0));let f=gc.mul(go(g.xyz,1));f=f.setZ(f.w);const y=new vm;function b(){r.removeEventListener("dispose",b),u.material.dispose(),u.geometry.dispose()}y.name="Background.material",y.side=1,y.depthTest=!1,y.depthWrite=!1,y.allowOverride=!1,y.fog=!1,y.lights=!1,y.vertexNode=f,y.colorNode=c,o.backgroundMeshNode=c,o.backgroundMesh=u=new dr(new Lr(1,32,32),y),u.frustumCulled=!1,u.name="Background.mesh",r.addEventListener("dispose",b)}const l=h.getCacheKey();o.backgroundCacheKey!==l&&(o.backgroundMeshNode.node=go(h).mul(lb),o.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,o.backgroundCacheKey=l),t.unshift(u,u.geometry,u.material,0,0,null,null)}else bt("Renderer: Unsupported background configuration.",r);const a=i.xr.getEnvironmentBlendMode();if("additive"===a?M_.set(0,0,0,1):"alpha-blend"===a&&M_.set(0,0,0,0),!0===i.autoClear||!0===n){const _=s.clearColorValue;_.r=M_.r,_.g=M_.g,_.b=M_.b,_.a=M_.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(_.r*=_.a,_.g*=_.a,_.b*=_.a),s.depthClearValue=i.getClearDepth(),s.stencilClearValue=i.getClearStencil(),s.clearColor=!0===i.autoClearColor,s.clearDepth=!0===i.autoClearDepth,s.clearStencil=!0===i.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}let E_=0;class A_{constructor(e="",t=[],s=0){this.name=e,this.bindings=t,this.index=s,this.id=E_++}}class C_{constructor(e,t,s,i,r,n,a,o,h,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=u,this.nodeAttributes=i,this.bindings=r,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=h,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new A_(t.name,[],t.index);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}class R_{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class P_{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class B_{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class F_ extends B_{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class D_{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let I_=0;class L_{constructor(e=null){this.id=I_++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class O_{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class U_{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class k_ extends U_{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class z_ extends U_{constructor(e,t=new Ft){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class V_ extends U_{constructor(e,t=new It){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class G_ extends U_{constructor(e,t=new es){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class j_ extends U_{constructor(e,t=new Us){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class $_ extends U_{constructor(e,t=new Tn){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class W_ extends U_{constructor(e,t=new Ut){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class H_ extends U_{constructor(e,t=new is){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class q_ extends k_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class X_ extends z_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Y_ extends V_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class K_ extends G_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Q_ extends j_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Z_ extends $_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class J_ extends W_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ex extends H_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let tx=0;const sx=new WeakMap,ix=new WeakMap,rx=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),nx=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class ax{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=Xy(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new L_,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:tx++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}createRenderTarget(e,t,s){return new ts(e,t,s)}createCubeRenderTarget(e,t){return new Cm(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=t[0].groupNode;let i,r=s.shared;if(r)for(let e=1;e<t.length;e++)s!==t[e].groupNode&&(r=!1);if(r){let s="";for(const e of t)if(e.isNodeUniformsGroup){e.uniforms.sort((e,t)=>e.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)s+=t.nodeUniform.node.id}else s+=e.nodeUniform.id;const r=this.renderer._currentRenderContext||this.renderer;let n=sx.get(r);void 0===n&&(n=new Map,sx.set(r,n));const a=Rn(s);i=n.get(a),void 0===i&&(i=new A_(e,t,this.bindingsIndexes[e].group),n.set(a,i))}else i=new A_(e,t,this.bindingsIndexes[e].group);return i}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},s=this.bindings;for(const e of Xn)for(const i in s[e]){const r=s[e][i],n=t[i]||(t[i]=[]);for(const e of r)!1===n.includes(e)&&n.push(e)}e=[];for(const s in t){const i=t[s],r=this._getBindGroup(s,i);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const s=e[t];this.bindingsIndexes[s.name].group=t,s.index=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t===zn&&s===zn||!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==zn&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==zn&&this.updateBeforeNodes.push(e),s!==zn&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===z||e.magFilter===V||e.magFilter===k||e.magFilter===G||e.minFilter===z||e.minFilter===V||e.minFilter===k||e.minFilter===G}getUniformBufferLimit(){return 16384}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const s=this.getDataFromNode(e);return void 0===s.cache&&(s.cache=new L_(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){yt("Abstract function.")}getInstanceIndex(){yt("Abstract function.")}getDrawIndex(){yt("Abstract function.")}getFrontFacing(){yt("Abstract function.")}getFragCoord(){yt("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,t.usageCount}generateTexture(){yt("Abstract function.")}generateTextureLod(){yt("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,s=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let r=0;r<t;r++){const n=s?s[r]:null;i+=null!==n?n.build(this,e):this.generateConst(e),r<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,s=null){const i=[];for(const e of t){const{name:t,type:r}=e;s&&s[t]&&s[t].isNode?i.push(s[t].build(this,r)):i.push(this.generateConst(r))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new Us:"vec2"===e||"uvec2"===e||"ivec2"===e?t=new Ft:"vec3"===e||"uvec3"===e||"ivec3"===e?t=new It:"vec4"!==e&&"uvec4"!==e&&"ivec4"!==e||(t=new es)),"float"===e)return nx(t);if("int"===e)return`${Math.round(t)}`;if("uint"===e)return t>=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${nx(t.r)}, ${nx(t.g)}, ${nx(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===s&&"mat2"!==e)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(s>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const s=this.attributes;for(const t of s)if(t.name===e)return t;const i=new R_(e,t);return this.registerDeclaration(i),s.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===q)return"int";if(t===X)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let s=In(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return rx.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,r=e.normalized;let n;return e instanceof Ni||!0===r||(n=this.getTypeFromArray(s)),this.getTypeFromLength(i,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=Xy(this.stack);const e=Za();return this.stacks.push(e),Qa(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){this.getDataFromNode(t).stack=e}return this.stack=e.parent,Qa(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){let i=(s=null===s?e.isGlobal(this)?this.globalCache:this.cache:s).getData(e);void 0===i&&(i={},s.setData(e,i)),void 0===i[t]&&(i[t]={});let r=i[t];const n=i.any?i.any.subBuilds:null,a=this.getClosestSubBuild(n);return a&&(void 0===r.subBuildsCache&&(r.subBuildsCache={}),r=r.subBuildsCache[a]||(r.subBuildsCache[a]={}),r.subBuilds=n),r}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e,"vertex");let i=s.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new R_("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,s=null,i=this.shaderStage){const r=this.getDataFromNode(e,i,this.globalCache);let n=r.structType;if(void 0===n){const a=this.structs.index++;null===s&&(s="StructType"+a),n=new O_(s,t),this.structs[i].push(n),this.types[i][s]=e,r.structType=n}return n}getOutputStructTypeFromNode(e,t){const s=this.getStructTypeFromNode(e,t,"OutputType","fragment");return s.output=!0,s}getUniformFromNode(e,t,s=this.shaderStage,i=null){const r=this.getDataFromNode(e,s,this.globalCache);let n=r.uniform;if(void 0===n){const a=this.uniforms.index++;n=new P_(i||"nodeUniform"+a,t,e),this.uniforms[s].push(n),this.registerDeclaration(n),r.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage,r=!1){const n=this.getDataFromNode(e,i),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){const h=r?"_const":"_var",u=this.vars[i]||(this.vars[i]=[]),l=this.vars[h]||(this.vars[h]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+l,this.vars[h]++),"variable"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new B_(t,s,r,c),r||u.push(o),this.registerDeclaration(o),n[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,s=e.getNodeType(this),i=null,r=null){const n=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,h=e.length;null===t&&(t="nodeVarying"+h),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new F_(t,s,i,r),e.push(o),this.registerDeclaration(o),n[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,s=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let r=1,n=i;for(;void 0!==s[n];)n=i+"_"+r++;r>1&&(e.name=n,yt(`TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${n}'.`)),s[n]=e}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[s]||(this.codes[s]=[]),n=e.length;r=new D_("nodeCode"+n,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,n=t;for(;n;){if(!0===i.get(n)){r=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(r)for(const e of s)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),n=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),n.set(s,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new Rb,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout,s={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)s[e.name]=new Hy(e.type,e.name);e.layout=null;const i=e.call(s),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowBuildStage(e,t,s=null){const i=this.getBuildStage();this.setBuildStage(t);const r=e.build(this,s);return this.setBuildStage(i),r}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,r=this.declarations,n=this.cache,a=this.buildStage,o=this.stack,h={code:""};this.flow=h,this.vars={},this.declarations={},this.cache=new L_,this.stack=Xy();for(const s of qn)this.setBuildStage(s),h.result=e.build(this,t);return h.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.declarations=r,this.cache=n,this.stack=o,this.setBuildStage(a),h}getFunctionOperator(){return null}buildFunctionCode(){yt("Abstract function.")}flowChildNode(e,t=null){const s=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=s,i}flowNodeFromShaderStage(e,t,s=null,i=null){const r=this.tab,n=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const h={...this.context};delete h.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=h;let u=null;if("generate"===this.buildStage){const r=this.flowChildNode(t,s);null!==i&&(r.code+=`${this.tab+i} = ${r.result};\n`),this.flowCode[e]=this.flowCode[e]+r.code,u=r}else u=t.build(this);return this.setShaderStage(a),this.cache=n,this.tab=r,this.context=o,u}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){yt("Abstract function.")}getVaryings(){yt("Abstract function.")}getVar(e,t,s=null){return`${null!==s?this.generateArrayDeclaration(e,s):this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(void 0!==s)for(const e of s)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){yt("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(void 0!==t)for(const e of t)s+=e.code+"\n";return s}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){yt("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,"any").subBuilds:e instanceof Set?[...e]:e,!t)return null;const s=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const i=t[e];if(s.includes(i))return i}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let s,i;return s=null!==t?this.getClosestSubBuild(t):this.subBuildFn,i=s?e?s+"_"+e:s:e,i}build(){const{object:e,material:t,renderer:s}=this;if(null!==t){let e=s.library.fromMaterial(t);null===e&&(bt(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new vm),e.build(this)}else this.addFlow("compute",e);for(const e of qn){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Xn){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=ix.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const s=this.getSharedDataFromNode(e);let i=s.cache;if(void 0===i){if("float"===t||"int"===t||"uint"===t)i=new q_(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)i=new X_(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)i=new Y_(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)i=new K_(e);else if("color"===t)i=new Q_(e);else if("mat2"===t)i=new Z_(e);else if("mat3"===t)i=new J_(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);i=new ex(e)}s.cache=i}return i}format(e,t,s){if((t=this.getVectorType(t))===(s=this.getVectorType(s))||null===s||this.isReference(s))return e;const i=this.getTypeLength(t),r=this.getTypeLength(s);return 16===i&&9===r?`${this.getType(s)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===i&&4===r?`${this.getType(s)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||r>4||0===r?e:i===r?`${this.getType(s)}( ${e} )`:i>r?(e="bool"===s?`all( ${e} )`:`${e}.${"xyz".slice(0,r)}`,this.format(e,this.getTypeFromLength(r,this.getComponentType(t)),s)):4===r&&i>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(s)&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${a} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||!0===Un(this.object).useVelocity}}class ox{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let s=e.get(t);return void 0===s&&(s={renderId:0,frameId:0},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===Vn){const t=this._getMaps(this.updateBeforeMap,s);if(t.frameId!==this.frameId){const s=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=s)}}else if(t===Gn){const t=this._getMaps(this.updateBeforeMap,s);if(t.renderId!==this.renderId){const s=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=s)}}else t===jn&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===Vn){const t=this._getMaps(this.updateAfterMap,s);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===Gn){const t=this._getMaps(this.updateAfterMap,s);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===jn&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===Vn){const t=this._getMaps(this.updateMap,s);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===Gn){const t=this._getMaps(this.updateMap,s);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===jn&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class hx{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}hx.isNodeFunctionInput=!0;class ux extends v_{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class lx extends v_{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:Gb(this.light),lightColor:e}}}class cx extends v_{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=zb(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=oh(new Us).setGroup(rh)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:s,lightDirectionNode:i}=this,r=Wc.dot(i).mul(.5).add(.5),n=Du(s,t,r);e.context.irradiance.addAssign(n)}}class dx extends v_{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=oh(0).setGroup(rh),this.penumbraCosNode=oh(0).setGroup(rh),this.cutoffDistanceNode=oh(0).setGroup(rh),this.decayExponentNode=oh(0).setGroup(rh),this.colorNode=oh(this.color).setGroup(rh)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:s,penumbraCosNode:i}=this;return Uu(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return void 0===s&&(s=function(e,t=Bc){const s=kb(e).mul(t);return s.xyz.div(s.w)}(this.light,e.context.positionWorld),t.projectionUV=s),s}setupDirect(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:r}=this,n=this.getLightVector(e),a=n.normalize(),o=a.dot(Gb(r)),h=this.getSpotAttenuation(e,o),u=n.length(),l=T_({lightDistance:u,cutoffDistance:s,decayExponent:i});let c,d,p=t.mul(h).mul(l);if(r.colorNode?(d=this.getLightCoord(e),c=r.colorNode(d)):r.map&&(d=this.getLightCoord(e),c=Vl(r.map,d.xy).onRenderUpdate(()=>r.map)),c){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:a}}}class px extends dx{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const s=this.light.iesMap;let i=null;if(s&&!0===s.isTexture){const e=t.acos().mul(1/Math.PI);i=Vl(s,ao(e,0),0).r}else i=super.getSpotAttenuation(t);return i}}class mx extends v_{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new It);this.lightProbe=ql(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=w_(Wc,this.lightProbe);e.context.irradiance.addAssign(t)}}const gx=Ka(([e,t])=>{const s=e.abs().sub(t);return uu(Tu(s,0)).add(vu(Tu(s.x,s.y),0))});class fx extends dx{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),null===t.aspect){let e=1;null!==t.map&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=so(0),s=this.penumbraCosNode,i=kb(this.light).mul(e.context.positionWorld||Bc);return Ja(i.w.greaterThan(0),()=>{const e=i.xyz.div(i.w),r=gx(e.xy.sub(ao(.5)),ao(.5)),n=fh(-1,mh(1,nu(s)).sub(1));t.assign(Lu(r.mul(-2).mul(n)))}),t}}const yx=new is,bx=new is;let _x=null;class xx extends v_{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=oh(new It).setGroup(rh),this.halfWidth=oh(new It).setGroup(rh),this.updateType=Gn}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;bx.identity(),yx.copy(t.matrixWorld),yx.premultiply(s),bx.extractRotation(yx),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(bx),this.halfHeight.value.applyMatrix4(bx)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=Vl(_x.LTC_FLOAT_1),s=Vl(_x.LTC_FLOAT_2)):(t=Vl(_x.LTC_HALF_1),s=Vl(_x.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:Vb(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){_x=e}}class vx{parseFunction(){yt("Abstract function.")}}class Tx{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){yt("Abstract function.")}}Tx.isNodeFunction=!0;const Sx=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,wx=/[a-z_0-9]+/gi,Mx="#pragma main";class Nx extends Tx{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(Mx),s=-1!==t?e.slice(t+12):e,i=s.match(Sx);if(null!==i&&5===i.length){const r=i[4],n=[];let a=null;for(;null!==(a=wx.exec(r));)n.push(a);const o=[];let h=0;for(;h<n.length;){const e="const"===n[h][0];!0===e&&h++;let t=n[h][0];"in"===t||"out"===t||"inout"===t?h++:t="";const s=n[h++][0];let i=Number.parseInt(n[h][0]);!1===Number.isNaN(i)?h++:i=null;const r=n[h++][0];o.push(new hx(s,r,i,t,e))}const u=s.substring(i[0].length),l=void 0!==i[3]?i[3]:"";return{type:i[2],inputs:o,name:l,precision:void 0!==i[1]?i[1]:"",inputsCode:r,blockCode:u,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("FunctionNode: Function is not a GLSL code.")})(e);super(t,s,i,r),this.inputsCode=n,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const s=this.blockCode;if(""!==s){const{type:i,inputsCode:r,headerCode:n,precision:a}=this;let o=`${i} ${e} ( ${r.trim()} )`;""!==a&&(o=`${a} ${o}`),t=n+o+s}else t="";return t}}class Ex extends vx{parseFunction(e){return new Nx(e)}}const Ax=new WeakMap,Cx=[],Rx=[];class Px extends my{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new ox,this.nodeBuilderCache=new Map,this.callHashCache=new uy,this.groupsData=new uy,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===nh.name)return!0;if(s===rh.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===ih.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}Cx[0]=t,Cx[1]=e;let i=this.groupsData.get(Cx);return void 0===i&&this.groupsData.set(Cx,i={}),Cx[0]=null,Cx[1]=null,i.version!==t.version&&(i.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const{nodeBuilderCache:i}=this,r=this.getForRenderCacheKey(e);if(s=i.get(r),void 0===s){const t=t=>{const s=this.backend.createNodeBuilder(e.object,this.renderer);return s.scene=e.scene,s.material=t,s.camera=e.camera,s.context.material=t,s.lightsNode=e.lightsNode,s.environmentNode=this.getEnvironmentNode(e.scene),s.fogNode=this.getFogNode(e.scene),s.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&s.enableMultiview(),s};let n=t(e.material);try{n.build()}catch(e){n=t(new vm),n.build();let s=e.stackTrace;!s&&e.stack&&(s=new An(e.stack)),bt("TSL: "+e,s)}s=this._createNodeBuilderState(n),i.set(r,s)}s.usedTimes++,t.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),s=this._createNodeBuilderState(i),t.nodeBuilderState=s}return s}_createNodeBuilderState(e){return new C_(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const s=this.get(e);s.environmentNode&&(t=s.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const s=this.get(e);s.backgroundNode&&(t=s.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){Cx[0]=e,Cx[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(Cx)||{};if(i.callId!==s){const r=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&Rx.push(t.getCacheKey(!0)),r&&Rx.push(r.getCacheKey()),n&&Rx.push(n.getCacheKey()),Rx.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),Rx.push(this.renderer.shadowMap.enabled?1:0),Rx.push(this.renderer.shadowMap.type),i.callId=s,i.cacheKey=Pn(Rx),this.callHashCache.set(Cx,i),Rx.length=0}return Cx[0]=null,Cx[1]=null,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),s=e.background;if(s){const i=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==s||i){const r=this.getCacheNode("background",s,()=>{if(!0===s.isCubeTexture||303===s.mapping||304===s.mapping||306===s.mapping){if(e.backgroundBlurriness>0||306===s.mapping)return If(s);{let e;return e=!0===s.isCubeTexture?od(s):Vl(s),Dm(e)}}if(!0===s.isTexture)return Vl(s,Jl.flipY()).setUpdateMatrix(!0);!0!==s.isColor&&bt("WebGPUNodes: Unsupported background configuration.",s)},i);t.backgroundNode=r,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,s,i=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=r.get(t);return(void 0===n||i)&&(n=s(),r.set(t,n)),n}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){const e=this.getCacheNode("fog",s,()=>{if(s.isFogExp2){const e=ld("color","color",s).setGroup(rh),t=ld("density","float",s).setGroup(rh);return Db(e,Fb(t))}if(s.isFog){const e=ld("color","color",s).setGroup(rh),t=ld("near","float",s).setGroup(rh),i=ld("far","float",s).setGroup(rh);return Db(e,Bb(t,i))}bt("Renderer: Unsupported fog configuration.",s)});t.fogNode=e,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){const e=this.getCacheNode("environment",s,()=>!0===s.isCubeTexture?od(s):!0===s.isTexture?Vl(s):void bt("Nodes: Unsupported environment configuration.",s));t.environmentNode=e,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,r=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=s,n.camera=i,n.material=r,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return Ax.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=e.isArrayTexture?mb(e,lo(Jl,Xl("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):Vl(e,Jl).renderOutput(t.toneMapping,t.currentColorSpace);return Ax.set(e,s),i}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const e of s.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new ox,this.nodeBuilderCache=new Map,this.cacheLib={}}}const Bx=new _r;class Fx{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Ut,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,s){const i=e.length;for(let r=0;r<i;r++){Bx.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=Bx.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=Bx.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let s=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,r=i.length;let n,a;if(this.clipIntersection?(n=this.intersectionPlanes,a=e.intersectionPlanes.length):(n=this.unionPlanes,a=e.unionPlanes.length),n.length!==a+r){n.length=a+r;for(let e=0;e<r;e++)n[a+e]=new es;s=!0}this.projectPlanes(i,n,a),s&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return void 0===t&&(t=new Fx(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class Dx{constructor(e,t){this.bundleGroup=e,this.camera=t}}const Ix=[];class Lx{constructor(){this.bundles=new uy}get(e,t){const s=this.bundles;Ix[0]=e,Ix[1]=t;let i=s.get(Ix);return void 0===i&&(i=new Dx(e,t),s.set(Ix,i)),Ix[0]=null,Ix[1]=null,i}dispose(){this.bundles=new uy}}class Ox{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(null!==s){t=new s;for(const s in e)t[s]=e[s]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t))yt(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}}addClass(e,t,s){if(s.has(t))yt(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}}const Ux=new Hb,kx=new WeakMap;class zx{createNode(e=[]){return(new Hb).setLights(e)}getNode(e){if(e.isQuadMesh)return Ux;let t=kx.get(e);return void 0===t&&(t=this.createNode(),kx.set(e,t)),t}}class Vx extends ts{constructor(e=1,t=1,s={}){super(e,t,s),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const Gx=new It,jx=new It;class $x extends vt{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new an,this._cameraL.viewport=new es,this._cameraR=new an,this._cameraR.viewport=new es,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new xn,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._frameBufferTargets=null,this._createXRLayer=Yx.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new Ft,this._onSessionEvent=Hx.bind(this),this._onSessionEnd=qx.bind(this),this._onInputSourcesChange=Xx.bind(this),this._onAnimationFrame=Kx.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(null!==this._glProjLayer||null!==this._glBaseLayer)return this._foveation}setFoveation(e){this._foveation=e,null!==this._glProjLayer&&(this._glProjLayer.fixedFoveation=e),null!==this._glBaseLayer&&void 0!==this._glBaseLayer.fixedFoveation&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,!0===this.isPresenting&&yt("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&yt("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(null!==this._session)return this._session.environmentBlendMode}getBinding(){return null===this._glBinding&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,s,i,r,n,a,o={}){const h=new Ir(e,t),u=new Vx(r,n,{format:ie,type:j,depthTexture:new Pr(r,n,o.stencil?J:X,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?ne:re),stencilBuffer:o.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u._autoAllocateDepthBuffer=!0;const c=new er({color:16777215,side:0});c.map=u.texture,c.map.offset.y=1,c.map.repeat.y=-1;const d=new dr(h,c);d.position.copy(s),d.quaternion.copy(i);const m={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:r,pixelheight:n,plane:d,material:c,rendercall:a,renderTarget:u};if(this._layers.push(m),null!==this._session){m.plane.material=new er({color:16777215,side:0}),m.plane.material.blending=5,m.plane.material.blendEquation=l,m.plane.material.blendSrc=p,m.plane.material.blendDst=p,m.xrlayer=this._createXRLayer(m);const e=this._session.renderState.layers;e.unshift(m.xrlayer),this._session.updateRenderState({layers:e})}else u.isXRRenderTarget=!1;return d}createCylinderLayer(e,t,s,i,r,n,a,o,h={}){const u=new Dr(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),c=new Vx(n,a,{format:ie,type:j,depthTexture:new Pr(n,a,h.stencil?J:X,void 0,void 0,void 0,void 0,void 0,void 0,h.stencil?ne:re),stencilBuffer:h.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});c._autoAllocateDepthBuffer=!0;const d=new er({color:16777215,side:1});d.map=c.texture,d.map.offset.y=1,d.map.repeat.y=-1;const m=new dr(u,d);m.position.copy(i),m.quaternion.copy(r);const g={type:"cylinder",radius:e,centralAngle:t,aspectratio:s,translation:i,quaternion:r,pixelwidth:n,pixelheight:a,plane:m,material:d,rendercall:o,renderTarget:c};if(this._layers.push(g),null!==this._session){g.plane.material=new er({color:16777215,side:1}),g.plane.material.blending=5,g.plane.material.blendEquation=l,g.plane.material.blendSrc=p,g.plane.material.blendDst=p,g.xrlayer=this._createXRLayer(g);const e=this._session.renderState.layers;e.unshift(g.xrlayer),this._session.updateRenderState({layers:e})}else c.isXRRenderTarget=!1;return m}renderLayers(){const e=new It,t=new Dt,s=this._renderer,i=this.isPresenting,r=s.getOutputRenderTarget(),n=s._frameBufferTarget;this.isPresenting=!1;const a=new Ft;s.getSize(a);const o=s._quad;for(const i of this._layers)if(i.renderTarget.isXRRenderTarget=null!==this._session,i.renderTarget._hasExternalTextures=i.renderTarget.isXRRenderTarget,i.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){i.xrlayer.transform=new XRRigidTransform(i.plane.getWorldPosition(e),i.plane.getWorldQuaternion(t));const r=this._glBinding.getSubImage(i.xrlayer,this._xrFrame);s.backend.setXRRenderTargetTextures(i.renderTarget,r.colorTexture,void 0),s._setXRLayerSize(i.renderTarget.width,i.renderTarget.height),s.setOutputRenderTarget(i.renderTarget),s.setRenderTarget(null),s._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:n,quad:a}=this._frameBufferTargets.get(i.renderTarget)||{frameBufferTarget:null,quad:null};n?(s._frameBufferTarget=n,s._quad=a):(s._quad=new ib(new vm),this._frameBufferTargets.set(i.renderTarget,{frameBufferTarget:s._getFrameBufferTarget(),quad:s._quad})),i.rendercall(),s._frameBufferTarget=null}else s.setRenderTarget(i.renderTarget),i.rendercall();s.setRenderTarget(null),s.setOutputRenderTarget(r),s._frameBufferTarget=n,s._setXRLayerSize(a.x,a.y),s._quad=o,this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer,s=t.backend;this._gl=t.getContext();const i=this._gl,r=i.getContextAttributes();if(this._session=e,null!==e){if(!0===s.isWebGPUBackend)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await s.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._supportsLayers){let s=null,n=null,a=null;t.depth&&(a=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,s=t.stencil?ne:re,n=t.stencil?J:X);const o={colorFormat:i.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const h=this._glBinding.createProjectionLayer(o),u=[h];this._glProjLayer=h,t.setPixelRatio(1),t._setXRLayerSize(h.textureWidth,h.textureHeight);const c=this._useMultiview?2:1,d=new Pr(h.textureWidth,h.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,s,c);if(this._xrRenderTarget=new Vx(h.textureWidth,h.textureHeight,{format:ie,type:j,colorSpace:t.outputColorSpace,depthTexture:d,stencilBuffer:t.stencil,samples:r.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const e of this._layers)e.plane.material=new er({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=l,e.plane.material.blendSrc=p,e.plane.material.blendDst=p,e.xrlayer=this._createXRLayer(e),u.unshift(e.xrlayer);e.updateRenderState({layers:u})}else{const s={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,i,s);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t._setXRLayerSize(r.framebufferWidth,r.framebufferHeight),this._xrRenderTarget=new Vx(r.framebufferWidth,r.framebufferHeight,{format:ie,type:j,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===r.ignoreDepthValues,resolveStencilBuffer:!1===r.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const s=e.near,i=e.far,r=this._cameraXR,n=this._cameraL,a=this._cameraR;r.near=a.near=n.near=s,r.far=a.far=n.far=i,r.isMultiViewCamera=this._useMultiview,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),r.layers.mask=6|e.layers.mask,n.layers.mask=-5&r.layers.mask,a.layers.mask=-3&r.layers.mask;const o=e.parent,h=r.cameras;Wx(r,o);for(let e=0;e<h.length;e++)Wx(h[e],o);2===h.length?function(e,t,s){Gx.setFromMatrixPosition(t.matrixWorld),jx.setFromMatrixPosition(s.matrixWorld);const i=Gx.distanceTo(jx),r=t.projectionMatrix.elements,n=s.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),h=(r[9]+1)/r[5],u=(r[9]-1)/r[5],l=(r[8]-1)/r[0],c=(n[8]+1)/n[0],d=a*l,p=a*c,m=i/(-l+c),g=m*-l;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(g),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===r[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+m,s=o+m,r=d-g,n=p+(i-g),l=h*o/s*t,c=u*o/s*t;e.projectionMatrix.makePerspective(r,n,l,c,t,s),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(r,n,a):r.projectionMatrix.copy(n.projectionMatrix),function(e,t,s){null===s?e.matrix.copy(t.matrixWorld):(e.matrix.copy(s.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*Mt*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,r,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new Fs,this._controllers[e]=t),t}}function Wx(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function Hx(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const s=this._controllers[t];if(void 0!==s){const t=this.getReferenceSpace();s.update(e.inputSource,e.frame,t),s.dispatchEvent({type:e.type,data:e.inputSource})}}function qx(){const e=this._session,t=this._renderer;e.removeEventListener("select",this._onSessionEvent),e.removeEventListener("selectstart",this._onSessionEvent),e.removeEventListener("selectend",this._onSessionEvent),e.removeEventListener("squeeze",this._onSessionEvent),e.removeEventListener("squeezestart",this._onSessionEvent),e.removeEventListener("squeezeend",this._onSessionEvent),e.removeEventListener("end",this._onSessionEnd),e.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let e=0;e<this._controllers.length;e++){const t=this._controllerInputSources[e];null!==t&&(this._controllerInputSources[e]=null,this._controllers[e].disconnect(t))}if(this._currentDepthNear=null,this._currentDepthFar=null,t._resetXRState(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._glBaseLayer=null,this._glProjLayer=null,!0===this._sessionUsesLayers)for(const e of this._layers)e.renderTarget=new Vx(e.pixelwidth,e.pixelheight,{format:ie,type:j,depthTexture:new Pr(e.pixelwidth,e.pixelheight,e.stencilBuffer?J:X,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?ne:re),stencilBuffer:e.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,e.material.map.offset.y=1,e.material.map.repeat.y=-1,delete e.xrlayer;this.isPresenting=!1,this._useMultiview=!1,t._animation.stop(),t._animation.setAnimationLoop(this._currentAnimationLoop),t._animation.setContext(this._currentAnimationContext),t._animation.start(),t.setPixelRatio(this._currentPixelRatio),t.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function Xx(e){const t=this._controllers,s=this._controllerInputSources;for(let i=0;i<e.removed.length;i++){const r=e.removed[i],n=s.indexOf(r);n>=0&&(s[n]=null,t[n].disconnect(r))}for(let i=0;i<e.added.length;i++){const r=e.added[i];let n=s.indexOf(r);if(-1===n){for(let e=0;e<t.length;e++){if(e>=s.length){s.push(r),n=e;break}if(null===s[e]){s[e]=r,n=e;break}}if(-1===n)break}const a=t[n];a&&a.connect(r)}}function Yx(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function Kx(e,t){if(void 0===t)return;const s=this._cameraXR,i=this._renderer,r=i.backend,n=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views;null!==this._glBaseLayer&&r.setXRTarget(n.framebuffer);let t=!1;e.length!==s.cameras.length&&(s.cameras.length=0,t=!0);for(let i=0;i<e.length;i++){const a=e[i];let o;if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,a);o=e.viewport,0===i&&r.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else o=n.getViewport(a);let h=this._cameras[i];void 0===h&&(h=new an,h.layers.enable(i),h.viewport=new es,this._cameras[i]=h),h.matrix.fromArray(a.transform.matrix),h.matrix.decompose(h.position,h.quaternion,h.scale),h.projectionMatrix.fromArray(a.projectionMatrix),h.projectionMatrixInverse.copy(h.projectionMatrix).invert(),h.viewport.set(o.x,o.y,o.width,o.height),0===i&&(s.matrix.copy(h.matrix),s.matrix.decompose(s.position,s.quaternion,s.scale)),!0===t&&s.cameras.push(h)}i.setOutputRenderTarget(this._xrRenderTarget)}for(let e=0;e<this._controllers.length;e++){const s=this._controllerInputSources[e],i=this._controllers[e];null!==s&&void 0!==i&&i.update(s,t,a)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class Qx extends vt{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new es(0,0,this._width,this._height),this._scissor=new es(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new Cr,this.depthTexture=new Pr}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===s&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,s,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,r=0,n=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,s,i),a.minDepth=r,a.maxDepth=n}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const Zx=new zs,Jx=new Ft,ev=new es,tv=new Sr,sv=new Nr,iv=new is,rv=new es,nv={[o]:1,[h]:0,[u]:2};class av{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,reversedDepthBuffer:i=!1,alpha:r=!0,depth:n=!0,stencil:a=!1,antialias:o=!1,samples:h=0,getFallback:u=null,outputBufferType:l=K,multiview:c=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=s,this.reversedDepthBuffer=i,this.outputColorSpace=He,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=n,this.stencil=a,this.info=new My,this.contextNode=$u(),this.library=new Ox,this.lighting=new zx,this._samples=h||!0===o?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new Qx(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new Al,this._inspector.setRenderer(this),this._getFallback=u,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new ib(new vm),this._quad.name="Output Color Transform",this._quad.material.name="outputColorTransform",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const d=!0===this.alpha?0:1;this._clearColor=new Wy(0,0,0,d),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._outputBufferType=l,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:1},this.xr=new $x(this,c),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,s)=>{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(this._renderTarget,this._mrt),n=e.overrideMaterial||s.material,a=this._objects.get(s,n,e,t,i.lightsNode,r,r.clippingContext),{fragmentShader:o,vertexShader:h}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:h}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let s=this.backend;try{await s.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=s=this._getFallback(e),await s.init(this)}catch(e){return void t(e)}}this._nodes=new Px(this,s),this._animation=new hy(this,this._nodes,this.info),this._attributes=new xy(s),this._background=new N_(this,this._nodes),this._geometries=new wy(this._attributes,this.info),this._textures=new $y(this,s,this.info),this._pipelines=new Py(s,this._nodes),this._bindings=new By(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new py(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Uy(this.lighting),this._bundles=new Lx,this._renderContexts=new Gy(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,n=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._handleObjectFunction,h=this._compilationPromises,u=!0===e.isScene?e:Zx;null===s&&(s=e);const l=this._renderTarget,c=this._renderContexts.get(l,this._mrt),d=this._activeMipmapLevel,p=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,i.renderId++,i.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new Fx),c.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,l);const m=this._renderLists.get(e,t);if(m.begin(),this._projectObject(e,t,0,m,c.clippingContext),s!==e&&s.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&m.pushLight(e)}),m.finish(),null!==l){this._textures.updateRenderTarget(l,d);const e=this._textures.get(l);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;s!==e?this._background.update(s,m,c):this._background.update(u,m,c);const g=m.opaque,f=m.transparent,y=m.transparentDoublePass,b=m.lightsNode;!0===this.opaque&&g.length>0&&this._renderObjects(g,t,u,b),!0===this.transparent&&f.length>0&&this._renderTransparents(f,y,t,u,b),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._handleObjectFunction=o,this._compilationPromises=h,await Promise.all(p)}async renderAsync(e,t){_t('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){bt("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=Nc,t.modelNormalViewMatrix=Ec):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Nc&&e.modelNormalViewMatrix===Ec}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return _t('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),bt(t),this._isDeviceLost=!0}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(i,r),h=this.backend.get(o);void 0===h.renderContexts&&(h.renderContexts=new Set);const u=i.version!==h.version,l=!1===h.renderContexts.has(a)||u;if(h.renderContexts.add(a),l){this.backend.beginBundle(a),(void 0===h.renderObjects||u)&&(h.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:l,opaque:c}=n;!0===this.opaque&&c.length>0&&this._renderObjects(c,r,t,s),!0===this.transparent&&l.length>0&&this._renderTransparents(l,e,r,t,s),this._currentRenderBundle=null,this.backend.finishBundle(a,o),h.version=i.version}else{const{renderObjects:e}=h;for(let t=0,s=e.length;t<s;t++){const s=e[t];this._nodes.needsRefresh(s)&&(this._nodes.updateBefore(s),this._nodes.updateForRender(s),this._bindings.updateForRender(s),this._nodes.updateAfter(s))}}this.backend.addBundle(a,o)}render(e,t){if(!1===this._initialized)throw new Error('Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this,s=0!==e,i=t!==jt.workingColorSpace;if(!1===s&&!1===i)return null;const{width:r,height:n}=this.getDrawingBufferSize(Jx),{depth:a,stencil:o}=this;let h=this._frameBufferTarget;null===h&&(h=new ts(r,n,{depthBuffer:a,stencilBuffer:o,type:this._outputBufferType,format:ie,colorSpace:jt.workingColorSpace,generateMipmaps:!1,minFilter:z,magFilter:z,samples:this.samples}),h.isPostProcessingRenderTarget=!0,this._frameBufferTarget=h);const u=this.getOutputRenderTarget();h.depthBuffer=a,h.stencilBuffer=o,null!==u?h.setSize(u.width,u.height,u.depth):h.setSize(r,n,1);const l=this._canvasTarget;return h.viewport.copy(l._viewport),h.scissor.copy(l._scissor),h.viewport.multiplyScalar(l._pixelRatio),h.scissor.multiplyScalar(l._pixelRatio),h.scissorTest=l._scissorTest,h.multiview=null!==u&&u.multiview,h.resolveDepthBuffer=null===u||u.resolveDepthBuffer,h._autoAllocateDepthBuffer=null!==u&&u._autoAllocateDepthBuffer,h}_renderScene(e,t,s=!0){if(!0===this._isDeviceLost)return;const i=s?this._getFrameBufferTarget():null,r=this._nodes.nodeFrame,n=r.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,h=this._handleObjectFunction;this._callDepth++;const u=!0===e.isScene?e:Zx,l=this._renderTarget||this._outputRenderTarget,c=this._activeCubeFace,d=this._activeMipmapLevel;let p;null!==i?(p=i,this.setRenderTarget(p)):p=l;const m=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=m,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(m),this.inspector.beginRender(this.backend.getTimestampUID(m),e,t,p);const g=this.xr;if(!1===g.isPresenting){let e=!1;if(!0===this.reversedDepthBuffer&&!0!==t.reversedDepth){if(t._reversedDepth=!0,t.isArrayCamera)for(const e of t.cameras)e._reversedDepth=!0;e=!0}const s=this.coordinateSystem;if(t.coordinateSystem!==s){if(t.coordinateSystem=s,t.isArrayCamera)for(const e of t.cameras)e.coordinateSystem=s;e=!0}if(!0===e&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.updateProjectionMatrix()}!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===g.enabled&&!0===g.isPresenting&&(!0===g.cameraAutoUpdate&&g.updateCamera(t),t=g.getCamera());const f=this._canvasTarget;let y=f._viewport,b=f._scissor,_=f._pixelRatio;null!==p&&(y=p.viewport,b=p.scissor,_=1),this.getDrawingBufferSize(Jx),ev.set(0,0,Jx.width,Jx.height);const x=void 0===y.minDepth?0:y.minDepth,v=void 0===y.maxDepth?1:y.maxDepth;m.viewportValue.copy(y).multiplyScalar(_).floor(),m.viewportValue.width>>=d,m.viewportValue.height>>=d,m.viewportValue.minDepth=x,m.viewportValue.maxDepth=v,m.viewport=!1===m.viewportValue.equals(ev),m.scissorValue.copy(b).multiplyScalar(_).floor(),m.scissor=f._scissorTest&&!1===m.scissorValue.equals(ev),m.scissorValue.width>>=d,m.scissorValue.height>>=d,m.clippingContext||(m.clippingContext=new Fx),m.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,p);const T=t.isArrayCamera?sv:tv;t.isArrayCamera||(iv.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),T.setFromProjectionMatrix(iv,t.coordinateSystem,t.reversedDepth));const S=this._renderLists.get(e,t);if(S.begin(),this._projectObject(e,t,0,S,m.clippingContext),S.finish(),!0===this.sortObjects&&S.sort(this._opaqueSort,this._transparentSort),null!==p){this._textures.updateRenderTarget(p,d);const e=this._textures.get(p);m.textures=e.textures,m.depthTexture=e.depthTexture,m.width=e.width,m.height=e.height,m.renderTarget=p,m.depth=p.depthBuffer,m.stencil=p.stencilBuffer}else m.textures=null,m.depthTexture=null,m.width=Jx.width,m.height=Jx.height,m.depth=this.depth,m.stencil=this.stencil;m.width>>=d,m.height>>=d,m.activeCubeFace=c,m.activeMipmapLevel=d,m.occlusionQueryCount=S.occlusionQueryCount,m.scissorValue.max(rv.set(0,0,0,0)),m.scissorValue.x+m.scissorValue.width>m.width&&(m.scissorValue.width=Math.max(m.width-m.scissorValue.x,0)),m.scissorValue.y+m.scissorValue.height>m.height&&(m.scissorValue.height=Math.max(m.height-m.scissorValue.y,0)),this._background.update(u,S,m),m.camera=t,this.backend.beginRender(m);const{bundles:w,lightsNode:M,transparentDoublePass:N,transparent:E,opaque:A}=S;return w.length>0&&this._renderBundles(w,u,M),!0===this.opaque&&A.length>0&&this._renderObjects(A,t,u,M),!0===this.transparent&&E.length>0&&this._renderTransparents(E,N,t,u,M),this.backend.finishRender(m),r.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=h,this._callDepth--,null!==i&&(this.setRenderTarget(l,c,d),this._renderOutput(p)),u.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(m)),m}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const s=this.autoClear,i=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=s,this.xr.enabled=i}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,s)}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,s)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,s,i){this._canvasTarget.setScissor(e,t,s,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,s,i,r=0,n=1){this._canvasTarget.setViewport(e,t,s,i,r,n)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,s=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i){this._textures.updateRenderTarget(i);const e=this._textures.get(i);r=this._renderContexts.get(i),r.textures=e.textures,r.depthTexture=e.depthTexture,r.width=e.width,r.height=e.height,r.renderTarget=i,r.depth=i.depthBuffer,r.stencil=i.stencilBuffer;const t=this.backend.getClearColor();r.clearColorValue.r=t.r,r.clearColorValue.g=t.g,r.clearColorValue.b=t.b,r.clearColorValue.a=t.a,r.clearDepthValue=this.getClearDepth(),r.clearStencilValue=this.getClearStencil(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){_t('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,s)}async clearColorAsync(){_t('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){_t('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){_t('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=0!==this.currentToneMapping,t=this.currentColorSpace!==jt.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:jt.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){!0===this._initialized&&(this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return yt("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const s=this._nodes.nodeFrame,i=s.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,s.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const r=this.backend,n=this._pipelines,a=this._bindings,o=this._nodes,h=Array.isArray(e)?e:[e];if(void 0===h[0]||!0!==h[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const s of h){if(!1===n.has(s)){const e=()=>{s.removeEventListener("dispose",e),n.delete(s),a.deleteForCompute(s),o.delete(s)};s.addEventListener("dispose",e);const t=s.onInitFunction;null!==t&&t.call(s,{renderer:this})}o.updateForCompute(s),a.updateForCompute(s);const i=a.getForCompute(s),h=n.getForCompute(s,i);r.compute(e,s,i,h,t)}r.finishCompute(e),s.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return _t('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){_t('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),s=this._renderContexts.get(e);s.textures=t.textures,s.depthTexture=t.depthTexture,s.width=t.width,s.height=t.height,s.renderTarget=e,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,this.backend.initRenderTarget(s)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=rv.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void bt("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=rv.copy(t).floor()}else t=rv.set(0,0,e.image.width,e.image.height);let s,i=this._currentRenderContext;null!==i?s=i.renderTarget:(s=this._renderTarget||this._getFrameBufferTarget(),null!==s&&(this._textures.updateRenderTarget(s),i=this._textures.get(s))),this._textures.updateTexture(e,{renderTarget:s}),this.backend.copyFramebufferToTexture(e,i,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,r,n),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,s,i,r,n=0,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,a)}_projectObject(e,t,s,i,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)s=e.renderOrder,e.isClippingGroup&&e.enabled&&(r=r.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const n=t.isArrayCamera?sv:tv;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&rv.setFromMatrixPosition(e.matrixWorld).applyMatrix4(iv);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,rv.z,null,r)}}else if(e.isLineLoop)bt("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?sv:tv;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),rv.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(iv)),Array.isArray(n)){const a=t.groups;for(let o=0,h=a.length;o<h;o++){const h=a[o],u=n[h.materialIndex];u&&u.visible&&i.push(e,t,u,s,rv.z,h,r)}}else n.visible&&i.push(e,t,n,s,rv.z,null,r)}}if(!0===e.isBundleGroup&&void 0!==this.backend.beginBundle){const s=i;(i=this._renderLists.get(e,t)).begin(),s.pushBundle({bundleGroup:e,camera:t,renderList:i}),i.finish()}const n=e.children;for(let e=0,a=n.length;e<a;e++)this._projectObject(n[e],t,s,i,r)}_renderBundles(e,t,s){for(const i of e)this._renderBundle(i,t,s)}_renderTransparents(e,t,s,i,r){if(t.length>0){for(const{material:e}of t)e.side=1;this._renderObjects(t,s,i,r,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,s,i,r);for(const{material:e}of t)e.side=2}else this._renderObjects(e,s,i,r)}_renderObjects(e,t,s,i,r=null){for(let n=0,a=e.length;n<a;n++){const{object:a,geometry:o,material:h,group:u,clippingContext:l}=e[n];this._currentRenderObjectFunction(a,s,t,o,h,u,i,l,r)}}_getShadowNodes(e){const t=e.version;let s=this._cacheShadowNodes.get(e);if(void 0===s||s.version!==t){const i=null!==e.map,r=e.colorNode&&e.colorNode.isNode,n=e.castShadowNode&&e.castShadowNode.isNode,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let o=null,h=null,u=null;if(i||r||n||a){let t,s;if(n?(t=e.castShadowNode.rgb,s=e.castShadowNode.a,!0!==this.shadowMap.transmitted&&_t("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(t=lo(0),s=so(1)),i&&(s=s.mul(ld("map","texture",e).a)),r&&(s=s.mul(e.colorNode.a)),h=go(t,s),a){const t=e.maskShadowNode||e.maskNode;h=Ka(([e])=>(t.not().discard(),e))(h)}}e.depthNode&&e.depthNode.isNode&&(u=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),s={version:t,colorNode:h,depthNode:u,positionNode:o},this._cacheShadowNodes.set(e,s)}return s}renderObject(e,t,s,i,r,n,a,o=null,h=null){let u,l,c,d,p=!1;if(e.onBeforeRender(this,t,s,i,r,n),!0===r.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,u=e.isNodeMaterial?e.colorNode:null,l=e.isNodeMaterial?e.depthNode:null,c=e.isNodeMaterial?e.positionNode:null,d=t.overrideMaterial.side,r.positionNode&&r.positionNode.isNode&&(e.positionNode=r.positionNode),e.alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.transparent=r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:s,positionNode:i}=this._getShadowNodes(r);3===this.shadowMap.type?e.side=null!==r.shadowSide?r.shadowSide:r.side:e.side=null!==r.shadowSide?r.shadowSide:nv[r.side],null!==t&&(e.colorNode=t),null!==s&&(e.depthNode=s),null!==i&&(e.positionNode=i)}r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,s,a,n,o,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,s,a,n,o,h),r.side=2):this._handleObjectFunction(e,r,t,s,a,n,o,h),p&&(t.overrideMaterial.colorNode=u,t.overrideMaterial.depthNode=l,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=d),e.onAfterRender(this,t,s,i,r,n)}hasCompatibility(e){return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,s,i,r,n,a,o){const h=this._objects.get(e,t,s,i,r,this._currentRenderContext,a,o);if(h.drawRange=e.geometry.drawRange,h.group=n,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(h),h.bundle=this._currentRenderBundle.bundleGroup}const u=this._nodes.needsRefresh(h);u&&(this._nodes.updateBefore(h),this._geometries.updateForRender(h),this._nodes.updateForRender(h),this._bindings.updateForRender(h)),this._pipelines.updateForRender(h),this.backend.draw(h,this.info),u&&this._nodes.updateAfter(h)}_createObjectPipeline(e,t,s,i,r,n,a,o){const h=this._objects.get(e,t,s,i,r,this._currentRenderContext,a,o);h.drawRange=e.geometry.drawRange,h.group=n,this._nodes.updateBefore(h),this._geometries.updateForRender(h),this._nodes.updateForRender(h),this._bindings.updateForRender(h),this._pipelines.getForRender(h,this._compilationPromises),this._nodes.updateAfter(h)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class ov{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}class hv extends ov{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(_y-e%_y)%_y;var e}get buffer(){return this._buffer}update(){return!0}}class uv extends hv{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let lv=0;class cv extends uv{constructor(e,t){super("UniformBuffer_"+lv++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class dv extends uv{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(!0!==this._updateRangeCache.has(t)){const s=this.updateRanges,i={start:e.offset,count:e.itemSize};s.push(i),this._updateRangeCache.set(t,i)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let s=0,i=this.uniforms.length;s<i;s++){const i=this.uniforms[s],r=i.boundary,n=i.itemSize*e,a=t%_y,o=a%r,h=a+o;t+=o,0!==h&&_y-h<n&&(t+=_y-h),i.offset=t/e,i.index=s,t+=n}return Math.ceil(t/_y)*_y}update(){let e=!1;for(const t of this.uniforms)!0===this.updateByType(t)&&(e=!0);return e}updateByType(e){return e.isNumberUniform?this.updateNumber(e):e.isVector2Uniform?this.updateVector2(e):e.isVector3Uniform?this.updateVector3(e):e.isVector4Uniform?this.updateVector4(e):e.isColorUniform?this.updateColor(e):e.isMatrix3Uniform?this.updateMatrix3(e):e.isMatrix4Uniform?this.updateMatrix4(e):void bt("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r]!==i){this._getBufferForType(n)[r]=s[r]=i,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y){const a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z){const a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,a[r+2]=s[r+2]=i.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z||s[r+4]!==i.w){const a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,a[r+2]=s[r+2]=i.z,a[r+3]=s[r+3]=i.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset;if(s[r+0]!==i.r||s[r+1]!==i.g||s[r+2]!==i.b){const n=this.buffer;n[r+0]=s[r+0]=i.r,n[r+1]=s[r+1]=i.g,n[r+2]=s[r+2]=i.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const s=this.values,i=e.getValue().elements,r=e.offset;if(s[r+0]!==i[0]||s[r+1]!==i[1]||s[r+2]!==i[2]||s[r+4]!==i[3]||s[r+5]!==i[4]||s[r+6]!==i[5]||s[r+8]!==i[6]||s[r+9]!==i[7]||s[r+10]!==i[8]){const n=this.buffer;n[r+0]=s[r+0]=i[0],n[r+1]=s[r+1]=i[1],n[r+2]=s[r+2]=i[2],n[r+4]=s[r+4]=i[3],n[r+5]=s[r+5]=i[4],n[r+6]=s[r+6]=i[5],n[r+8]=s[r+8]=i[6],n[r+9]=s[r+9]=i[7],n[r+10]=s[r+10]=i[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const s=this.values,i=e.getValue().elements,r=e.offset;if(!1===function(e,t,s){for(let i=0,r=t.length;i<r;i++)if(e[s+i]!==t[i])return!1;return!0}(s,i,r)){this.buffer.set(i,r),function(e,t,s){for(let i=0,r=t.length;i<r;i++)e[s+i]=t[i]}(s,i,r),t=!0,this.addUniformUpdateRange(e)}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let pv=0;class mv extends dv{constructor(e,t){super(e),this.id=pv++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class gv extends ov{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let fv=0;class yv extends gv{constructor(e,t){super(e,t),this.id=fv++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class bv extends yv{constructor(e,t,s,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s,this.access=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class _v extends bv{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class xv extends bv{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const vv={bitcast_int_uint:new Cb("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new Cb("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},Tv={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},Sv={low:"lowp",medium:"mediump",high:"highp"},wv={swizzleAssign:!0,storageBuffer:!1},Mv={perspective:"smooth",linear:"noperspective"},Nv={centroid:"centroid"},Ev="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n";class Av extends ax{constructor(e,t){super(e,t,new Ex),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==We}_include(e){const t=vv[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==vv[e]&&this._include(e),Tv[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,s){return`${e} ? ${t} : ${s}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {\n\n\t${s.vars}\n\n${s.code}\n\treturn ${s.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,s=t.count*t.itemSize,{itemSize:i}=t,r=t.array.constructor.name.toLowerCase().includes("int");let n=r?oe:ae;2===i?n=r?ue:he:3===i?n=r?1032:se:4===i&&(n=r?le:ie);const a={Float32Array:Y,Uint8Array:j,Uint16Array:H,Uint32Array:X,Int8Array:$,Int16Array:W,Int32Array:q,Uint8ClampedArray:j},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(s/i))));let h=Math.ceil(s/i/o);o*h*i<s&&h++;const u=o*h*i,l=new e.constructor(u);l.set(e,0),t.array=l;const c=new mr(t.array,o,h,n,a[t.array.constructor.name]||Y);c.needsUpdate=!0,c.isPBOTexture=!0;const d=new kl(c,null,null);d.setPrecision("high"),t.pboNode=d,t.pbo=d.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:s}=e,i=t.value;if(this.renderer.backend.has(i)){this.renderer.backend.get(i).pbo=i.pbo}const r=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName),n=this.getPropertyName(r);this.increaseUsage(s);const a=s.build(this,"uint"),o=this.getDataFromNode(e);let h=o.propertyName;if(void 0===h){const s=this.getVarFromNode(e);h=this.getPropertyName(s);const r=this.getDataFromNode(t);let u=r.propertySizeName;void 0===u&&(u=h+"Size",this.getVarFromNode(t,u,"uint"),this.addLineFlowCode(`${u} = uint( textureSize( ${n}, 0 ).x )`,e),r.propertySizeName=u);const{itemSize:l}=i,c="."+Yn.join("").slice(0,l),d=`ivec2(${a} % ${u}, ${a} / ${u})`,p=this.generateTextureLoad(null,n,d,"0",null,null);let m="vec4";i.pbo.type===X?m="uvec4":i.pbo.type===q&&(m="ivec4"),this.addLineFlowCode(`${h} = ${m}(${p})${c}`,e),o.propertyName=h}return h}generateTextureLoad(e,t,s,i,r,n){let a;return null===i&&(i="0"),a=r?n?`texelFetchOffset( ${t}, ivec3( ${s}, ${r} ), ${i}, ${n} )`:`texelFetch( ${t}, ivec3( ${s}, ${r} ), ${i} )`:n?`texelFetchOffset( ${t}, ${s}, ${i}, ${n} )`:`texelFetch( ${t}, ${s}, ${i} )`,null!==e&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,s,i,r){return i&&(s=`vec3( ${s}, ${i} )`),e.isDepthTexture?r?`textureOffset( ${t}, ${s}, ${r} ).x`:`texture( ${t}, ${s} ).x`:r?`textureOffset( ${t}, ${s}, ${r} )`:`texture( ${t}, ${s} )`}generateTextureLevel(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureLodOffset( ${t}, ${s}, ${i}, ${n} )`:`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureOffset( ${t}, ${s}, ${n}, ${i} )`:`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureGradOffset( ${t}, ${s}, ${i[0]}, ${i[1]}, ${n} )`:`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return e.isCubeTexture?`texture( ${t}, vec4( ${s}, ${i} ) )`:r?n?`textureOffset( ${t}, vec4( ${s}, ${r}, ${i} ), ${n} )`:`texture( ${t}, vec4( ${s}, ${r}, ${i} ) )`:n?`textureOffset( ${t}, vec3( ${s}, ${i} ), ${n} )`:`texture( ${t}, vec3( ${s}, ${i} ) )`;bt(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}getVars(e){const t=[],s=this.vars[e];if(void 0!==s)for(const e of s)t.push(`${this.getVar(e.type,e.name,e.count)};`);return t.join("\n\t")}getUniforms(e){const t=this.uniforms[e],s=[],i={};for(const e of t){let t=null,r=!1;if("texture"===e.type||"texture3D"===e.type){const s=e.node.value;let i="";!0!==s.isDataTexture&&!0!==s.isData3DTexture||(s.type===X?i="u":s.type===q&&(i="i")),t="texture3D"===e.type&&!1===s.isArrayTexture?`${i}sampler3D ${e.name};`:s.compareFunction?!0===s.isArrayTexture?`sampler2DArrayShadow ${e.name};`:`sampler2DShadow ${e.name};`:!0===s.isArrayTexture||!0===s.isDataArrayTexture||!0===s.isCompressedArrayTexture?`${i}sampler2DArray ${e.name};`:`${i}sampler2D ${e.name};`}else if("cubeTexture"===e.type)t=`samplerCube ${e.name};`;else if("cubeDepthTexture"===e.type){t=e.node.value.compareFunction?`samplerCubeShadow ${e.name};`:`samplerCube ${e.name};`}else if("buffer"===e.type){const s=e.node,i=this.getType(s.bufferType),r=s.bufferCount,n=r>0?r:"";t=`${s.name} {\n\t${i} ${e.name}[${n}];\n};\n`}else{const t=e.groupNode.name;if(void 0===i[t]){const e=this.uniformGroups[t];if(void 0!==e){const s=[];for(const t of e.uniforms){const e=t.getType(),i=this.getVectorType(e),r=t.nodeUniform.node.precision;let n=`${i} ${t.name};`;null!==r&&(n=Sv[r]+" "+n),s.push("\t"+n)}i[t]=s}}r=!0}if(!r){const i=e.node.precision;null!==i&&(t=Sv[i]+" "+t),t="uniform "+t,s.push(t)}}let r="";for(const e in i){const t=i[e];r+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==q){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const i=s.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let s=0;for(const i of e)t+=`layout( location = ${s++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[];for(const s of e.members)t.push(`\t${s.type} ${s.name};`);return t.join("\n")}getStructs(e){const t=[],s=this.structs[e],i=[];for(const e of s)if(e.output)for(const t of e.members)i.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let s="struct "+e.name+" {\n";s+=this.getStructMembers(e),s+="\n};\n",t.push(s)}return 0===i.length&&i.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+i.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const s=this.varyings;if("vertex"===e||"compute"===e)for(const i of s){"compute"===e&&(i.needsInterpolation=!0);const s=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){t+=`${Mv[i.interpolationType]||i.interpolationType} ${Nv[i.interpolationSampling]||""} out ${s} ${i.name};\n`}else{t+=`${s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":""}out ${s} ${i.name};\n`}else t+=`${s} ${i.name};\n`}else if("fragment"===e)for(const e of s)if(e.needsInterpolation){const s=this.getType(e.type);if(e.interpolationType){t+=`${Mv[e.interpolationType]||e.interpolationType} ${Nv[e.interpolationSampling]||""} in ${s} ${e.name};\n`}else{t+=`${s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":""}in ${s} ${e.name};\n`}}for(const s of this.builtins[e])t+=`${s};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){bt("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){bt("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){bt("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,s=this.shaderStage){const i=this.extensions[s]||(this.extensions[s]=new Map);!1===i.has(e)&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const s=this.extensions[e];if(void 0!==s)for(const{name:e,behavior:i}of s.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=wv[e];if(void 0===t){let s;switch(t=!1,e){case"float32Filterable":s="OES_texture_float_linear";break;case"clipDistance":s="WEBGL_clip_cull_distance"}if(void 0!==s){const e=this.renderer.backend.extensions;e.has(s)&&(e.get(s),t=!0)}wv[e]=t}return t}isFlipY(){return!0}getUniformBufferLimit(){const e=this.renderer.backend.gl;return e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE)}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s<e.length;s++){const i=e[s],r=this.getPropertyName(i.attributeNode);r&&(t+=`${i.varyingName} = ${r};\n\t`)}return t}_getGLSLUniformStruct(e,t){return`\nlayout( std140 ) uniform ${e} {\n${t}\n};`}_getGLSLVertexCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${Ev}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// transforms\n\t${e.transforms}\n\n\t// flow\n\t${e.flow}\n\n\tgl_PointSize = 1.0;\n\n}\n`}_getGLSLFragmentCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${Ev}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let s="// code\n\n";s+=this.flowCode[t];const i=this.flowNodes[t],r=i[i.length-1];for(const e of i){const i=this.getFlowData(e),n=e.name;n&&(s.length>0&&(s+="\n"),s+=`\t// flow -> ${n}\n\t`),s+=`${i.code}\n\t`,e===r&&"compute"!==t&&(s+="// result\n\t","vertex"===t?(s+="gl_Position = ",s+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${i.result};`)))}const n=e[t];n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=s}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);let a=n.uniformGPU;if(void 0===a){const i=e.groupNode,o=i.name,h=this.getBindGroupArray(o,s);if("texture"===t)a=new bv(r.name,r.node,i),h.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new _v(r.name,r.node,i),h.push(a);else if("texture3D"===t)a=new xv(r.name,r.node,i),h.push(a);else if("buffer"===t){r.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let s=t.buffer;void 0===s&&(e.name=`NodeBuffer_${e.id}`,s=new cv(e,i),s.name=e.name,t.buffer=s),h.push(s),a=s}else{let e=this.uniformGroups[o];void 0===e?(e=new mv(o,i),this.uniformGroups[o]=e,h.push(e)):-1===h.indexOf(e)&&h.push(e),a=this.getNodeUniform(r,t);const s=a.name,n=e.uniforms.some(e=>e.name===s);n||e.addUniform(a)}n.uniformGPU=a}return r}}let Cv=null,Rv=null;class Pv{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[lt]:null,[ut]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),s=this.renderer.info.frame;let i;i=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+e.id+":f"+s}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?ut:lt;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void _t("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const s=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=s,s}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return Cv=Cv||new Ft,this.renderer.getDrawingBufferSize(Cv)}setScissorTest(){}getClearColor(){const e=this.renderer;return Rv=Rv||new Wy,e.getClearColor(Rv),Rv.getRGB(Rv),Rv}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=pt("canvas");return e.style.display="block",e}(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${a} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let Bv,Fv,Dv=0;class Iv{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class Lv{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=s.get(a);let h,u=o.bufferGPU;if(void 0===u&&(u=this._createBuffer(i,t,r,n),o.bufferGPU=u,o.bufferType=t,o.version=a.version),r instanceof Float32Array)h=i.FLOAT;else if("undefined"!=typeof Float16Array&&r instanceof Float16Array)h=i.HALF_FLOAT;else if(r instanceof Uint16Array)h=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)h=i.SHORT;else if(r instanceof Uint32Array)h=i.UNSIGNED_INT;else if(r instanceof Int32Array)h=i.INT;else if(r instanceof Int8Array)h=i.BYTE;else if(r instanceof Uint8Array)h=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);h=i.UNSIGNED_BYTE}let l={bufferGPU:u,bufferType:t,type:h,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:h===i.INT||h===i.UNSIGNED_INT||e.gpuType===q,id:Dv++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);l=new Iv(l,e)}s.set(e,l)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,n=t.get(r),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(a,n.bufferGPU),0===o.length)s.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e<t;e++){const t=o[e];s.bufferSubData(a,t.start*i.BYTES_PER_ELEMENT,i,t.start,t.count)}r.clearUpdateRanges()}s.bindBuffer(a,null),n.version=r.version}destroyAttribute(e){const t=this.backend,{gl:s}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);s.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:s}=t,i=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:r}=t.get(i),n=e.array,a=n.byteLength;s.bindBuffer(s.COPY_READ_BUFFER,r);const o=s.createBuffer();s.bindBuffer(s.COPY_WRITE_BUFFER,o),s.bufferData(s.COPY_WRITE_BUFFER,a,s.STREAM_READ),s.copyBufferSubData(s.COPY_READ_BUFFER,s.COPY_WRITE_BUFFER,0,0,a),await t.utils._clientWaitAsync();const h=new e.array.constructor(n.length);return s.bindBuffer(s.COPY_WRITE_BUFFER,o),s.getBufferSubData(s.COPY_WRITE_BUFFER,0,h),s.deleteBuffer(o),s.bindBuffer(s.COPY_READ_BUFFER,null),s.bindBuffer(s.COPY_WRITE_BUFFER,null),h.buffer}_createBuffer(e,t,s,i){const r=e.createBuffer();return e.bindBuffer(t,r),e.bufferData(t,s,i),e.bindBuffer(t,null),r}}class Ov{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;Bv={[l]:e.FUNC_ADD,[c]:e.FUNC_SUBTRACT,[d]:e.FUNC_REVERSE_SUBTRACT},Fv={[p]:e.ZERO,[m]:e.ONE,[g]:e.SRC_COLOR,[y]:e.SRC_ALPHA,[S]:e.SRC_ALPHA_SATURATE,[v]:e.DST_COLOR,[_]:e.DST_ALPHA,[f]:e.ONE_MINUS_SRC_COLOR,[b]:e.ONE_MINUS_SRC_ALPHA,[T]:e.ONE_MINUS_DST_COLOR,[x]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=(new es).fromArray(t),this.currentViewport=(new es).fromArray(s),this._tempVec4=new es}enable(e){const{enabled:t}=this;!0!==t[e]&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;!1!==t[e]&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;0!==e?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(1===e?t.cullFace(t.BACK):2===e?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:s}=this;e!==t&&(s.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,s){const i=this.gl,r=this.backend.drawBuffersIndexedExt;if(r)for(let n=0;n<e.length;n++){const a=e[n];let o=null;if(null!==t){const e=t.getBlendMode(a.name);6===e.blending?o=s:0!==e.blending&&(o=e)}else o=s;null!==o?this._setMRTBlendingIndex(n,o):r.blendFuncSeparateiOES(n,i.ONE,i.ZERO,i.ONE,i.ZERO)}else _t("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.")}_setMRTBlendingIndex(e,t){const{gl:s}=this,i=this.backend.drawBuffersIndexedExt,r=t.blending,n=t.blendSrc,a=t.blendDst,o=t.blendEquation,h=t.premultipliedAlpha;if(5===r){const s=null!==t.blendSrcAlpha?t.blendSrcAlpha:n,r=null!==t.blendDstAlpha?t.blendDstAlpha:a,h=null!==t.blendEquationAlpha?t.blendEquationAlpha:o;i.blendEquationSeparateiOES(e,Bv[o],Bv[h]),i.blendFuncSeparateiOES(e,Fv[n],Fv[a],Fv[s],Fv[r])}else if(i.blendEquationSeparateiOES(e,s.FUNC_ADD,s.FUNC_ADD),h)switch(r){case 1:default:i.blendFuncSeparateiOES(e,s.ONE,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,s.ONE,s.ONE,s.ONE,s.ONE);break;case 3:i.blendFuncSeparateiOES(e,s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:i.blendFuncSeparateiOES(e,s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ZERO,s.ONE)}else switch(r){case 1:default:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE,s.ONE,s.ONE);break;case 3:i.blendFuncSeparateiOES(e,s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:i.blendFuncSeparateiOES(e,s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ZERO,s.ONE)}}setBlending(e,t,s,i,r,n,a,o){const{gl:h}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(h.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,n=n||s,a=a||i,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(h.blendEquationSeparate(Bv[t],Bv[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(h.blendFuncSeparate(Fv[s],Fv[i],Fv[n],Fv[a]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=n,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||o!==this.currentPremultipledAlpha){if(this.currentBlendEquation===l&&this.currentBlendEquationAlpha===l||(h.blendEquation(h.FUNC_ADD),this.currentBlendEquation=l,this.currentBlendEquationAlpha=l),o)switch(e){case 1:h.blendFuncSeparate(h.ONE,h.ONE_MINUS_SRC_ALPHA,h.ONE,h.ONE_MINUS_SRC_ALPHA);break;case 2:h.blendFunc(h.ONE,h.ONE);break;case 3:h.blendFuncSeparate(h.ZERO,h.ONE_MINUS_SRC_COLOR,h.ZERO,h.ONE);break;case 4:h.blendFuncSeparate(h.DST_COLOR,h.ONE_MINUS_SRC_ALPHA,h.ZERO,h.ONE);break;default:bt("WebGLState: Invalid blending: ",e)}else switch(e){case 1:h.blendFuncSeparate(h.SRC_ALPHA,h.ONE_MINUS_SRC_ALPHA,h.ONE,h.ONE_MINUS_SRC_ALPHA);break;case 2:h.blendFuncSeparate(h.SRC_ALPHA,h.ONE,h.ONE,h.ONE);break;case 3:bt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:bt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:bt("WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=o}}else!0===this.currentBlendingEnabled&&(this.disable(h.BLEND),this.currentBlendingEnabled=!1)}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setReversedDepth(e){if(this.currentDepthReversed!==e){const t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=xt[e]),this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}this.currentDepthFunc=e}}scissor(e,t,s,i){const r=this._tempVec4.set(e,t,s,i);if(!1===this.currentScissor.equals(r)){const{gl:e}=this;e.scissor(r.x,r.y,r.z,r.w),this.currentScissor.copy(r)}}viewport(e,t,s,i){const r=this._tempVec4.set(e,t,s,i);if(!1===this.currentViewport.equals(r)){const{gl:e}=this;e.viewport(r.x,r.y,r.z,r.w),this.currentViewport.copy(r)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,s){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===s||(this.gl.stencilFunc(e,t,s),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=s)}setStencilOp(e,t,s){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===s||(this.gl.stencilOp(e,t,s),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=s)}setMaterial(e,t,s){const{gl:i}=this;2===e.side?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let r=1===e.side;t&&(r=!r),this.setFlipSided(r),1===e.blending&&!1===e.transparent?this.setBlending(0):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const n=e.stencilWrite;if(this.setStencilTest(n),n&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage&&this.backend.renderer.currentSamples>0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),s>0&&this.currentClippingPlanes!==s){const e=12288;for(let t=0;t<8;t++)t<s?this.enable(e+t):this.disable(e+t)}}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===s||(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const s=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(s.bindVertexArray(e),null!==t&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0)}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:s,currentBoundFramebuffers:i}=this;return i[e]!==t&&(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:s}=this;let i=[],r=!1;if(null!==e.textures){i=this.currentDrawbuffers.get(t),void 0===i&&(i=[],this.currentDrawbuffers.set(t,i));const n=e.textures;if(i.length!==n.length||i[0]!==s.COLOR_ATTACHMENT0){for(let e=0,t=n.length;e<t;e++)i[e]=s.COLOR_ATTACHMENT0+e;i.length=n.length,r=!0}}else i[0]!==s.BACK&&(i[0]=s.BACK,r=!0);r&&s.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:s,maxTextures:i}=this;void 0===e&&(e=t.TEXTURE0+i-1),s!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,s){const{gl:i,currentTextureSlot:r,currentBoundTextures:n,maxTextures:a}=this;void 0===s&&(s=null===r?i.TEXTURE0+a-1:r);let o=n[s];void 0===o&&(o={type:void 0,texture:void 0},n[s]=o),o.type===e&&o.texture===t||(r!==s&&(i.activeTexture(s),this.currentTextureSlot=s),i.bindTexture(e,t),o.type=e,o.texture=t)}bindBufferBase(e,t,s){const{gl:i}=this,r=`${e}-${t}`;return this.currentBoundBufferBases[r]!==s&&(i.bindBufferBase(e,t,s),this.currentBoundBufferBases[r]=s,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:s}=this,i=s[t];void 0!==i&&void 0!==i.type&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}}class Uv{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=""){const{gl:s,extensions:i}=this;let r;const n=jt.getTransfer(t);if(e===j)return s.UNSIGNED_BYTE;if(e===Q)return s.UNSIGNED_SHORT_4_4_4_4;if(e===Z)return s.UNSIGNED_SHORT_5_5_5_1;if(e===ee)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===te)return s.UNSIGNED_INT_10F_11F_11F_REV;if(e===$)return s.BYTE;if(e===W)return s.SHORT;if(e===H)return s.UNSIGNED_SHORT;if(e===q)return s.INT;if(e===X)return s.UNSIGNED_INT;if(e===Y)return s.FLOAT;if(e===K)return s.HALF_FLOAT;if(1021===e)return s.ALPHA;if(e===se)return s.RGB;if(e===ie)return s.RGBA;if(e===re)return s.DEPTH_COMPONENT;if(e===ne)return s.DEPTH_STENCIL;if(e===ae)return s.RED;if(e===oe)return s.RED_INTEGER;if(e===he)return s.RG;if(e===ue)return s.RG_INTEGER;if(e===le)return s.RGBA_INTEGER;if(e===ce||e===de||e===pe||e===me)if(n===Ye){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===ce)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===de)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===pe)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===me)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===ce)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===de)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===pe)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===me)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===ge||e===fe||e===ye||e===be){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(e===ge)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===fe)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===ye)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===be)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===_e||e===xe||e===ve||e===Te||e===Se||e===we||e===Me){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(e===_e||e===xe)return n===Ye?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===ve)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===Te)return r.COMPRESSED_R11_EAC;if(e===Se)return r.COMPRESSED_SIGNED_R11_EAC;if(e===we)return r.COMPRESSED_RG11_EAC;if(e===Me)return r.COMPRESSED_SIGNED_RG11_EAC}if(e===Ne||e===Ee||e===Ae||e===Ce||e===Re||e===Pe||e===Be||e===Fe||e===De||e===Ie||e===Le||e===Oe||e===Ue||e===ke){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===Ne)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Ee)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Ae)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Ce)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Re)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===Pe)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Be)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Fe)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===De)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Ie)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Le)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Oe)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Ue)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===ke)return n===Ye?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===ze){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===ze)return n===Ye?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(e===Ve||e===Ge||e===je||e===$e){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===Ve)return r.COMPRESSED_RED_RGTC1_EXT;if(e===Ge)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===je)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===$e)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===J?s.UNSIGNED_INT_24_8:void 0!==s[e]?s[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((s,i)=>{!function r(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void i();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),s()):requestAnimationFrame(r)}()})}}let kv,zv,Vv,Gv=!1;class jv{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===Gv&&(this._init(),Gv=!0)}_init(){const e=this.gl;kv={[D]:e.REPEAT,[I]:e.CLAMP_TO_EDGE,[L]:e.MIRRORED_REPEAT},zv={[O]:e.NEAREST,[U]:e.NEAREST_MIPMAP_NEAREST,[k]:e.NEAREST_MIPMAP_LINEAR,[z]:e.LINEAR,[V]:e.LINEAR_MIPMAP_NEAREST,[G]:e.LINEAR_MIPMAP_LINEAR},Vv={[Qe]:e.NEVER,[rt]:e.ALWAYS,[Ze]:e.LESS,[et]:e.LEQUAL,[Je]:e.EQUAL,[it]:e.GEQUAL,[tt]:e.GREATER,[st]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,r=!1){const{gl:n,extensions:a}=this;if(null!==e){if(void 0!==n[e])return n[e];yt("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===n.RED&&(s===n.FLOAT&&(o=n.R32F),s===n.HALF_FLOAT&&(o=n.R16F),s===n.UNSIGNED_BYTE&&(o=n.R8),s===n.UNSIGNED_SHORT&&(o=n.R16),s===n.UNSIGNED_INT&&(o=n.R32UI),s===n.BYTE&&(o=n.R8I),s===n.SHORT&&(o=n.R16I),s===n.INT&&(o=n.R32I)),t===n.RED_INTEGER&&(s===n.UNSIGNED_BYTE&&(o=n.R8UI),s===n.UNSIGNED_SHORT&&(o=n.R16UI),s===n.UNSIGNED_INT&&(o=n.R32UI),s===n.BYTE&&(o=n.R8I),s===n.SHORT&&(o=n.R16I),s===n.INT&&(o=n.R32I)),t===n.RG&&(s===n.FLOAT&&(o=n.RG32F),s===n.HALF_FLOAT&&(o=n.RG16F),s===n.UNSIGNED_BYTE&&(o=n.RG8),s===n.UNSIGNED_SHORT&&(o=n.RG16),s===n.UNSIGNED_INT&&(o=n.RG32UI),s===n.BYTE&&(o=n.RG8I),s===n.SHORT&&(o=n.RG16I),s===n.INT&&(o=n.RG32I)),t===n.RG_INTEGER&&(s===n.UNSIGNED_BYTE&&(o=n.RG8UI),s===n.UNSIGNED_SHORT&&(o=n.RG16UI),s===n.UNSIGNED_INT&&(o=n.RG32UI),s===n.BYTE&&(o=n.RG8I),s===n.SHORT&&(o=n.RG16I),s===n.INT&&(o=n.RG32I)),t===n.RGB){const e=r?Xe:jt.getTransfer(i);s===n.FLOAT&&(o=n.RGB32F),s===n.HALF_FLOAT&&(o=n.RGB16F),s===n.UNSIGNED_BYTE&&(o=n.RGB8),s===n.UNSIGNED_SHORT&&(o=n.RGB16),s===n.UNSIGNED_INT&&(o=n.RGB32UI),s===n.BYTE&&(o=n.RGB8I),s===n.SHORT&&(o=n.RGB16I),s===n.INT&&(o=n.RGB32I),s===n.UNSIGNED_BYTE&&(o=e===Ye?n.SRGB8:n.RGB8),s===n.UNSIGNED_SHORT_5_6_5&&(o=n.RGB565),s===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1),s===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGB4),s===n.UNSIGNED_INT_5_9_9_9_REV&&(o=n.RGB9_E5),s===n.UNSIGNED_INT_10F_11F_11F_REV&&(o=n.R11F_G11F_B10F)}if(t===n.RGB_INTEGER&&(s===n.UNSIGNED_BYTE&&(o=n.RGB8UI),s===n.UNSIGNED_SHORT&&(o=n.RGB16UI),s===n.UNSIGNED_INT&&(o=n.RGB32UI),s===n.BYTE&&(o=n.RGB8I),s===n.SHORT&&(o=n.RGB16I),s===n.INT&&(o=n.RGB32I)),t===n.RGBA){const e=r?Xe:jt.getTransfer(i);s===n.FLOAT&&(o=n.RGBA32F),s===n.HALF_FLOAT&&(o=n.RGBA16F),s===n.UNSIGNED_BYTE&&(o=n.RGBA8),s===n.UNSIGNED_SHORT&&(o=n.RGBA16),s===n.UNSIGNED_INT&&(o=n.RGBA32UI),s===n.BYTE&&(o=n.RGBA8I),s===n.SHORT&&(o=n.RGBA16I),s===n.INT&&(o=n.RGBA32I),s===n.UNSIGNED_BYTE&&(o=e===Ye?n.SRGB8_ALPHA8:n.RGBA8),s===n.UNSIGNED_SHORT_4_4_4_4&&(o=n.RGBA4),s===n.UNSIGNED_SHORT_5_5_5_1&&(o=n.RGB5_A1)}return t===n.RGBA_INTEGER&&(s===n.UNSIGNED_BYTE&&(o=n.RGBA8UI),s===n.UNSIGNED_SHORT&&(o=n.RGBA16UI),s===n.UNSIGNED_INT&&(o=n.RGBA32UI),s===n.BYTE&&(o=n.RGBA8I),s===n.SHORT&&(o=n.RGBA16I),s===n.INT&&(o=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(s===n.UNSIGNED_SHORT&&(o=n.DEPTH_COMPONENT16),s===n.UNSIGNED_INT&&(o=n.DEPTH_COMPONENT24),s===n.FLOAT&&(o=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&s===n.UNSIGNED_INT_24_8&&(o=n.DEPTH24_STENCIL8),o!==n.R16F&&o!==n.R32F&&o!==n.RG16F&&o!==n.RG32F&&o!==n.RGBA16F&&o!==n.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this,n=jt.getPrimaries(jt.workingColorSpace),a=t.colorSpace===We?null:jt.getPrimaries(t.colorSpace),o=t.colorSpace===We||n===a?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),s.texParameteri(e,s.TEXTURE_WRAP_S,kv[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,kv[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,kv[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,zv[t.magFilter]);const h=void 0!==t.mipmaps&&t.mipmaps.length>0,u=t.minFilter===z&&h?G:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,zv[u]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,Vv[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===O)return;if(t.minFilter!==k&&t.minFilter!==G)return;if(t.type===Y&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,r=this.getGLTextureType(e);let n=i[r];void 0===n&&(n=t.createTexture(),s.state.bindTexture(r,n),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=n),s.set(e,{textureGPU:n,glTextureType:r})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:r,width:n,height:a,depth:o}=t,h=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),l=this.getInternalFormat(e.internalFormat,h,u,e.colorSpace,e.isVideoTexture),c=s.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,c),this.setTextureParameters(d,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,r,l,n,a,o):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,r,l,n,a,o):e.isVideoTexture||s.texStorage2D(d,r,l,n,a),i.set(e,{textureGPU:c,glTextureType:d,glFormat:h,glType:u,glInternalFormat:l})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:r,glTextureType:n,glFormat:a,glType:o}=i.get(t),{width:h,height:u}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(n,r),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(n,0,0,0,h,u,a,o,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:r}=t,{textureGPU:n,glTextureType:a,glFormat:o,glType:h,glInternalFormat:u}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t<i.length;t++){const n=i[t];e.isCompressedArrayTexture?e.format!==s.RGBA?null!==o?s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,o,n.data):yt("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):s.texSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,o,h,n.data):null!==o?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,o,n.data):yt("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const n=t.images,a=e.mipmaps;for(let e=0;e<6;e++){const t=$v(n[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,i,r,o,h,t);for(let t=0;t<a.length;t++){const i=$v(a[t].images[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,i.width,i.height,o,h,i)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const i=t.image;if(e.layerUpdates.size>0){const t=Sn(i.width,i.height,e.format,e.type);for(const r of e.layerUpdates){const e=i.data.subarray(r*t/i.data.BYTES_PER_ELEMENT,(r+1)*t/i.data.BYTES_PER_ELEMENT);s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,r,i.width,i.height,1,o,h,e)}e.clearLayerUpdates()}else s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,i.width,i.height,i.depth,o,h,i.data)}else if(e.isData3DTexture){const e=t.image;s.texSubImage3D(s.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,h,e.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(a,0,u,o,h,t.image);else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e<t;e++){const t=n[e],i=$v(t);s.texSubImage2D(a,e,0,0,t.width,t.height,o,h,i)}else{const e=$v(t.image);s.texSubImage2D(a,0,0,0,i,r,o,h,e)}}}generateMipmaps(e){const{gl:t,backend:s}=this,{textureGPU:i,glTextureType:r}=s.get(e);s.state.bindTexture(r,i),t.generateMipmap(r)}deallocateRenderBuffers(e){const{gl:t,backend:s}=this;if(e){const i=s.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const e in i.framebuffers)t.deleteFramebuffer(i.framebuffers[e]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let e=0;e<i.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(i.msaaRenderbuffers[e]);delete i.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:s,backend:i}=this,{textureGPU:r,renderTarget:n}=i.get(e);this.deallocateRenderBuffers(n),!1===t&&s.deleteTexture(r),i.delete(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){const{gl:a,backend:o}=this,{state:h}=this.backend,{textureGPU:u,glTextureType:l,glType:c,glFormat:d}=o.get(t);let p,m,g,f,y,b,_,x,v;h.bindTexture(l,u);const T=e.isCompressedTexture?e.mipmaps[n]:e.image;if(null!==s)p=s.max.x-s.min.x,m=s.max.y-s.min.y,g=s.isBox3?s.max.z-s.min.z:1,f=s.min.x,y=s.min.y,b=s.isBox3?s.min.z:0;else{const t=Math.pow(2,-r);p=Math.floor(T.width*t),m=Math.floor(T.height*t),g=e.isDataArrayTexture||e.isArrayTexture?T.depth:e.isData3DTexture?Math.floor(T.depth*t):1,f=0,y=0,b=0}null!==i?(_=i.x,x=i.y,v=i.z):(_=0,x=0,v=0),a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const S=a.getParameter(a.UNPACK_ROW_LENGTH),w=a.getParameter(a.UNPACK_IMAGE_HEIGHT),M=a.getParameter(a.UNPACK_SKIP_PIXELS),N=a.getParameter(a.UNPACK_SKIP_ROWS),E=a.getParameter(a.UNPACK_SKIP_IMAGES);a.pixelStorei(a.UNPACK_ROW_LENGTH,T.width),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,T.height),a.pixelStorei(a.UNPACK_SKIP_PIXELS,f),a.pixelStorei(a.UNPACK_SKIP_ROWS,y),a.pixelStorei(a.UNPACK_SKIP_IMAGES,b);const A=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,C=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const s=o.get(e),i=o.get(t),l=o.get(s.renderTarget),c=o.get(i.renderTarget),d=l.framebuffers[s.cacheKey],T=c.framebuffers[i.cacheKey];h.bindFramebuffer(a.READ_FRAMEBUFFER,d),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,T);for(let e=0;e<g;e++)A&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,s.textureGPU,r,b+e),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,u,n,v+e)),a.blitFramebuffer(f,y,p,m,_,x,p,m,a.DEPTH_BUFFER_BIT,a.NEAREST);h.bindFramebuffer(a.READ_FRAMEBUFFER,null),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else if(0!==r||e.isRenderTargetTexture||o.has(e)){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer()),h.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<g;e++)A?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,t.textureGPU,r,b+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t.textureGPU,r),C?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,u,n,v+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,u,n),0!==r?a.blitFramebuffer(f,y,p,m,_,x,p,m,a.COLOR_BUFFER_BIT,a.NEAREST):C?a.copyTexSubImage3D(l,n,_,x,v+e,f,y,p,m):a.copyTexSubImage2D(l,n,_,x,f,y,p,m);h.bindFramebuffer(a.READ_FRAMEBUFFER,null),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else C?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(l,n,_,x,v,p,m,g,d,c,T.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(l,n,_,x,v,p,m,g,d,T.data):a.texSubImage3D(l,n,_,x,v,p,m,g,d,c,T):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,n,_,x,p,m,d,c,T.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,n,_,x,T.width,T.height,d,T.data):a.texSubImage2D(a.TEXTURE_2D,n,_,x,p,m,d,c,T);a.pixelStorei(a.UNPACK_ROW_LENGTH,S),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,w),a.pixelStorei(a.UNPACK_SKIP_PIXELS,M),a.pixelStorei(a.UNPACK_SKIP_ROWS,N),a.pixelStorei(a.UNPACK_SKIP_IMAGES,E),0===n&&t.generateMipmaps&&a.generateMipmap(l),h.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:r}=this.backend,{textureGPU:n}=this.backend.get(e),{x:a,y:o,z:h,w:u}=s,l=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(l){const s=0!==a||0!==o;let l,d;if(!0===e.isDepthTexture?(l=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(l|=i.STENCIL_BUFFER_BIT)):(l=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),s){const e=this.backend.get(t.renderTarget),s=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,s),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=c-o-u;i.blitFramebuffer(a,p,a+h,p+u,a,p,a+h,p+u,l,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,s),r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,p,h,u),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,n,0),i.blitFramebuffer(0,0,h,u,0,0,h,u,l,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,c-u-o,h,u),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,s,i=!1){const{gl:r}=this,n=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:h,width:u,height:l}=n;if(r.bindRenderbuffer(r.RENDERBUFFER,e),o&&!h){let t=r.DEPTH_COMPONENT24;if(!0===i){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,n.samples,t,u,l)}else s>0?(a&&a.isDepthTexture&&a.type===r.FLOAT&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,s,t,u,l)):r.renderbufferStorage(r.RENDERBUFFER,t,u,l);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else o&&h&&(s>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,s,r.DEPTH24_STENCIL8,u,l):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,u,l),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e));r.bindRenderbuffer(r.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,s,i,r,n){const{backend:a,gl:o}=this,{textureGPU:h,glFormat:u,glType:l}=this.backend.get(e),c=o.createFramebuffer();a.state.bindFramebuffer(o.READ_FRAMEBUFFER,c);const d=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,d,h,0);const p=this._getTypedArrayType(l),m=i*r*this._getBytesPerTexel(l,u),g=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,g),o.bufferData(o.PIXEL_PACK_BUFFER,m,o.STREAM_READ),o.readPixels(t,s,i,r,u,l,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new p(m/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,g),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteFramebuffer(c),f}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:s}=this;let i=0;return e===s.UNSIGNED_BYTE&&(i=1),e!==s.UNSIGNED_SHORT_4_4_4_4&&e!==s.UNSIGNED_SHORT_5_5_5_1&&e!==s.UNSIGNED_SHORT_5_6_5&&e!==s.UNSIGNED_SHORT&&e!==s.HALF_FLOAT||(i=2),e!==s.UNSIGNED_INT&&e!==s.FLOAT||(i=4),t===s.RGBA?4*i:t===s.RGB?3*i:t===s.ALPHA?i:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function $v(e){return e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas?e:e.data}class Wv{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class Hv{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const qv={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class Xv{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:s,mode:i,object:r,type:n,info:a,index:o}=this;0!==o?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),a.update(r,t,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:a,object:o,info:h}=this;0!==s&&(0!==a?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),h.update(o,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:a}=this;if(0===s)return;const o=i.get("WEBGL_multi_draw");if(null===o)for(let i=0;i<s;i++)this.render(e[i],t[i]);else{0!==this.index?o.multiDrawElementsWEBGL(r,t,0,this.type,e,0,s):o.multiDrawArraysWEBGL(r,e,0,t,0,s);let i=0;for(let e=0;e<s;e++)i+=t[e];a.update(n,i,1)}}renderMultiDrawInstances(e,t,s,i){const{extensions:r,mode:n,object:a,info:o}=this;if(0===s)return;const h=r.get("WEBGL_multi_draw");if(null===h)for(let r=0;r<s;r++)this.renderInstances(e[r],t[r],i[r]);else{0!==this.index?h.multiDrawElementsInstancedWEBGL(n,t,0,this.type,e,0,i,0,s):h.multiDrawArraysInstancedWEBGL(n,e,0,t,0,i,0,s);let r=0;for(let e=0;e<s;e++)r+=t[e]*i[e];o.update(a,r,1)}}}class Yv{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return void 0===t&&(yt(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class Kv extends Yv{constructor(e,t,s=2048){if(super(s),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return yt("EXT_disjoint_timer_query not supported; timestamps will be disabled."),void(this.trackTimestamp=!1);this.queries=[];for(let t=0;t<this.maxQueries;t++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return _t(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const s=this.queries[t];if(s)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,s),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){bt("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){bt("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[t,s]of this.queryOffsets){if("ended"===this.queryStates.get(s)){const i=this.queries[s];e.set(t,this.resolveQuery(i))}}if(0===e.size)return this.lastValue;const t={},s=[];for(const[i,r]of e){const e=i.match(/^(.*):f(\d+)$/),n=parseInt(e[2]);!1===s.includes(n)&&s.push(n),void 0===t[n]&&(t[n]=0);const a=await r;this.timestamps.set(i,a),t[n]+=a}const i=t[s[s.length-1]];return this.lastValue=i,this.frames=s,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return bt("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed)return void t(this.lastValue);let s,i=!1;const r=e=>{i||(i=!0,s&&(clearTimeout(s),s=null),t(e))},n=()=>{if(this.isDisposed)r(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void r(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(s=setTimeout(n,1));const i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(i)/1e6)}catch(e){bt("Error checking query:",e),t(this.lastValue)}};n()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class Qv extends Pv{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,s={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=void 0!==t.context?t.context:e.domElement.getContext("webgl2",s);function r(t){t.preventDefault();const s={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(s)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=i,this.extensions=new Wv(this),this.capabilities=new Hv(this),this.attributeUtils=new Lv(this),this.textureUtils=new jv(this),this.bufferRenderer=new Xv(this),this.state=new Ov(this),this.utils=new Uv(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),!0===t.reversedDepthBuffer&&this.extensions.has("EXT_clip_control")&&this.state.setReversedDepth(!0)}get coordinateSystem(){return ot}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,s=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),null!==s){const t=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:s,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&yt("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new Kv(this.gl,e,2048));const s=this.timestampQueryPool[e];null!==s.allocateQueriesForContext(t)&&s.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,s=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:s}=this.getDrawingBufferSize();t.viewport(0,0,e,s)}if(e.scissor)this.updateScissor(e);else{const{width:e,height:s}=this.getDrawingBufferSize();t.scissor(0,0,e,s)}this.initTimestampQuery(lt,this.getTimestampUID(e)),s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext;s.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e<a.length;e++){const t=a[e];t.generateMipmaps&&this.generateMipmaps(t)}if(this._currentContext=r,this._resolveRenderTarget(e),null!==r){if(this._setFramebuffer(r),r.viewport)this.updateViewport(r);else{const{width:e,height:t}=this.getDrawingBufferSize();s.viewport(0,0,e,t)}if(r.scissor)this.updateScissor(r);else{const{width:e,height:t}=this.getDrawingBufferSize();s.scissor(0,0,e,t)}}this.prepareTimestampBuffer(lt,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const e=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const n=()=>{let a=0;for(let t=0;t<s.length;t++){const n=s[t];null!==n&&(r.getQueryParameter(n,r.QUERY_RESULT_AVAILABLE)&&(0===r.getQueryParameter(n,r.QUERY_RESULT)&&e.add(i[t]),s[t]=null,r.deleteQuery(n),a++))}a<s.length?requestAnimationFrame(n):t.occluded=e};n()}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:s,y:i,width:r,height:n}=e.viewportValue;t.viewport(s,e.height-n-i,r,n)}updateScissor(e){const{state:t}=this,{x:s,y:i,width:r,height:n}=e.scissorValue;t.scissor(s,e.height-n-i,r,n)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,s,i=null,r=!0,n=!0){const{gl:a,renderer:o}=this;if(null===i){i={textures:null,clearColorValue:this.getClearColor()}}let h=0;if(e&&(h|=a.COLOR_BUFFER_BIT),t&&(h|=a.DEPTH_BUFFER_BIT),s&&(h|=a.STENCIL_BUFFER_BIT),0!==h){let u;u=i.clearColorValue?i.clearColorValue:this.getClearColor();const l=o.getClearDepth(),c=o.getClearStencil();if(t&&this.state.setDepthMask(!0),null===i.textures)a.clearColor(u.r,u.g,u.b,u.a),a.clear(h);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++)0===e?a.clearBufferfv(a.COLOR,e,[u.r,u.g,u.b,u.a]):a.clearBufferfv(a.COLOR,e,[0,0,0,1]);t&&s?a.clearBufferfi(a.DEPTH_STENCIL,0,l,c):t?a.clearBufferfv(a.DEPTH,0,[l]):s&&a.clearBufferiv(a.STENCIL,0,[c]),r&&n&&this._resolveRenderTarget(i)}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(ut,this.getTimestampUID(e))}compute(e,t,s,i,r=null){const{state:n,gl:a}=this;!1===this.discard&&(n.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformBuffers:h,attributes:u}=this.get(i),l=this._getVaoKey(u),c=this.vaoCache[l];void 0===c?this.vaoCache[l]=this._createVao(u):n.setVertexState(c),n.useProgram(o),this._bindUniforms(s);const d=this._getTransformFeedback(h);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,d),a.beginTransformFeedback(a.POINTS),r=null!==r?r:t.count,Array.isArray(r)?(_t("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute&&(_t("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),r=t.count),u[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,r):a.drawArrays(a.POINTS,0,r),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let e=0;e<h.length;e++){const t=h[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const{state:t,gl:s}=this;this.discard=!1,t.disable(s.RASTERIZER_DISCARD),this.prepareTimestampBuffer(ut,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:s,material:i,context:r,hardwareClippingPlanes:n}=e,{programGPU:a}=this.get(s),{gl:o,state:h}=this,u=this.get(r),l=e.getDrawParameters();if(null===l)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinant()<0;h.setMaterial(i,c,n),null!==r.mrt&&null!==r.textures&&h.setMRTBlending(r.textures,r.mrt,i),h.useProgram(a);const d=e.getAttributes(),p=this.get(d);let m=p.vaoGPU;if(void 0===m){const e=this._getVaoKey(d);m=this.vaoCache[e],void 0===m&&(m=this._createVao(d),this.vaoCache[e]=m,p.vaoGPU=m)}const g=e.getIndex(),f=null!==g?this.get(g).bufferGPU:null;h.setVertexState(m,f);const y=u.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),u.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),u.occlusionQueries[u.occlusionQueryIndex]=e,u.occlusionQueryObjects[u.occlusionQueryIndex]=t}u.lastOcclusionObject=t}const b=this.bufferRenderer;t.isPoints?b.mode=o.POINTS:t.isLineSegments?b.mode=o.LINES:t.isLine?b.mode=o.LINE_STRIP:t.isLineLoop?b.mode=o.LINE_LOOP:!0===i.wireframe?(h.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=o.LINES):b.mode=o.TRIANGLES;const{vertexCount:_,instanceCount:x}=l;let{firstVertex:v}=l;if(b.object=t,null!==g){v*=g.array.BYTES_PER_ELEMENT;const e=this.get(g);b.index=g.count,b.type=e.type}else b.index=0;const T=()=>{t.isBatchedMesh?null!==t._multiDrawInstances?(_t("WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),b.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?b.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):_t("WebGLBackend: WEBGL_multi_draw not supported."):x>1?b.renderInstances(v,_,x):b.render(v,_)};if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const s=this.get(e.camera),i=e.camera.cameras,r=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===s.indexesGPU||s.indexesGPU.length!==i.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let s=0,r=i.length;s<r;s++){const i=o.createBuffer();e[0]=s,o.bindBuffer(o.UNIFORM_BUFFER,i),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(i)}s.indexesGPU=t}const n=this.get(r),a=this.renderer.getPixelRatio(),u=this._currentContext.renderTarget,l=this._isRenderCameraDepthArray(this._currentContext),c=this._currentContext.activeCubeFace;if(l){const e=this.get(u.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=u;for(let e=0,s=i.length;e<s;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1,!1);this.renderer._activeCubeFace=c,this._currentContext.activeCubeFace=c}}for(let r=0,u=i.length;r<u;r++){const u=i[r];if(t.layers.test(u.layers)){l&&(this.renderer._activeCubeFace=r,this._currentContext.activeCubeFace=r,this._setFramebuffer(this._currentContext));const t=u.viewport;if(void 0!==t){const s=t.x*a,i=t.y*a,r=t.width*a,n=t.height*a;h.viewport(Math.floor(s),Math.floor(e.context.height-n-i),Math.floor(r),Math.floor(n))}h.bindBufferBase(o.UNIFORM_BUFFER,n.index,s.indexesGPU[r]),T()}this._currentContext.activeCubeFace=c,this.renderer._activeCubeFace=c}}else T()}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}updateSampler(){return""}createNodeBuilder(e,t){return new Av(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,r="fragment"===s?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:n}=i,a=s.createProgram(),o=this.get(r).shaderGPU,h=this.get(n).shaderGPU;if(s.attachShader(a,o),s.attachShader(a,h),s.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:o,vertexShader:h}),null!==t&&this.parallel){const r=new Promise(t=>{const r=this.parallel,n=()=>{s.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(n)};n()});return void t.push(r)}this._completeCompile(e,i)}_handleSource(e,t){const s=e.split("\n"),i=[],r=Math.max(t-6,0),n=Math.min(t+6,s.length);for(let e=r;e<n;e++){const r=e+1;i.push(`${r===t?">":" "} ${r}: ${s[e]}`)}return i.join("\n")}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const n=/ERROR: 0:(\d+)/.exec(r);if(n){const i=parseInt(n[1]);return s.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=(i.getProgramInfoLog(e)||"").trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,s,t);else{const n=this._getShaderErrors(i,s,"vertex"),a=this._getShaderErrors(i,t,"fragment");bt("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+a)}else""!==r&&yt("WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,a,o),s.useProgram(n);const h=e.getBindings();this._setupBindings(h,n),this.set(t,{programGPU:n})}createComputePipeline(e,t){const{state:s,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:n}=e,a=i.createProgram(),o=this.get(r).shaderGPU,h=this.get(n).shaderGPU,u=n.transforms,l=[],c=[];for(let e=0;e<u.length;e++){const t=u[e];l.push(t.varyingName),c.push(t.attributeNode)}i.attachShader(a,o),i.attachShader(a,h),i.transformFeedbackVaryings(a,l,i.SEPARATE_ATTRIBS),i.linkProgram(a),!1===i.getProgramParameter(a,i.LINK_STATUS)&&this._logProgramError(a,o,h),s.useProgram(a),this._setupBindings(t,a);const d=n.attributes,p=[],m=[];for(let e=0;e<d.length;e++){const t=d[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER)}for(let e=0;e<c.length;e++){const t=c[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER);const s=this.get(t);m.push(s)}this.set(e,{programGPU:a,transformBuffers:m,attributes:p})}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,s=0;for(const i of t){this.set(i,{textures:s,uniformBuffers:e});for(const t of i.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&s++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,s=this.get(e);let i=s.uniformBuffers,r=s.textures;for(const s of e.bindings){const e=this.get(s);if(s.isUniformsGroup||s.isUniformBuffer){const r=s.buffer;let{bufferGPU:n}=this.get(r);void 0===n?(n=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,n),t.bufferData(t.UNIFORM_BUFFER,r.byteLength,t.DYNAMIC_DRAW),this.set(r,{bufferGPU:n})):t.bindBuffer(t.UNIFORM_BUFFER,n);const a=s.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,n),0===a.length)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{const e=dt(r),s=e?1:r.BYTES_PER_ELEMENT;for(let i=0,n=a.length;i<n;i++){const n=a[i],o=n.start*s,h=n.count*s,u=o*(e?r.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,u,r,o,h)}}e.index=i++,e.bufferGPU=n,this.set(s,e)}else if(s.isSampledTexture){const{textureGPU:t,glTextureType:i}=this.get(s.texture);e.index=r++,e.textureGPU=t,e.glTextureType=i,this.set(s,e)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const s=this.get(e).bufferGPU,i=e.buffer,r=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,s),0===r.length)t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW);else{const e=dt(i),s=e?1:i.BYTES_PER_ELEMENT;for(let n=0,a=r.length;n<a;n++){const a=r[n],o=a.start*s,h=a.count*s,u=o*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,u,i,o,h)}}}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(qv).filter(t=>qv[t]===e),s=this.extensions;for(let e=0;e<t.length;e++)if(s.has(t[e]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){this.textureUtils.copyTextureToTexture(e,t,s,i,r,n)}copyFramebufferToTexture(e,t,s){this.textureUtils.copyFramebufferToTexture(e,t,s)}hasCompatibility(e){return e===ct||super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:s}=this;this._setFramebuffer(e),s.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(null!==e.textures){const r=e.renderTarget,n=this.get(r),{samples:a,depthBuffer:o,stencilBuffer:h}=r,u=!0===r.isCubeRenderTarget,l=!0===r.isRenderTarget3D,c=r.depth>1,d=!0===r.isXRRenderTarget,p=!0===d&&!0===r._hasExternalTextures;let m=n.msaaFrameBuffer,g=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(r),_=Vy(e);let x;if(u?(n.cubeFramebuffers||(n.cubeFramebuffers={}),x=n.cubeFramebuffers[_]):d&&!1===p?x=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),x=n.framebuffers[_]),void 0===x){x=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,x);const i=e.textures,o=[];if(u){n.cubeFramebuffers[_]=x;const{textureGPU:e}=this.get(i[0]),s=this.renderer._activeCubeFace,r=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+s,e,r)}else{n.framebuffers[_]=x;for(let s=0;s<i.length;s++){const n=i[s],o=this.get(n);o.renderTarget=e.renderTarget,o.cacheKey=_;const h=t.COLOR_ATTACHMENT0+s;if(r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,h,o.textureGPU,0,a,0,2);else if(l||c){const e=this.renderer._activeCubeFace,s=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,h,o.textureGPU,s,e)}else if(b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,h,t.TEXTURE_2D,o.textureGPU,0,a);else{const e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,h,t.TEXTURE_2D,o.textureGPU,e)}}}const d=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const s=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(s,e,0,b),n.xrDepthRenderbuffer=s,o.push(h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,d,t.RENDERBUFFER,s)}else if(null!==e.depthTexture){o.push(h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const s=this.get(e.depthTexture);if(s.renderTarget=e.renderTarget,s.cacheKey=_,r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,d,s.textureGPU,0,a,0,2);else if(p&&b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,d,t.TEXTURE_2D,s.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,d,s.textureGPU,0,e)}else if(e.depthTexture.isCubeTexture){const e=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_2D,s.textureGPU,0)}n.depthInvalidationArray=o}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,x);const i=this.renderer._activeCubeFace,r=this.get(e.depthTexture),n=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,n,r.textureGPU,0,i)}if((d||b||r.multiview)&&!0!==r._isOpaqueFramebuffer){s.bindFramebuffer(t.FRAMEBUFFER,x);const i=this.get(e.textures[0]);r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,i.textureGPU,0,a,0,2):b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0);const o=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const e=n.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,o,t.RENDERBUFFER,e)}else{const s=this.get(e.depthTexture);r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,s.textureGPU,0,a,0,2):b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,s.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,s.textureGPU,0)}}}if(a>0&&!1===b&&!r.multiview){if(void 0===m){const i=[];m=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,m);const r=[],u=e.textures;for(let s=0;s<u.length;s++){r[s]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,r[s]),i.push(t.COLOR_ATTACHMENT0+s);const n=e.textures[s],o=this.get(n);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,o.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+s,t.RENDERBUFFER,r[s])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),n.msaaFrameBuffer=m,n.msaaRenderbuffers=r,o&&void 0===g){g=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(g,e,a),n.depthRenderbuffer=g;const s=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;i.push(s)}n.invalidationArray=i}i=n.msaaFrameBuffer}else i=x;s.drawBuffers(e,x)}s.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let s=0;s<e.length;s++){t+=":"+this.get(e[s]).id}return t}_createVao(e){const{gl:t}=this,s=t.createVertexArray();t.bindVertexArray(s);for(let s=0;s<e.length;s++){const i=e[s],r=this.get(i);let n,a;t.bindBuffer(t.ARRAY_BUFFER,r.bufferGPU),t.enableVertexAttribArray(s),!0===i.isInterleavedBufferAttribute?(n=i.data.stride*r.bytesPerElement,a=i.offset*r.bytesPerElement):(n=0,a=0),r.isInteger?t.vertexAttribIPointer(s,i.itemSize,r.type,n,a):t.vertexAttribPointer(s,i.itemSize,r.type,i.normalized,n,a),i.isInstancedBufferAttribute&&!i.isInterleavedBufferAttribute?t.vertexAttribDivisor(s,i.meshPerAttribute):i.isInterleavedBufferAttribute&&i.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(s,i.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),s}_getTransformFeedback(e){let t="";for(let s=0;s<e.length;s++)t+=":"+e[s].id;let s=this.transformFeedbackCache[t];if(void 0!==s)return s;const{gl:i}=this;s=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,s);for(let t=0;t<e.length;t++){const s=e[t];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,t,s.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=s,s}_setupBindings(e,t){const s=this.gl;for(const i of e)for(const e of i.bindings){const i=this.get(e).index;if(e.isUniformsGroup||e.isUniformBuffer){const r=s.getUniformBlockIndex(t,e.name);s.uniformBlockBinding(t,r,i)}else if(e.isSampledTexture){const r=s.getUniformLocation(t,e.name);s.uniform1i(r,i)}}}_bindUniforms(e){const{gl:t,state:s}=this;for(const i of e)for(const e of i.bindings){const i=this.get(e),r=i.index;e.isUniformsGroup||e.isUniformBuffer?s.bindBufferBase(t.UNIFORM_BUFFER,r,i.bufferGPU):e.isSampledTexture&&s.bindTexture(i.glTextureType,i.textureGPU,t.TEXTURE0+r)}}_resolveRenderTarget(e){const{gl:t,state:s}=this,i=e.renderTarget;if(null!==e.textures&&i){const r=this.get(i);if(i.samples>0&&!1===this._useMultisampledExtension(i)){const n=r.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=r.msaaFrameBuffer,h=r.msaaRenderbuffers,u=e.textures,l=u.length>1;if(s.bindFramebuffer(t.READ_FRAMEBUFFER,o),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),l)for(let e=0;e<u.length;e++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);for(let s=0;s<u.length;s++){if(l){const{textureGPU:e}=this.get(u[s]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,h[s]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:s,y:i,width:r,height:n}=e.scissorValue,o=e.height-n-i;t.blitFramebuffer(s,o,s+r,o+n,s,o,s+r,o+n,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,t.NEAREST)}if(l)for(let e=0;e<u.length;e++){const{textureGPU:s}=this.get(u[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,h[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,s,0)}!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,r.invalidationArray)}else if(!1===i.resolveDepthBuffer&&r.framebuffers){const i=r.framebuffers[e.getCacheKey()];s.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,r.depthInvalidationArray)}}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const Zv="point-list",Jv="line-list",eT="line-strip",tT="triangle-list",sT="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},iT="never",rT="less",nT="equal",aT="less-equal",oT="greater",hT="not-equal",uT="greater-equal",lT="always",cT="store",dT="load",pT="clear",mT="ccw",gT="cw",fT="none",yT="back",bT="uint16",_T="uint32",xT="r8unorm",vT="r8snorm",TT="r8uint",ST="r8sint",wT="r16uint",MT="r16sint",NT="r16float",ET="rg8unorm",AT="rg8snorm",CT="rg8uint",RT="rg8sint",PT="r32uint",BT="r32sint",FT="r32float",DT="rg16uint",IT="rg16sint",LT="rg16float",OT="rgba8unorm",UT="rgba8unorm-srgb",kT="rgba8snorm",zT="rgba8uint",VT="rgba8sint",GT="bgra8unorm",jT="bgra8unorm-srgb",$T="rgb9e5ufloat",WT="rgb10a2unorm",HT="rg11b10ufloat",qT="rg32uint",XT="rg32sint",YT="rg32float",KT="rgba16uint",QT="rgba16sint",ZT="rgba16float",JT="rgba32uint",eS="rgba32sint",tS="rgba32float",sS="depth16unorm",iS="depth24plus",rS="depth24plus-stencil8",nS="depth32float",aS="depth32float-stencil8",oS="bc1-rgba-unorm",hS="bc1-rgba-unorm-srgb",uS="bc2-rgba-unorm",lS="bc2-rgba-unorm-srgb",cS="bc3-rgba-unorm",dS="bc3-rgba-unorm-srgb",pS="bc4-r-unorm",mS="bc4-r-snorm",gS="bc5-rg-unorm",fS="bc5-rg-snorm",yS="bc6h-rgb-ufloat",bS="bc6h-rgb-float",_S="bc7-rgba-unorm",xS="bc7-rgba-unorm-srgb",vS="etc2-rgb8unorm",TS="etc2-rgb8unorm-srgb",SS="etc2-rgb8a1unorm",wS="etc2-rgb8a1unorm-srgb",MS="etc2-rgba8unorm",NS="etc2-rgba8unorm-srgb",ES="eac-r11unorm",AS="eac-r11snorm",CS="eac-rg11unorm",RS="eac-rg11snorm",PS="astc-4x4-unorm",BS="astc-4x4-unorm-srgb",FS="astc-5x4-unorm",DS="astc-5x4-unorm-srgb",IS="astc-5x5-unorm",LS="astc-5x5-unorm-srgb",OS="astc-6x5-unorm",US="astc-6x5-unorm-srgb",kS="astc-6x6-unorm",zS="astc-6x6-unorm-srgb",VS="astc-8x5-unorm",GS="astc-8x5-unorm-srgb",jS="astc-8x6-unorm",$S="astc-8x6-unorm-srgb",WS="astc-8x8-unorm",HS="astc-8x8-unorm-srgb",qS="astc-10x5-unorm",XS="astc-10x5-unorm-srgb",YS="astc-10x6-unorm",KS="astc-10x6-unorm-srgb",QS="astc-10x8-unorm",ZS="astc-10x8-unorm-srgb",JS="astc-10x10-unorm",ew="astc-10x10-unorm-srgb",tw="astc-12x10-unorm",sw="astc-12x10-unorm-srgb",iw="astc-12x12-unorm",rw="astc-12x12-unorm-srgb",nw="clamp-to-edge",aw="repeat",ow="mirror-repeat",hw="linear",uw="nearest",lw="zero",cw="one",dw="src",pw="one-minus-src",mw="src-alpha",gw="one-minus-src-alpha",fw="dst",yw="one-minus-dst",bw="dst-alpha",_w="one-minus-dst-alpha",xw="src-alpha-saturated",vw="constant",Tw="one-minus-constant",Sw="add",ww="subtract",Mw="reverse-subtract",Nw="min",Ew="max",Aw=0,Cw=15,Rw="keep",Pw="zero",Bw="replace",Fw="invert",Dw="increment-clamp",Iw="decrement-clamp",Lw="increment-wrap",Ow="decrement-wrap",Uw="storage",kw="read-only-storage",zw="write-only",Vw="read-only",Gw="read-write",jw="non-filtering",$w="comparison",Ww="float",Hw="unfilterable-float",qw="depth",Xw="sint",Yw="uint",Kw="2d",Qw="3d",Zw="2d",Jw="2d-array",eM="cube",tM="3d",sM="all",iM="vertex",rM="instance",nM={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},aM={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class oM extends gv{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class hM extends hv{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let uM=0;class lM extends hM{constructor(e,t){super("StorageBuffer_"+uM++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Hn,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class cM extends my{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:hw}),this.flipYSampler=e.createSampler({minFilter:uw}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar<uniform> flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d<f32>;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array<f32>;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube<f32>;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n"})}getTransferPipeline(e,t){const s=`${e}-${t=t||"2d-array"}`;let i=this.transferPipelines[s];return void 0===i&&(i=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[s]=i),i}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,a=this.device.createTexture({size:{width:r,height:n},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),o=this.getTransferPipeline(i,e.textureBindingViewDimension),h=this.getTransferPipeline(i,a.textureBindingViewDimension),u=this.device.createCommandEncoder({}),l=(e,t,s,i,r,n)=>{const a=e.getBindGroupLayout(0),o=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t.createView({dimension:t.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:n?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),h=u.beginRenderPass({colorAttachments:[{view:i.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:r,arrayLayerCount:1}),loadOp:pT,storeOp:cT}]});h.setPipeline(e),h.setBindGroup(0,o),h.draw(3,1,0,s),h.end()};l(o,e,s,a,0,!1),l(h,a,0,e,s,!0),this.device.queue.submit([u.finish()]),a.destroy()}generateMipmaps(e,t=null){const s=this.get(e),i=s.layers||this._mipmapCreateBundles(e),r=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(r,i),null===t&&this.device.queue.submit([r.finish()]),s.layers=i}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",s=this.getTransferPipeline(e.format,t),i=s.getBindGroupLayout(0),r=[];for(let n=1;n<e.mipLevelCount;n++)for(let a=0;a<e.depthOrArrayLayers;a++){const o=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:e.createView({dimension:t,baseMipLevel:n-1,mipLevelCount:1})},{binding:2,resource:{buffer:this.noFlipUniformBuffer}}]}),h={colorAttachments:[{view:e.createView({dimension:"2d",baseMipLevel:n,mipLevelCount:1,baseArrayLayer:a,arrayLayerCount:1}),loadOp:pT,storeOp:cT}]},u=this.device.createRenderBundleEncoder({colorFormats:[e.format]});u.setPipeline(s),u.setBindGroup(0,o),u.draw(3,1,0,a),r.push({renderBundles:[u.finish()],passDescriptor:h})}return r}_mipmapRunBundles(e,t){const s=t.length;for(let i=0;i<s;i++){const s=t[i],r=e.beginRenderPass(s.passDescriptor);r.executeBundles(s.renderBundles),r.end()}}}const dM={[Qe]:"never",[Ze]:"less",[Je]:"equal",[et]:"less-equal",[tt]:"greater",[it]:"greater-equal",[rt]:"always",[st]:"not-equal"},pM=[0,1,3,2,4,5];class mM{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,s=e.minFilter+"-"+e.magFilter+"-"+e.wrapS+"-"+e.wrapT+"-"+(e.wrapR||"0")+"-"+e.anisotropy+"-"+(e.compareFunction||0);let i=this._samplerCache.get(s);if(void 0===i){const r={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};e.isDepthTexture&&null===e.compareFunction&&(r.magFilter=uw,r.minFilter=uw,r.mipmapFilter=uw),r.magFilter===hw&&r.minFilter===hw&&r.mipmapFilter===hw&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&t.hasCompatibility(ct)&&(r.compare=dM[e.compareFunction]);i={sampler:t.device.createSampler(r),usedTimes:0},this._samplerCache.set(s,i)}const r=t.get(e);if(r.sampler!==i.sampler){if(void 0!==r.sampler){const e=this._samplerCache.get(r.samplerKey);e.usedTimes--,0===e.usedTimes&&this._samplerCache.delete(r.samplerKey)}r.samplerKey=s,r.sampler=i.sampler,i.usedTimes++}return s}createDefaultTexture(e){let t;const s=gM(e);t=e.isCubeTexture?this._getDefaultCubeTextureGPU(s):this._getDefaultTextureGPU(s),this.backend.get(e).texture=t}createTexture(e,t={}){const s=this.backend,i=s.get(e);if(i.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");if(e.isExternalTexture)return i.texture=e.sourceTexture,void(i.initialized=!0);void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:r,height:n,depth:a,levels:o}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const h=this._getDimension(e),u=e.internalFormat||t.format||gM(e,s.device);i.format=u;const{samples:l,primarySamples:c,isMSAA:d}=s.utils.getTextureSampleData(e);let p=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(p|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&u!==$T&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:r,height:n,depthOrArrayLayers:a},mipLevelCount:o,sampleCount:c,dimension:h,format:u,usage:p};if(void 0===u)return yt("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(m.textureBindingViewDimension=eM);try{i.texture=s.device.createTexture(m)}catch(t){return yt("WebGPURenderer: Failed to create texture with descriptor:",m),void this.createDefaultTexture(e)}if(d){const e=Object.assign({},m);e.label=e.label+"-msaa",e.sampleCount=l,e.mipLevelCount=1,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e,t=!1){const s=this.backend,i=s.get(e);void 0!==i.texture&&!1===t&&i.texture.destroy(),void 0!==i.msaaTexture&&i.msaaTexture.destroy(),s.delete(e)}generateMipmaps(e,t=null){const s=this.backend.get(e);this._generateMipmaps(s.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:s,height:i}=e.getDrawingBufferSize(),r=e.renderer.currentSamples,n=t.colorTexture,a=e.get(n);if(n.width===s&&n.height===i&&n.samples===r)return a.texture;let o=a.texture;return o&&o.destroy(),o=e.device.createTexture({label:"colorBuffer",size:{width:s,height:i,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.currentSamples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),n.source.width=s,n.source.height=i,n.samples=r,a.texture=o,o}getDepthBuffer(e=!0,t=!1){const s=this.backend,i=s.renderer.getCanvasTarget(),{width:r,height:n}=s.getDrawingBufferSize(),a=s.renderer.currentSamples,o=i.depthTexture;if(o.width===r&&o.height===n&&o.samples===a&&o.depth===e&&o.stencil===t)return s.get(o).texture;const h=s.get(o).texture;let u,l;if(t?(u=ne,l=J):e&&(u=re,l=X),void 0!==h){if(o.image.width===r&&o.image.height===n&&o.format===u&&o.type===l&&o.samples===a)return h;this.destroyTexture(o)}return o.name="depthBuffer",o.format=u,o.type=l,o.image.width=r,o.image.height=n,o.samples=a,this.createTexture(o,{width:r,height:n}),s.get(o).texture}updateTexture(e,t){const s=this.backend.get(e),i=e.mipmaps,{textureDescriptorGPU:r}=s;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture)if(i.length>0)for(let t=0,n=i.length;t<n;t++){const n=i[t];this._copyBufferToTexture(n,s.texture,r,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,s.texture,r,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let i=0;i<t.image.depth;i++)this._copyBufferToTexture(t.image,s.texture,r,i,e.flipY,i);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,s.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,s.texture,r);else if(i.length>0)for(let t=0,n=i.length;t<n;t++){const n=i[t];this._copyImageToTexture(n,s.texture,r,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,s.texture,r,0,e.flipY,e.premultiplyAlpha);s.version=e.version}}async copyTextureToBuffer(e,t,s,i,r,n){const a=this.backend.device,o=this.backend.get(e),h=o.texture,u=o.textureDescriptorGPU.format,l=this._getBytesPerTexel(u);let c=i*l;c=256*Math.ceil(c/256);const d=a.createBuffer({size:(r-1)*c+i*l,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=a.createCommandEncoder();p.copyTextureToBuffer({texture:h,origin:{x:t,y:s,z:n}},{buffer:d,bytesPerRow:c},{width:i,height:r});const m=this._getTypedArrayType(u);a.queue.submit([p.finish()]),await d.mapAsync(GPUMapMode.READ);return new m(d.getMappedRange())}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const s=new Jt;s.minFilter=O,s.magFilter=O,this.createTexture(s,{width:1,height:1,format:e}),this.defaultTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const s=new Rr;s.minFilter=O,s.magFilter=O,this.createTexture(s,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=s}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,s){const i=e.images,r=e.mipmaps;for(let n=0;n<6;n++){const a=i[n],o=!0===e.flipY?pM[n]:n;a.isDataTexture?this._copyBufferToTexture(a.image,t,s,o,e.flipY):this._copyImageToTexture(a,t,s,o,e.flipY,e.premultiplyAlpha);for(let i=0;i<r.length;i++){const a=r[i].images[n];a.isDataTexture?this._copyBufferToTexture(a.image,t,s,o,e.flipY,0,i+1):this._copyImageToTexture(a,t,s,o,e.flipY,e.premultiplyAlpha,i+1)}}}_copyImageToTexture(e,t,s,i,r,n,a=0){const o=this.backend.device,h=a>0?e.width:s.size.width,u=a>0?e.height:s.size.height;try{o.queue.copyExternalImageToTexture({source:e,flipY:r},{texture:t,mipLevel:a,origin:{x:0,y:0,z:i},premultipliedAlpha:n},{width:h,height:u,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new cM(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,r,n=0,a=0){const o=this.backend.device,h=e.data,u=this._getBytesPerTexel(s.format),l=e.width*u;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:i}},h,{offset:e.width*e.height*u*n,bytesPerRow:l},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===r&&this._flipY(t,s,i)}_copyCompressedBufferToTexture(e,t,s){const i=this.backend.device,r=this._getBlockData(s.format),n=s.size.depthOrArrayLayers>1;for(let a=0;a<e.length;a++){const o=e[a],h=o.width,u=o.height,l=n?s.size.depthOrArrayLayers:1,c=Math.ceil(h/r.width)*r.byteLength,d=c*Math.ceil(u/r.height);for(let e=0;e<l;e++)i.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:e}},o.data,{offset:e*d,bytesPerRow:c,rowsPerImage:Math.ceil(u/r.height)},{width:Math.ceil(h/r.width)*r.width,height:Math.ceil(u/r.height)*r.height,depthOrArrayLayers:1})}}_getBlockData(e){return e===oS||e===hS?{byteLength:8,width:4,height:4}:e===uS||e===lS||e===cS||e===dS?{byteLength:16,width:4,height:4}:e===pS||e===mS?{byteLength:8,width:4,height:4}:e===gS||e===fS||e===yS||e===bS||e===_S||e===xS?{byteLength:16,width:4,height:4}:e===vS||e===TS||e===SS||e===wS?{byteLength:8,width:4,height:4}:e===MS||e===NS?{byteLength:16,width:4,height:4}:e===ES||e===AS?{byteLength:8,width:4,height:4}:e===CS||e===RS||e===PS||e===BS?{byteLength:16,width:4,height:4}:e===FS||e===DS?{byteLength:16,width:5,height:4}:e===IS||e===LS?{byteLength:16,width:5,height:5}:e===OS||e===US?{byteLength:16,width:6,height:5}:e===kS||e===zS?{byteLength:16,width:6,height:6}:e===VS||e===GS?{byteLength:16,width:8,height:5}:e===jS||e===$S?{byteLength:16,width:8,height:6}:e===WS||e===HS?{byteLength:16,width:8,height:8}:e===qS||e===XS?{byteLength:16,width:10,height:5}:e===YS||e===KS?{byteLength:16,width:10,height:6}:e===QS||e===ZS?{byteLength:16,width:10,height:8}:e===JS||e===ew?{byteLength:16,width:10,height:10}:e===tw||e===sw?{byteLength:16,width:12,height:10}:e===iw||e===rw?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=nw;return e===D?t=aw:e===L&&(t=ow),t}_convertFilterMode(e){let t=hw;return e!==O&&1004!==e&&e!==k||(t=uw),t}_getBytesPerTexel(e){return e===xT||e===vT||e===TT||e===ST?1:e===wT||e===MT||e===NT||e===ET||e===AT||e===CT||e===RT?2:e===PT||e===BT||e===FT||e===DT||e===IT||e===LT||e===OT||e===UT||e===kT||e===zT||e===VT||e===GT||e===jT||e===$T||e===WT||e===HT||e===nS||e===iS||e===rS||e===aS?4:e===qT||e===XT||e===YT||e===KT||e===QT||e===ZT?8:e===JT||e===eS||e===tS?16:void 0}_getTypedArrayType(e){return e===TT?Uint8Array:e===ST?Int8Array:e===xT?Uint8Array:e===vT?Int8Array:e===CT?Uint8Array:e===RT?Int8Array:e===ET?Uint8Array:e===AT?Int8Array:e===zT?Uint8Array:e===VT?Int8Array:e===OT||e===UT?Uint8Array:e===kT?Int8Array:e===wT?Uint16Array:e===MT?Int16Array:e===DT?Uint16Array:e===IT?Int16Array:e===KT?Uint16Array:e===QT?Int16Array:e===NT||e===LT||e===ZT?Uint16Array:e===PT?Uint32Array:e===BT?Int32Array:e===FT?Float32Array:e===qT?Uint32Array:e===XT?Int32Array:e===YT?Float32Array:e===JT?Uint32Array:e===eS?Int32Array:e===tS?Float32Array:e===GT||e===jT?Uint8Array:e===WT||e===$T||e===HT?Uint32Array:e===nS?Float32Array:e===iS||e===rS?Uint32Array:e===aS?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?Qw:Kw,t}}function gM(e,t=null){const s=e.format,i=e.type,r=e.colorSpace,n=jt.getTransfer(r);let a;if(!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(s){case ce:case de:a=n===Ye?hS:oS;break;case pe:a=n===Ye?lS:uS;break;case me:a=n===Ye?dS:cS;break;case Ve:a=pS;break;case Ge:a=mS;break;case je:a=gS;break;case $e:a=fS;break;case ze:a=n===Ye?xS:_S;break;case xe:case _e:a=n===Ye?TS:vS;break;case ve:a=n===Ye?NS:MS;break;case Te:a=ES;break;case Se:a=AS;break;case we:a=CS;break;case Me:a=RS;break;case Ne:a=n===Ye?BS:PS;break;case Ee:a=n===Ye?DS:FS;break;case Ae:a=n===Ye?LS:IS;break;case Ce:a=n===Ye?US:OS;break;case Re:a=n===Ye?zS:kS;break;case Pe:a=n===Ye?GS:VS;break;case Be:a=n===Ye?$S:jS;break;case Fe:a=n===Ye?HS:WS;break;case De:a=n===Ye?XS:qS;break;case Ie:a=n===Ye?KS:YS;break;case Le:a=n===Ye?ZS:QS;break;case Oe:a=n===Ye?ew:JS;break;case Ue:a=n===Ye?sw:tw;break;case ke:a=n===Ye?rw:iw;break;case ie:a=n===Ye?UT:OT;break;default:bt("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case ie:switch(i){case $:a=kT;break;case W:a=QT;break;case H:a=KT;break;case X:a=JT;break;case q:a=eS;break;case j:a=n===Ye?UT:OT;break;case K:a=ZT;break;case Y:a=tS;break;default:bt("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case se:switch(i){case ee:a=$T;break;case te:a=HT;break;default:bt("WebGPURenderer: Unsupported texture type with RGBFormat.",i)}break;case ae:switch(i){case $:a=vT;break;case W:a=MT;break;case H:a=wT;break;case X:a=PT;break;case q:a=BT;break;case j:a=xT;break;case K:a=NT;break;case Y:a=FT;break;default:bt("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case he:switch(i){case $:a=AT;break;case W:a=IT;break;case H:a=DT;break;case X:a=qT;break;case q:a=XT;break;case j:a=ET;break;case K:a=LT;break;case Y:a=YT;break;default:bt("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case re:switch(i){case H:a=sS;break;case X:a=iS;break;case Y:a=nS;break;default:bt("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case ne:switch(i){case J:a=rS;break;case Y:t&&!1===t.features.has(nM.Depth32FloatStencil8)&&bt('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),a=aS;break;default:bt("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case oe:switch(i){case q:a=BT;break;case X:a=PT;break;default:bt("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case ue:switch(i){case q:a=XT;break;case X:a=qT;break;default:bt("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case le:switch(i){case q:a=eS;break;case X:a=JT;break;default:bt("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:bt("WebGPURenderer: Unsupported texture format.",s)}return a}const fM=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,yM=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,bM={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class _M extends Tx{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(fM);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=yM.exec(s));)i.push({name:r[1],type:r[2]});const n=[];for(let e=0;e<i.length;e++){const{name:t,type:s}=i[e];let r=s;r.startsWith("ptr")?r="pointer":(r.startsWith("texture")&&(r=s.split("<")[0]),r=bM[r]),n.push(new hx(r,t))}const a=e.substring(t[0].length),o=t[3]||"void",h=void 0!==t[1]?t[1]:"";return{type:bM[o]||o,inputs:n,name:h,inputsCode:s,blockCode:a,outputType:o}}throw new Error("FunctionNode: Function is not a WGSL code.")})(e);super(t,s,i),this.inputsCode=r,this.blockCode=n,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class xM extends vx{parseFunction(e){return new _M(e)}}const vM={[$n]:"read",[Wn]:"write",[Hn]:"read_write"},TM={[D]:"repeat",[I]:"clamp",[L]:"mirror"},SM={vertex:sT.VERTEX,fragment:sT.FRAGMENT,compute:sT.COMPUTE},wM={instance:!0,swizzleAssign:!1,storageBuffer:!0},MM={"^^":"tsl_xor"},NM={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},EM={},AM={tsl_xor:new Cb("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Cb("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Cb("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Cb("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Cb("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Cb("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Cb("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Cb("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new Cb("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new Cb("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Cb("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new Cb("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Cb("\nfn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new Cb("\nfn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},CM={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let RM="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(RM+="diagnostic( off, derivative_uniformity );\n");class PM extends ax{constructor(e,t){super(e,t,new xM),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map}_generateTextureSample(e,t,s,i,r,n=this.shaderStage){return"fragment"===n?i?r?`textureSample( ${t}, ${t}_sampler, ${s}, ${i}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:r?`textureSample( ${t}, ${t}_sampler, ${s}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.generateTextureSampleLevel(e,t,s,"0",i)}generateTextureSampleLevel(e,t,s,i,r,n){return!1===this.isUnfilterable(e)?r?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i,r):this.generateTextureLod(e,t,s,r,n,i)}generateWrapFunction(e){const t=`tsl_coord_${TM[e.wrapS]}S_${TM[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let s=EM[t];if(void 0===s){const i=[],r=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const a=(e,t)=>{e===D?(i.push(AM.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===I?(i.push(AM.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===L?(i.push(AM.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,yt(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",EM[t]=s=new Cb(n,i)}return s.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,s){const i=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[s];if(void 0===i.dimensionsSnippet[s]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),h=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3<u32>":"vec2<u32>",n=h||e.isStorageTexture?t:`${t}${s?`, u32( ${s} )`:""}`,r=new Hu(new wl(`textureDimensions( ${n} )`,a)),i.dimensionsSnippet[s]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new Hu(new wl(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new Hu(new wl("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,s,i,r="0u",n){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r);return i&&(s=`${s} + vec2<f32>(${i}) / ${o}`),n?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${s} ), ${o}, u32( ${n} ), u32( ${r} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${s} ), ${o}, u32( ${r} ) )`)}generateTextureLod(e,t,s,i,r,n="0u"){if(!0===e.isCubeTexture){r&&(s=`${s} + vec3<f32>(${r})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${e.isDepthTexture?"u32":"f32"}( ${n} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),h=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";r&&(s=`${s} + ${h}<f32>(${r}) / ${h}<f32>( ${o} )`);return s=`${h}<u32>( clamp( floor( ${a}( ${s} ) * ${h}<f32>( ${o} ) ), ${`${h}<f32>( 0 )`}, ${`${h}<f32>( ${o} - ${"vec3"===h?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,s,n,i,null)}generateStorageTextureLoad(e,t,s,i,r,n){let a;return n&&(s=`${s} + ${n}`),a=r?`textureLoad( ${t}, ${s}, ${r} )`:`textureLoad( ${t}, ${s} )`,a}generateTextureLoad(e,t,s,i,r,n){let a;return null===i&&(i="0u"),n&&(s=`${s} + ${n}`),r?a=`textureLoad( ${t}, ${s}, ${r}, u32( ${i} ) )`:(a=`textureLoad( ${t}, ${s}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,s,i,r){let n;return n=i?`textureStore( ${t}, ${s}, ${i}, ${r} )`:`textureStore( ${t}, ${s}, ${r} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(ct)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===Y||!1===this.isSampleCompare(e)&&e.minFilter===O&&e.magFilter===O||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,s,i,r,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,s,i,r,"0",n):this._generateTextureSample(e,t,s,i,r,n),a}generateTextureGrad(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return r?n?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${r}, ${i[0]}, ${i[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${r}, ${i[0]}, ${i[1]} )`:n?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;bt(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?n?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;bt(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,s,i,r,n){return!1===this.isUnfilterable(e)?r?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i,r):this.generateTextureLod(e,t,s,r,n,i)}generateTextureBias(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return r?n?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;bt(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,s=e.type;return"texture"===s||"cubeTexture"===s||"cubeDepthTexture"===s||"storageTexture"===s||"texture3D"===s?t:"buffer"===s||"storageBuffer"===s||"indirectStorageBuffer"===s?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=MM[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(yt("WebGPURenderer: Atomic operations are only supported in compute shaders."),Hn):$n:e.access}getStorageAccess(e,t){return vM[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);if(void 0===n.uniformGPU){let a;const o=e.groupNode,h=o.name,u=this.getBindGroupArray(h,s);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const n=this.getNodeAccess(e,s);"texture"===t||"storageTexture"===t?i=!0===e.value.is3DTexture?new xv(r.name,r.node,o,n):new bv(r.name,r.node,o,n):"cubeTexture"===t||"cubeDepthTexture"===t?i=new _v(r.name,r.node,o,n):"texture3D"===t&&(i=new xv(r.name,r.node,o,n)),i.store=!0===e.isStorageTextureNode,i.mipLevel=i.store?e.mipLevel:0,i.setVisibility(SM[s]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===i.store){const e=new oM(`${r.name}_sampler`,r.node,o);e.setVisibility(SM[s]),u.push(e,i),a=[e,i]}else u.push(i),a=[i]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=this.getSharedDataFromNode(e);let h=n.buffer;if(void 0===h){h=new("buffer"===t?cv:lM)(e,o),n.buffer=h}h.setVisibility(h.getVisibility()|SM[s]),u.push(h),a=h,r.name=i||"NodeBuffer_"+r.id}else{let e=this.uniformGroups[h];void 0===e&&(e=new mv(h,o),e.setVisibility(sT.VERTEX|sT.FRAGMENT|sT.COMPUTE),this.uniformGroups[h]=e),-1===u.indexOf(e)&&u.push(e),a=this.getNodeUniform(r,t);const s=a.name,i=e.uniforms.some(e=>e.name===s);i||e.addUniform(a)}n.uniformGPU=a}return r}getBuiltin(e,t,s,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:s}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${s.vars}\n${s.code}\n`;return s.result&&(r+=`\treturn ${s.result};\n`),r+="\n}\n",r}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],s=this.directives[e];if(void 0!==s)for(const e of s)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){const t=[],s=this.builtins[e];if(void 0!==s)for(const{name:e,property:i,type:r}of s.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,s,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:s,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:s,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const n=this.getType(i);t.push(`var<${s}> ${e}: array< ${n}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const s=this.getAttributesArray();for(let e=0,i=s.length;e<i;e++){const i=s[e],r=i.name,n=this.getType(i.type);t.push(`@location( ${e} ) ${r} : ${n}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const s of e.members){const i=e.output?"@location( "+s.index+" ) ":"";let r=this.getType(s.type);s.atomic&&(r="atomic< "+r+" >"),t.push(`\t${i+s.name} : ${r}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const s=this.structs[e];if(s.length>0){const e=[];for(const t of s){let s=`struct ${t.name} {\n`;s+=this.getStructMembers(t),s+="\n};",e.push(s)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,s=null){let i=`var ${t} : `;return i+=null!==s?this.generateArrayDeclaration(e,s):this.getType(e),i}getVars(e){const t=[],s=this.vars[e];if(void 0!==s)for(const e of s)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,i=this.vars[e];for(let r=0;r<s.length;r++){const n=s[r];if(n.needsInterpolation){let e=`@location( ${r} )`;if(n.interpolationType){const t=null!==n.interpolationSampling?`, ${n.interpolationSampling} )`:" )";e+=` @interpolate( ${n.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(n.type)&&(e+=" @interpolate(flat, either)");t.push(`${e} ${n.name} : ${this.getType(n.type)}`)}else"vertex"===e&&!1===i.includes(n)&&i.push(n)}}const s=this.getBuiltins(e);s&&t.push(s);const i=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+i):i}isCustomStruct(e){const t=e.value,s=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&null!==s.structTypeNode,r=s.value&&s.value.array&&"number"==typeof s.value.itemSize&&s.value.array.length>s.value.itemSize;return i&&!r}getUniforms(e){const t=this.uniforms[e],s=[],i=[],r=[],n={};for(const r of t){const t=r.groupNode.name,a=this.bindingsIndexes[t];if("texture"===r.type||"cubeTexture"===r.type||"cubeDepthTexture"===r.type||"storageTexture"===r.type||"texture3D"===r.type){const t=r.node.value;let i;(!0===t.isCubeTexture||!1===this.isUnfilterable(t)&&!0!==r.node.isStorageTextureNode)&&(this.isSampleCompare(t)?s.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name}_sampler : sampler_comparison;`):s.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name}_sampler : sampler;`));let n="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(n="_multisampled"),!0===t.isCubeTexture&&!0===t.isDepthTexture)i="texture_depth_cube";else if(!0===t.isCubeTexture)i="texture_cube<f32>";else if(!0===t.isDepthTexture)i=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${n}_2d<f32>`:`texture_depth${n}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===r.node.isStorageTextureNode){const s=gM(t),n=this.getStorageAccess(r.node,e),a=r.node.value.is3DTexture,o=r.node.value.isArrayTexture;i=`texture_storage_${a?"3d":"2d"+(o?"_array":"")}<${s}, ${n}>`}else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array<f32>";else if(!0===t.is3DTexture||!0===t.isData3DTexture)i="texture_3d<f32>";else{i=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}s.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const t=r.node,s=this.getType(t.getNodeType(this)),n=t.bufferCount,o=n>0&&"buffer"===r.type?", "+n:"",h=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(r))i.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${h}> ${r.name} : ${s};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${s}>`:`${s}`}${o} >`;i.push(this._getWGSLStructBinding(r.name,e,h,a.binding++,a.group))}}else{const e=r.groupNode.name;if(void 0===n[e]){const t=this.uniformGroups[e];if(void 0!==t){const s=[];for(const e of t.uniforms){const t=e.getType(),i=this.getType(this.getVectorType(t));s.push(`\t${e.name} : ${i}`)}let i=this.uniformGroupsBindings[e];void 0===i&&(i={index:a.binding++,id:a.group},this.uniformGroupsBindings[e]=i),n[e]={index:i.index,id:i.id,snippets:s}}}}}for(const e in n){const t=n[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...s,...i,...r].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],n=r[r.length-1],a=n.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),h=e.name;if(h&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${h}\n`),i+=`${r.code}\n\t`,e===n&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.builtinClipSpace = ${r.result};`;else if("fragment"===t)if(o)s.returnType=a.getNodeType(this),s.structs+="var<private> output : "+s.returnType+";",i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4<f32>";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar<private> output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,s){return`select( ${s}, ${t}, ${e} )`}getType(e){return NM[e]||e}isAvailable(e){let t=wM[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),wM[e]=t),t}getUniformBufferLimit(){return this.renderer.backend.device.limits.maxUniformBufferBindingSize}_getWGSLMethod(e){return void 0!==AM[e]&&this._include(e),CM[e]}_include(e){const t=AM[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar<private> varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${RM}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[s,i,r]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${s}, ${i}, ${r} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${s} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${s} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y );\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,s,i=0,r=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${s}> ${e} : ${n};`}}class BM{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?rS:iS),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,s=e.getRenderTarget();t=s?s.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const s=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:s?1:t,isMSAA:s}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return null!==e.textures?e.textures.map(e=>this.getTextureFormatGPU(e)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?Zv:e.isLineSegments||e.isMesh&&!0===t.wireframe?Jv:e.isLine?eT:e.isMesh?tT:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===j)return GT;if(e===K)return ZT;throw new Error("Unsupported output buffer type.")}}const FM=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&FM.set(Float16Array,["float16"]);const DM=new Map([[Ni,["float16"]]]),IM=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class LM{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,r=i.get(s);let n=r.buffer;if(void 0===n){const a=i.device;let o=s.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e<o.length;e++)65535===o[e]&&(o[e]=4294967295);if(s.array=o,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&3===s.itemSize){o=new o.constructor(4*s.count);for(let e=0;e<s.count;e++)o.set(s.array.subarray(3*e,3*e+3),4*e);s.itemSize=4,s.array=o,r._force3to4BytesAlignment=!0}const h=o.byteLength,u=h+(4-h%4)%4;n=a.createBuffer({label:s.name,size:u,usage:t,mappedAtCreation:!0}),new o.constructor(n.getMappedRange()).set(o),n.unmap(),r.buffer=n}}updateAttribute(e){const t=this._getBufferAttribute(e),s=this.backend,i=s.device,r=s.get(t),n=s.get(t).buffer;let a=t.array;if(!0===r._force3to4BytesAlignment){a=new a.constructor(4*t.count);for(let e=0;e<t.count;e++)a.set(t.array.subarray(3*e,3*e+3),4*e);t.array=a}const o=t.updateRanges;if(0===o.length)i.queue.writeBuffer(n,0,a,0);else{const e=dt(a),s=e?1:a.BYTES_PER_ELEMENT;for(let t=0,h=o.length;t<h;t++){const h=o[t];let u,l;if(!0===r._force3to4BytesAlignment){u=4*Math.floor(h.start/3)*s,l=4*Math.ceil(h.count/3)*s}else u=h.start*s,l=h.count*s;const c=u*(e?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(n,c,a,u,l)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),s=new Map;for(let e=0;e<t.length;e++){const i=t[e],r=i.array.BYTES_PER_ELEMENT,n=this._getBufferAttribute(i);let a=s.get(n);if(void 0===a){let e,t;!0===i.isInterleavedBufferAttribute?(e=i.data.stride*r,t=i.data.isInstancedInterleavedBuffer?rM:iM):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?rM:iM),!1!==i.normalized||i.array.constructor!==Int16Array&&i.array.constructor!==Uint16Array||(e=4),a={arrayStride:e,attributes:[],stepMode:t},s.set(n,a)}const o=this._getVertexFormat(i),h=!0===i.isInterleavedBufferAttribute?i.offset*r:0;a.attributes.push({shaderLocation:e,offset:h,format:o})}return Array.from(s.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,s=t.device,i=t.get(this._getBufferAttribute(e)).buffer,r=i.size,n=s.createBuffer({label:`${e.name}_readback`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=s.createCommandEncoder({label:`readback_encoder_${e.name}`});a.copyBufferToBuffer(i,0,n,0,r);const o=a.finish();s.queue.submit([o]),await n.mapAsync(GPUMapMode.READ);const h=n.getMappedRange(),u=new e.array.constructor(h.slice(0));return n.unmap(),u.buffer}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,r=e.constructor;let n;if(1===t)n=IM.get(i);else{const e=(DM.get(r)||FM.get(i))[s?1:0];if(e){const s=i.BYTES_PER_ELEMENT*t,r=4*Math.floor((s+3)/4)/i.BYTES_PER_ELEMENT;if(r%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");n=`${e}x${r}`}}return n||bt("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class OM{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class UM{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,s=t.device,i=t.get(e);if(i.layout)return i.layout.layoutGPU;const r=this._createLayoutEntries(e),n=Rn(JSON.stringify(r));let a=this._bindGroupLayoutCache.get(n);return void 0===a&&(a=new OM(s.createBindGroupLayout({entries:r})),this._bindGroupLayoutCache.set(n,a)),a.usedTimes++,i.layout=a,i.layoutKey=n,a.layoutGPU}createBindings(e,t,s,i=0){const{backend:r}=this,n=r.get(e),a=this.createBindingsLayout(e);let o;s>0&&(void 0===n.groups&&(n.groups=[],n.versions=[]),n.versions[s]===i&&(o=n.groups[s])),void 0===o&&(o=this.createBindGroup(e,a),s>0&&(n.groups[s]=o,n.versions[s]=i)),n.group=o}updateBinding(e){const t=this.backend,s=t.device,i=e.buffer,r=t.get(e).buffer,n=e.updateRanges;if(0===n.length)s.queue.writeBuffer(r,0,i,0);else{const e=dt(i),t=e?1:i.BYTES_PER_ELEMENT;for(let a=0,o=n.length;a<o;a++){const o=n[a],h=o.start*t,u=o.count*t,l=h*(e?i.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(r,l,i,h,u)}}}createBindGroupIndex(e,t){const s=this.backend.device,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0],n=s.createBuffer({label:"bindingCameraIndex_"+r,size:16,usage:i});s.queue.writeBuffer(n,0,e,0);const a=[{binding:0,resource:{buffer:n}}];return s.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:a})}createBindGroup(e,t){const s=this.backend,i=s.device;let r=0;const n=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=s.get(t);if(void 0===e.buffer){const s=t.byteLength,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=[];t.visibility&sT.VERTEX&&n.push("vertex"),t.visibility&sT.FRAGMENT&&n.push("fragment"),t.visibility&sT.COMPUTE&&n.push("compute");const a=`(${n.join(",")})`,o=i.createBuffer({label:`bindingBuffer${t.id}_${t.name}_${a}`,size:s,usage:r});e.buffer=o}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=s.get(t.attribute).buffer;n.push({binding:r,resource:{buffer:e}})}else if(t.isSampledTexture){const e=s.get(t.texture);let a;if(void 0!==e.externalTexture)a=i.importExternalTexture({source:e.externalTexture});else{const s=t.store?1:e.texture.mipLevelCount,i=t.store?t.mipLevel:0;let r=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(r+=`-${e.texture.depthOrArrayLayers}`),r+=`-${s}-${i}`,a=e[r],void 0===a){const n=sM;let o;o=t.isSampledCubeTexture?eM:t.isSampledTexture3D?tM:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Jw:Zw,a=e[r]=e.texture.createView({aspect:n,dimension:o,mipLevelCount:s,baseMipLevel:i})}}n.push({binding:r,resource:a})}else if(t.isSampler){const e=s.get(t.texture);n.push({binding:r,resource:e.sampler})}r++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}_createLayoutEntries(e){const t=[];let s=0;for(const i of e.bindings){const e=this.backend,r={binding:s,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){const e={};i.isStorageBuffer&&(i.visibility&sT.COMPUTE&&(i.access===Hn||i.access===Wn)?e.type=Uw:e.type=kw),r.buffer=e}else if(i.isSampledTexture&&i.store){const e={};e.format=this.backend.get(i.texture).texture.format;const t=i.access;e.access=t===Hn?Gw:t===Wn?zw:Vw,i.texture.isArrayTexture?e.viewDimension=Jw:i.texture.is3DTexture&&(e.viewDimension=tM),r.storageTexture=e}else if(i.isSampledTexture){const t={},{primarySamples:s}=e.utils.getTextureSampleData(i.texture);if(s>1&&(t.multisampled=!0,i.texture.isDepthTexture||(t.sampleType=Hw)),i.texture.isDepthTexture)e.compatibilityMode&&null===i.texture.compareFunction?t.sampleType=Hw:t.sampleType=qw;else if(i.texture.isDataTexture||i.texture.isDataArrayTexture||i.texture.isData3DTexture){const e=i.texture.type;e===q?t.sampleType=Xw:e===X?t.sampleType=Yw:e===Y&&(this.backend.hasFeature("float32-filterable")?t.sampleType=Ww:t.sampleType=Hw)}i.isSampledCubeTexture?t.viewDimension=eM:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?t.viewDimension=Jw:i.isSampledTexture3D&&(t.viewDimension=tM),r.texture=t}else if(i.isSampler){const t={};i.texture.isDepthTexture&&(null!==i.texture.compareFunction&&e.hasCompatibility(ct)?t.type=$w:t.type=jw),r.sampler=t}else bt(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(r),s++}return t}deleteBindGroupData(e){const{backend:t}=this,s=t.get(e);s.layout&&(s.layout.usedTimes--,0===s.layout.usedTimes&&this._bindGroupLayoutCache.delete(s.layoutKey),s.layout=void 0,s.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class kM{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:s,material:i,geometry:r,pipeline:n}=e,{vertexProgram:a,fragmentProgram:o}=n,h=this.backend,u=h.device,l=h.utils,c=h.get(n),d=[];for(const t of e.getBindings()){const e=h.get(t),{layoutGPU:s}=e.layout;d.push(s)}const p=h.attributeUtils.createShaderVertexBuffers(e);let m;0===i.blending||1===i.blending&&!1===i.transparent||(m=this._getBlending(i));let g={};!0===i.stencilWrite&&(g={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const f=this._getColorWriteMask(i),y=[];if(null!==e.context.textures){const t=e.context.textures,s=e.context.mrt;for(let e=0;e<t.length;e++){const i=t[e],r=l.getTextureFormatGPU(i);let n;if(null!==s)if(!0!==this.backend.compatibilityMode){const e=s.getBlendMode(i.name);6===e.blending?n=m:0!==e.blending&&(n=this._getBlending(e))}else _t("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),n=m;else n=m;y.push({format:r,blend:n,writeMask:f})}}else{const t=l.getCurrentColorFormat(e.context);y.push({format:t,blend:m,writeMask:f})}const b=h.get(a).module,_=h.get(o).module,x=this._getPrimitiveState(s,r,i),v=this._getDepthCompare(i),T=l.getCurrentDepthStencilFormat(e.context),S=this._getSampleCount(e.context),w={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},b,{buffers:p}),fragment:Object.assign({},_,{targets:y}),primitive:x,multisample:{count:S,alphaToCoverageEnabled:i.alphaToCoverage&&S>1},layout:u.createPipelineLayout({bindGroupLayouts:d})},M={},N=e.context.depth,E=e.context.stencil;if(!0!==N&&!0!==E||(!0===N&&(M.format=T,M.depthWriteEnabled=i.depthWrite,M.depthCompare=v),!0===E&&(M.stencilFront=g,M.stencilBack=g,M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(M.depthBias=i.polygonOffsetUnits,M.depthBiasSlopeScale=i.polygonOffsetFactor,M.depthBiasClamp=0),w.depthStencil=M),u.pushErrorScope("validation"),null===t)c.pipeline=u.createRenderPipeline(w),u.popErrorScope().then(e=>{null!==e&&(c.error=!0,bt(e.message))});else{const e=new Promise(async e=>{try{c.pipeline=await u.createRenderPipelineAsync(w)}catch(e){}const t=await u.popErrorScope();null!==t&&(c.error=!0,bt(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const s=this.backend,{utils:i,device:r}=s,n=i.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:i.getCurrentColorFormats(e),depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return r.createRenderBundleEncoder(a)}createComputePipeline(e,t){const s=this.backend,i=s.device,r=s.get(e.computeProgram).module,n=s.get(e),a=[];for(const e of t){const t=s.get(e),{layoutGPU:i}=t.layout;a.push(i)}n.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,a=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,o=null!==e.blendDstAlpha?e.blendDstAlpha:n,h=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(a)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(h)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:Sw},s={srcFactor:r,dstFactor:n,operation:Sw}};if(e.premultipliedAlpha)switch(i){case 1:r(cw,gw,cw,gw);break;case 2:r(cw,cw,cw,cw);break;case 3:r(lw,pw,lw,cw);break;case 4:r(fw,gw,lw,cw)}else switch(i){case 1:r(mw,gw,cw,gw);break;case 2:r(mw,cw,cw,cw);break;case 3:bt(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case 4:bt(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};bt("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case p:t=lw;break;case 201:t=cw;break;case 202:t=dw;break;case 203:t=pw;break;case y:t=mw;break;case b:t=gw;break;case 208:t=fw;break;case 209:t=yw;break;case 206:t=bw;break;case 207:t=_w;break;case 210:t=xw;break;case 211:t=vw;break;case 212:t=Tw;break;default:bt("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=iT;break;case 519:t=lT;break;case 513:t=rT;break;case 515:t=aT;break;case 514:t=nT;break;case 518:t=uT;break;case 516:t=oT;break;case 517:t=hT;break;default:bt("WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case Ke:t=Rw;break;case 0:t=Pw;break;case 7681:t=Bw;break;case 5386:t=Fw;break;case 7682:t=Dw;break;case 7683:t=Iw;break;case 34055:t=Lw;break;case 34056:t=Ow;break;default:bt("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case l:t=Sw;break;case 101:t=ww;break;case 102:t=Mw;break;case 103:t=Nw;break;case 104:t=Ew;break;default:bt("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},r=this.backend.utils;i.topology=r.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?bT:_T);let n=1===s.side;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),i.frontFace=!0===n?gT:mT,i.cullMode=2===s.side?fT:yT,i}_getColorWriteMask(e){return!0===e.colorWrite?Cw:Aw}_getDepthCompare(e){let t;if(!1===e.depthTest)t=lT;else{const s=this.backend.parameters.reversedDepthBuffer?xt[e.depthFunc]:e.depthFunc;switch(s){case 0:t=iT;break;case 1:t=lT;break;case 2:t=rT;break;case 3:t=aT;break;case 4:t=nT;break;case 5:t=uT;break;case 6:t=oT;break;case 7:t=hT;break;default:bt("WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class zM extends Yv{constructor(e,t,s=2048){super(s),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return _t(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,s=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,s);const r=i.finish();if(this.device.queue.submit([r]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,s),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,s)),a={},o=[];for(const[t,s]of e){const e=t.match(/^(.*):f(\d+)$/),i=parseInt(e[2]);!1===o.includes(i)&&o.push(i),void 0===a[i]&&(a[i]=0);const r=n[s],h=n[s+1],u=Number(h-r)/1e6;this.timestamps.set(t,u),a[i]+=u}const h=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=h,this.frames=o,h}catch(e){return bt("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){bt("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){bt("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class VM extends Pv{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new BM(this),this.attributeUtils=new LM(this),this.bindingUtils=new UM(this),this.pipelineUtils=new kM(this),this.textureUtils=new mM(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[ct]:t}}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:"compatibility"},i="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(nM),n=[];for(const e of r)i.features.has(e)&&n.push(e);const a={requiredFeatures:n,requiredLimits:t.requiredLimits};s=await i.requestDevice(a)}else s=t.device;this.compatibilityMode=!s.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),s.lost.then(t=>{if("destroyed"===t.reason)return;const s={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(s)}),this.device=s,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(nM.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let s=t.context;if(void 0===s){const i=this.parameters;s=!0===e.isDefaultCanvasTarget&&void 0!==i.context?i.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${a} webgpu`);const r=i.alpha?"premultiplied":"opaque",n=i.outputType===K?"extended":"standard";s.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r,toneMapping:{mode:n}}),t.context=s}return s}get coordinateSystem(){return ht}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),s=this.get(t),i=e.currentSamples;let r=s.descriptor;if(void 0===r||s.samples!==i){r={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(r.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=r.colorAttachments[0];i>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,s.descriptor=r,s.samples=i}const n=r.colorAttachments[0];return i>0?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),r}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const s=e.renderTarget,i=this.get(s);let r=i.descriptors;void 0!==r&&i.width===s.width&&i.height===s.height&&i.samples===s.samples||(r={},i.descriptors=r);const n=e.getCacheKey();let a=r[n];if(void 0===a){const t=e.textures,o=[];let h;const u=this._isRenderCameraDepthArray(e);for(let i=0;i<t.length;i++){const r=this.get(t[i]),n={label:`colorAttachment_${i}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:Zw};if(s.isRenderTarget3D)h=e.activeCubeFace,n.baseArrayLayer=0,n.dimension=tM,n.depthOrArrayLayers=t[i].image.depth;else if(s.isRenderTarget&&t[i].image.depth>1)if(!0===u){const t=e.camera.cameras;for(let e=0;e<t.length;e++){const t={...n,baseArrayLayer:e,arrayLayerCount:1,dimension:Zw},s=r.texture.createView(t);o.push({view:s,resolveTarget:void 0,depthSlice:void 0})}}else n.dimension=Jw,n.depthOrArrayLayers=t[i].image.depth;if(!0!==u){const e=r.texture.createView(n);let t,s;void 0!==r.msaaTexture?(t=r.msaaTexture.createView(),s=e):(t=e,s=void 0),o.push({view:t,resolveTarget:s,depthSlice:h})}}if(a={textureViews:o},e.depth){const t=this.get(e.depthTexture),s={};(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(s.dimension=Zw,s.arrayLayerCount=1,s.baseArrayLayer=e.activeCubeFace),a.depthStencilView=t.texture.createView(s)}r[n]=a,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const o={colorAttachments:[]};for(let e=0;e<a.textureViews.length;e++){const s=a.textureViews[e];let i={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(i=t.clearValue),o.colorAttachments.push({view:s.view,depthSlice:s.depthSlice,resolveTarget:s.resolveTarget,loadOp:t.loadOp||dT,storeOp:t.storeOp||cT,clearValue:i})}return a.depthStencilView&&(o.depthStencilAttachment={view:a.depthStencilView}),o}beginRender(e){const t=this.get(e),s=this.device,i=e.occlusionQueryCount;let r,n;i>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=s.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:dT}),this.initTimestampQuery(lt,this.getTimestampUID(e),n),n.occlusionQuerySet=r;const a=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let s=0;s<t.length;s++){const i=t[s];e.clearColor?(i.clearValue=0===s?e.clearColorValue:{r:0,g:0,b:0,a:1},i.loadOp=pT):i.loadOp=dT,i.storeOp=cT}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=pT):t.loadOp=dT,t.storeOp=cT}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=pT):a.depthLoadOp=dT,a.depthStoreOp=cT),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=pT):a.stencilLoadOp=dT,a.stencilStoreOp=cT);const o=s.createCommandEncoder({label:"renderContext_"+e.id});if(!0===this._isRenderCameraDepthArray(e)){const s=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===s.length?this._updateDepthLayerDescriptors(e,t,s):this._createDepthLayerDescriptors(e,t,n,s),t.bundleEncoders=[],t.bundleSets=[];for(let i=0;i<s.length;i++){const s=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+i),r={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(s),t.bundleSets.push(r)}t.currentPass=null}else{const s=o.beginRenderPass(n);t.currentPass=s,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=n,t.encoder=o,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,s,i){const r=s.depthStencilAttachment;t.layerDescriptors=[];const n=this.get(e.depthTexture);n.viewCache||(n.viewCache=[]);for(let a=0;a<i.length;a++){const i={...s,colorAttachments:[{...s.colorAttachments[0],view:s.colorAttachments[a].view}]};if(s.depthStencilAttachment){const t=a;n.viewCache[t]||(n.viewCache[t]=n.texture.createView({dimension:Zw,baseArrayLayer:a,arrayLayerCount:1})),i.depthStencilAttachment={view:n.viewCache[t],depthLoadOp:r.depthLoadOp||pT,depthStoreOp:r.depthStoreOp||cT,depthClearValue:r.depthClearValue||1},e.stencil&&(i.depthStencilAttachment.stencilLoadOp=r.stencilLoadOp,i.depthStencilAttachment.stencilStoreOp=r.stencilStoreOp,i.depthStencilAttachment.stencilClearValue=r.stencilClearValue)}else i.depthStencilAttachment={...r};t.layerDescriptors.push(i)}}_updateDepthLayerDescriptors(e,t,s){for(let i=0;i<s.length;i++){const s=t.layerDescriptors[i];if(s.depthStencilAttachment){const t=s.depthStencilAttachment;e.depth&&(e.clearDepth?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=pT):t.depthLoadOp=dT),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=pT):t.stencilLoadOp=dT)}}}finishRender(e){const t=this.get(e),s=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const s=[];for(let e=0;e<t.bundleEncoders.length;e++){const i=t.bundleEncoders[e];s.push(i.finish())}for(let r=0;r<t.layerDescriptors.length;r++)if(r<s.length){const n=t.layerDescriptors[r],a=i.beginRenderPass(n);if(e.viewport){const{x:t,y:s,width:i,height:r,minDepth:n,maxDepth:o}=e.viewportValue;a.setViewport(t,s,i,r,n,o)}if(e.scissor){const{x:t,y:s,width:i,height:r}=e.scissorValue;a.setScissorRect(t,s,i,r)}a.executeBundles([s[r]]),a.end()}}else t.currentPass&&t.currentPass.end();if(s>0){const i=8*s;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const n=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,n,0,i),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;e<t.length;e++){const s=t[e];!0===s.generateMipmaps&&this.textureUtils.generateMipmaps(s)}}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await s.mapAsync(GPUMapMode.READ);const r=s.getMappedRange(),n=new BigUint64Array(r);for(let t=0;t<i.length;t++)n[t]===BigInt(0)&&e.add(i[t]);s.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:r,height:n,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(s,i,r,n,a,o)}updateScissor(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:r,height:n}=e.scissorValue;t.setScissorRect(s,i,r,n)}getClearColor(){const e=super.getClearColor();return!0===this.renderer.alpha&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,s,i=null){const r=this.device,n=this.renderer;let a,o,h,u,l=[];if(e){const e=this.getClearColor();o={r:e.r,g:e.g,b:e.b,a:e.a}}if(null===i){h=n.depth,u=n.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){l=t.colorAttachments;const e=l[0];e.clearValue=o,e.loadOp=pT,e.storeOp=cT}(h||u)&&(a=t.depthStencilAttachment)}else{h=i.depth,u=i.stencil;const r={loadOp:e?pT:dT,clearValue:e?o:void 0};h&&(r.depthLoadOp=t?pT:dT,r.depthClearValue=t?n.getClearDepth():void 0,r.depthStoreOp=cT),u&&(r.stencilLoadOp=s?pT:dT,r.stencilClearValue=s?n.getClearStencil():void 0,r.stencilStoreOp=cT);const c=this._getRenderPassDescriptor(i,r);l=c.colorAttachments,a=c.depthStencilAttachment}h&&a&&(t?(a.depthLoadOp=pT,a.depthClearValue=n.getClearDepth(),a.depthStoreOp=cT):(a.depthLoadOp=dT,a.depthStoreOp=cT)),u&&a&&(s?(a.stencilLoadOp=pT,a.stencilClearValue=n.getClearStencil(),a.stencilStoreOp=cT):(a.stencilLoadOp=dT,a.stencilStoreOp=cT));const c=r.createCommandEncoder({label:"clear"});c.beginRenderPass({colorAttachments:l,depthStencilAttachment:a}).end(),r.queue.submit([c.finish()])}beginCompute(e){const t=this.get(e),s={label:"computeGroup_"+e.id};this.initTimestampQuery(ut,this.getTimestampUID(e),s),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(s)}compute(e,t,s,i,r=null){const n=this.get(t),{passEncoderGPU:a}=this.get(e),o=this.get(i).pipeline;this.pipelineUtils.setPipeline(a,o);for(let e=0,t=s.length;e<t;e++){const t=s[e],i=this.get(t);a.setBindGroup(e,i.group)}if(null===r&&(r=t.count),r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute){const e=this.get(r).buffer;return void a.dispatchWorkgroupsIndirect(e,0)}if("number"==typeof r){const e=r;if(void 0===n.dispatchSize||n.count!==e){n.dispatchSize=[0,1,1],n.count=e;const s=t.workgroupSize;let i=s[0];for(let e=1;e<s.length;e++)i*=s[e];const a=Math.ceil(e/i),o=this.device.limits.maxComputeWorkgroupsPerDimension;r=[a,1,1],a>o&&(r[0]=Math.min(a,o),r[1]=Math.ceil(a/o)),n.dispatchSize=r}r=n.dispatchSize}a.dispatchWorkgroups(r[0],r[1]||1,r[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:s,material:i,context:r,pipeline:n}=e,a=e.getBindings(),o=this.get(r),h=this.get(n),u=h.pipeline;if(!0===h.error)return;const l=e.getIndex(),c=null!==l,d=e.getDrawParameters();if(null===d)return;const p=(t,s)=>{this.pipelineUtils.setPipeline(t,u),s.pipeline=u;const n=s.bindingGroups;for(let e=0,s=a.length;e<s;e++){const s=a[e],i=this.get(s);n[s.index]!==s.id&&(t.setBindGroup(s.index,i.group),n[s.index]=s.id)}if(!0===c&&s.index!==l){const e=this.get(l).buffer,i=l.array instanceof Uint16Array?bT:_T;t.setIndexBuffer(e,i),s.index=l}const h=e.getVertexBuffers();for(let e=0,i=h.length;e<i;e++){const i=h[e];if(s.attributes[e]!==i){const r=this.get(i).buffer;t.setVertexBuffer(e,r),s.attributes[e]=i}}!0===r.stencil&&!0===i.stencilWrite&&o.currentStencilRef!==i.stencilRef&&(t.setStencilReference(i.stencilRef),o.currentStencilRef=i.stencilRef)},m=(r,n)=>{if(p(r,n),!0===s.isBatchedMesh){const e=s._multiDrawStarts,n=s._multiDrawCounts,a=s._multiDrawCount,o=s._multiDrawInstances;null!==o&&_t("WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");let h=!0===c?l.array.BYTES_PER_ELEMENT:1;i.wireframe&&(h=s.geometry.attributes.position.count>65535?4:2);for(let i=0;i<a;i++){const a=o?o[i]:1,u=a>1?0:i;!0===c?r.drawIndexed(n[i],a,e[i]/h,0,u):r.draw(n[i],a,e[i],u),t.update(s,n[i],a)}}else if(!0===c){const{vertexCount:i,instanceCount:n,firstVertex:a}=d,o=e.getIndirect();if(null!==o){const t=this.get(o).buffer,s=e.getIndirectOffset(),i=Array.isArray(s)?s:[s];for(let e=0;e<i.length;e++)r.drawIndexedIndirect(t,i[e])}else r.drawIndexed(i,n,a,0,0);t.update(s,i,n)}else{const{vertexCount:i,instanceCount:n,firstVertex:a}=d,o=e.getIndirect();if(null!==o){const t=this.get(o).buffer,s=e.getIndirectOffset(),i=Array.isArray(s)?s:[s];for(let e=0;e<i.length;e++)r.drawIndirect(t,i[e])}else r.draw(i,n,a,0);t.update(s,i,n)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),i=e.camera.cameras,n=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==i.length){const e=this.get(n),s=[],r=new Uint32Array([0,0,0,0]);for(let t=0,n=i.length;t<n;t++){r[0]=t;const{layoutGPU:i}=e.layout,n=this.bindingUtils.createBindGroupIndex(r,i);s.push(n)}t.indexesGPU=s}const a=this.renderer.getPixelRatio();for(let e=0,h=i.length;e<h;e++){const h=i[e];if(s.layers.test(h.layers)){const s=h.viewport;let i=o.currentPass,u=o.currentSets;if(o.bundleEncoders){i=o.bundleEncoders[e],u=o.bundleSets[e]}s&&i.setViewport(Math.floor(s.x*a),Math.floor(s.y*a),Math.floor(s.width*a),Math.floor(s.height*a),r.viewportValue.minDepth,r.viewportValue.maxDepth),n&&t.indexesGPU&&(i.setBindGroup(n.index,t.indexesGPU[e]),u.bindingGroups[n.index]=n.id),m(i,u)}}}else if(o.currentPass){if(void 0!==o.occlusionQuerySet){const e=o.lastOcclusionObject;e!==s&&(null!==e&&!0===e.occlusionTest&&(o.currentPass.endOcclusionQuery(),o.occlusionQueryIndex++),!0===s.occlusionTest&&(o.currentPass.beginOcclusionQuery(o.occlusionQueryIndex),o.occlusionQueryObjects[o.occlusionQueryIndex]=s),o.lastOcclusionObject=s)}m(o.currentPass,o.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),a=r.getCurrentColorSpace(e.context),o=r.getCurrentColorFormat(e.context),h=r.getCurrentDepthStencilFormat(e.context),u=r.getPrimitiveTopology(s,i);let l=!1;return t.material===i&&t.materialVersion===i.version&&t.transparent===i.transparent&&t.blending===i.blending&&t.premultipliedAlpha===i.premultipliedAlpha&&t.blendSrc===i.blendSrc&&t.blendDst===i.blendDst&&t.blendEquation===i.blendEquation&&t.blendSrcAlpha===i.blendSrcAlpha&&t.blendDstAlpha===i.blendDstAlpha&&t.blendEquationAlpha===i.blendEquationAlpha&&t.colorWrite===i.colorWrite&&t.depthWrite===i.depthWrite&&t.depthTest===i.depthTest&&t.depthFunc===i.depthFunc&&t.stencilWrite===i.stencilWrite&&t.stencilFunc===i.stencilFunc&&t.stencilFail===i.stencilFail&&t.stencilZFail===i.stencilZFail&&t.stencilZPass===i.stencilZPass&&t.stencilFuncMask===i.stencilFuncMask&&t.stencilWriteMask===i.stencilWriteMask&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===a&&t.colorFormat===o&&t.depthStencilFormat===h&&t.primitiveTopology===u&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=n,t.colorSpace=a,t.colorFormat=o,t.depthStencilFormat=h,t.primitiveTopology=u,t.clippingContextCacheKey=e.clippingContextCacheKey,l=!0),l}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,r=e.context,n=t.isMesh&&t.matrixWorld.determinant()<0;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,n,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,s),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}initTimestampQuery(e,t,s){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new zM(this.device,e,2048));const i=this.timestampQueryPool[e],r=i.allocateQueriesForContext(t);s.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:r,endOfPassWriteIndex:r+1}}createNodeBuilder(e,t){return new PM(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage+(""!==e.name?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),i=s.currentPass.finish();this.get(t).bundleGPU=i,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}getMaxAnisotropy(){return 16}hasFeature(e){return void 0!==aM[e]&&(e=aM[e]),this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){let a=0,o=0,h=0,u=0,l=0,c=0,d=e.image.width,p=e.image.height,m=1;null!==s&&(!0===s.isBox3?(u=s.min.x,l=s.min.y,c=s.min.z,d=s.max.x-s.min.x,p=s.max.y-s.min.y,m=s.max.z-s.min.z):(u=s.min.x,l=s.min.y,d=s.max.x-s.min.x,p=s.max.y-s.min.y,m=1)),null!==i&&(a=i.x,o=i.y,h=i.z||0);const g=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),f=this.get(e).texture,y=this.get(t).texture;g.copyTextureToTexture({texture:f,mipLevel:r,origin:{x:u,y:l,z:c}},{texture:y,mipLevel:n,origin:{x:a,y:o,z:h}},[d,p,m]),this.device.queue.submit([g.finish()]),0===n&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,s){const i=this.get(t);let r=null;r=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const n=this.get(e).texture;if(r.format!==n.format)return void bt("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,n.format);let a;if(i.currentPass?(i.currentPass.end(),a=i.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:r,origin:[s.x,s.y,0]},{texture:n},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,a),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=dT;t.depth&&(e.depthStencilAttachment.depthLoadOp=dT),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=dT),i.currentPass=a.beginRenderPass(e),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else this.device.queue.submit([a.finish()])}hasCompatibility(e){return void 0!==this._compatibility[ct]?this._compatibility[ct]:super.hasCompatibility(e)}dispose(){if(this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}if(this.timestampQueryPool)for(const e of Object.values(this.timestampQueryPool))null!==e&&e.dispose();void 0===this.parameters.device&&null!==this.device&&this.device.destroy()}}class GM extends hn{constructor(e,t,s,i,r,n){super(e,t,s,i,r,n),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class jM extends hn{constructor(e,t,s,i,r,n){super(e,t,s,i,r,n),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class $M extends Ox{constructor(){super(),this.addMaterial(Ym,"MeshPhongMaterial"),this.addMaterial(Vf,"MeshStandardMaterial"),this.addMaterial(jf,"MeshPhysicalMaterial"),this.addMaterial(qf,"MeshToonMaterial"),this.addMaterial(zm,"MeshBasicMaterial"),this.addMaterial(qm,"MeshLambertMaterial"),this.addMaterial(Em,"MeshNormalMaterial"),this.addMaterial(Kf,"MeshMatcapMaterial"),this.addMaterial(Sm,"LineBasicMaterial"),this.addMaterial(Mm,"LineDashedMaterial"),this.addMaterial(iy,"PointsMaterial"),this.addMaterial(ey,"SpriteMaterial"),this.addMaterial(oy,"ShadowMaterial"),this.addLight(S_,ln),this.addLight(lx,pn),this.addLight(xx,gn),this.addLight(dx,hn),this.addLight(ux,mn),this.addLight(cx,qr),this.addLight(mx,yn),this.addLight(px,GM),this.addLight(fx,jM),this.addToneMapping(_b,1),this.addToneMapping(xb,2),this.addToneMapping(vb,3),this.addToneMapping(Sb,4),this.addToneMapping(Eb,6),this.addToneMapping(Ab,7)}}class WM extends av{constructor(e={}){let t;e.forceWebGL?t=Qv:(t=VM,e.getFallback=()=>(yt("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new Qv(e)));super(new t(e),e),this.library=new $M,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const HM={type:"change"},qM={type:"start"},XM={type:"end"},YM=1e-6,KM=-1,QM=0,ZM=1,JM=2,eN=3,tN=4,sN=new e.Vector2,iN=new e.Vector2,rN=new e.Vector3,nN=new e.Vector3,aN=new e.Vector3,oN=new e.Quaternion,hN=new e.Vector3,uN=new e.Vector3,lN=new e.Vector3,cN=new e.Vector3;class dN extends e.Controls{constructor(t,s=null){super(t,s),this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:e.MOUSE.ROTATE,MIDDLE:e.MOUSE.DOLLY,RIGHT:e.MOUSE.PAN},this.target=new e.Vector3,this.state=KM,this.keyState=KM,this._lastPosition=new e.Vector3,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new e.Vector3,this._movePrev=new e.Vector2,this._moveCurr=new e.Vector2,this._lastAxis=new e.Vector3,this._zoomStart=new e.Vector2,this._zoomEnd=new e.Vector2,this._panStart=new e.Vector2,this._panEnd=new e.Vector2,this._pointers=[],this._pointerPositions={},this._onPointerMove=mN.bind(this),this._onPointerDown=pN.bind(this),this._onPointerUp=gN.bind(this),this._onPointerCancel=fN.bind(this),this._onContextMenu=SN.bind(this),this._onMouseWheel=TN.bind(this),this._onKeyDown=bN.bind(this),this._onKeyUp=yN.bind(this),this._onTouchStart=wN.bind(this),this._onTouchMove=MN.bind(this),this._onTouchEnd=NN.bind(this),this._onMouseDown=_N.bind(this),this._onMouseMove=xN.bind(this),this._onMouseUp=vN.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,null!==s&&(this.connect(s),this.handleResize()),this.update()}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){this._eye.subVectors(this.object.position,this.target),this.noRotate||this._rotateCamera(),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this._checkDistances(),this.object.lookAt(this.target),this._lastPosition.distanceToSquared(this.object.position)>YM&&(this.dispatchEvent(HM),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>YM||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(HM),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=KM,this.keyState=KM,this.target.copy(this._target0),this.object.position.copy(this._position0),this.object.up.copy(this._up0),this.object.zoom=this._zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(HM),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(iN.copy(this._panEnd).sub(this._panStart),iN.lengthSq()){if(this.object.isOrthographicCamera){const e=(this.object.right-this.object.left)/this.object.zoom/this.domElement.clientWidth,t=(this.object.top-this.object.bottom)/this.object.zoom/this.domElement.clientWidth;iN.x*=e,iN.y*=t}iN.multiplyScalar(this._eye.length()*this.panSpeed),nN.copy(this._eye).cross(this.object.up).setLength(iN.x),nN.add(rN.copy(this.object.up).setLength(iN.y)),this.object.position.add(nN),this.target.add(nN),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(iN.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){cN.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=cN.length();e?(this._eye.copy(this.object.position).sub(this.target),hN.copy(this._eye).normalize(),uN.copy(this.object.up).normalize(),lN.crossVectors(uN,hN).normalize(),uN.setLength(this._moveCurr.y-this._movePrev.y),lN.setLength(this._moveCurr.x-this._movePrev.x),cN.copy(uN.add(lN)),aN.crossVectors(cN,this._eye).normalize(),e*=this.rotateSpeed,oN.setFromAxisAngle(aN,e),this._eye.applyQuaternion(oN),this.object.up.applyQuaternion(oN),this._lastAxis.copy(aN),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),oN.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(oN),this.object.up.applyQuaternion(oN)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let t;this.state===tN?(t=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(t):this.object.isOrthographicCamera?(this.object.zoom=e.MathUtils.clamp(this.object.zoom/t,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(t=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==t&&t>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(t):this.object.isOrthographicCamera?(this.object.zoom=e.MathUtils.clamp(this.object.zoom/t,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor)}_getMouseOnScreen(e,t){return sN.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),sN}_getMouseOnCircle(e,t){return sN.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),sN}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId==e.pointerId)return void this._pointers.splice(t,1)}_trackPointer(t){let s=this._pointerPositions[t.pointerId];void 0===s&&(s=new e.Vector2,this._pointerPositions[t.pointerId]=s),s.set(t.pageX,t.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0].pointerId?this._pointers[1]:this._pointers[0];return this._pointerPositions[t.pointerId]}_checkDistances(){this.noZoom&&this.noPan||(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}}function pN(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e))}function mN(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function gN(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchEnd(e):this._onMouseUp(),this._removePointer(e),0===this._pointers.length&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp)))}function fN(e){this._removePointer(e)}function yN(){!1!==this.enabled&&(this.keyState=KM,window.addEventListener("keydown",this._onKeyDown))}function bN(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===KM&&(e.code!==this.keys[QM]||this.noRotate?e.code!==this.keys[ZM]||this.noZoom?e.code!==this.keys[JM]||this.noPan||(this.keyState=JM):this.keyState=ZM:this.keyState=QM))}function _N(t){let s;switch(t.button){case 0:s=this.mouseButtons.LEFT;break;case 1:s=this.mouseButtons.MIDDLE;break;case 2:s=this.mouseButtons.RIGHT;break;default:s=-1}switch(s){case e.MOUSE.DOLLY:this.state=ZM;break;case e.MOUSE.ROTATE:this.state=QM;break;case e.MOUSE.PAN:this.state=JM;break;default:this.state=KM}const i=this.keyState!==KM?this.keyState:this.state;i!==QM||this.noRotate?i!==ZM||this.noZoom?i!==JM||this.noPan||(this._panStart.copy(this._getMouseOnScreen(t.pageX,t.pageY)),this._panEnd.copy(this._panStart)):(this._zoomStart.copy(this._getMouseOnScreen(t.pageX,t.pageY)),this._zoomEnd.copy(this._zoomStart)):(this._moveCurr.copy(this._getMouseOnCircle(t.pageX,t.pageY)),this._movePrev.copy(this._moveCurr)),this.dispatchEvent(qM)}function xN(e){const t=this.keyState!==KM?this.keyState:this.state;t!==QM||this.noRotate?t!==ZM||this.noZoom?t!==JM||this.noPan||this._panEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):this._zoomEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):(this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)))}function vN(){this.state=KM,this.dispatchEvent(XM)}function TN(e){if(!1!==this.enabled&&!0!==this.noZoom){switch(e.preventDefault(),e.deltaMode){case 2:this._zoomStart.y-=.025*e.deltaY;break;case 1:this._zoomStart.y-=.01*e.deltaY;break;default:this._zoomStart.y-=25e-5*e.deltaY}this.dispatchEvent(qM),this.dispatchEvent(XM)}}function SN(e){!1!==this.enabled&&e.preventDefault()}function wN(e){if(this._trackPointer(e),1===this._pointers.length)this.state=eN,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=tN;const e=this._pointers[0].pageX-this._pointers[1].pageX,t=this._pointers[0].pageY-this._pointers[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(e*e+t*t);const s=(this._pointers[0].pageX+this._pointers[1].pageX)/2,i=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(s,i)),this._panEnd.copy(this._panStart)}this.dispatchEvent(qM)}function MN(e){if(this._trackPointer(e),1===this._pointers.length)this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY));else{const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(s*s+i*i);const r=(e.pageX+t.x)/2,n=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(r,n))}}function NN(e){switch(this._pointers.length){case 0:this.state=KM;break;case 1:this.state=eN,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=tN;for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId!==e.pointerId){const e=this._pointerPositions[this._pointers[t].pointerId];this._moveCurr.copy(this._getMouseOnCircle(e.x,e.y)),this._movePrev.copy(this._moveCurr);break}}this.dispatchEvent(XM)}const EN={type:"change"},AN={type:"start"},CN={type:"end"},RN=new e.Ray,PN=new e.Plane,BN=Math.cos(70*e.MathUtils.DEG2RAD),FN=new e.Vector3,DN=2*Math.PI,IN=-1,LN=0,ON=1,UN=2,kN=3,zN=4,VN=5,GN=6,jN=1e-6;class $N extends e.Controls{constructor(t,s=null){super(t,s),this.state=IN,this.target=new e.Vector3,this.cursor=new e.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:e.MOUSE.ROTATE,MIDDLE:e.MOUSE.DOLLY,RIGHT:e.MOUSE.PAN},this.touches={ONE:e.TOUCH.ROTATE,TWO:e.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new e.Vector3,this._lastQuaternion=new e.Quaternion,this._lastTargetPosition=new e.Vector3,this._quat=(new e.Quaternion).setFromUnitVectors(t.up,new e.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new e.Spherical,this._sphericalDelta=new e.Spherical,this._scale=1,this._panOffset=new e.Vector3,this._rotateStart=new e.Vector2,this._rotateEnd=new e.Vector2,this._rotateDelta=new e.Vector2,this._panStart=new e.Vector2,this._panEnd=new e.Vector2,this._panDelta=new e.Vector2,this._dollyStart=new e.Vector2,this._dollyEnd=new e.Vector2,this._dollyDelta=new e.Vector2,this._dollyDirection=new e.Vector3,this._mouse=new e.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=HN.bind(this),this._onPointerDown=WN.bind(this),this._onPointerUp=qN.bind(this),this._onContextMenu=eE.bind(this),this._onMouseWheel=KN.bind(this),this._onKeyDown=QN.bind(this),this._onTouchStart=ZN.bind(this),this._onTouchMove=JN.bind(this),this._onMouseDown=XN.bind(this),this._onMouseMove=YN.bind(this),this._interceptControlDown=tE.bind(this),this._interceptControlUp=sE.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,this.domElement.style.cursor="grab"===e?"grab":"auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1});this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){null!==this._domElementKeyEvents&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(EN),this.update(),this.state=IN}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(t=null){const s=this.object.position;FN.copy(s).sub(this.target),FN.applyQuaternion(this._quat),this._spherical.setFromVector3(FN),this.autoRotate&&this.state===IN&&this._rotateLeft(this._getAutoRotationAngle(t)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let i=this.minAzimuthAngle,r=this.maxAzimuthAngle;isFinite(i)&&isFinite(r)&&(i<-Math.PI?i+=DN:i>Math.PI&&(i-=DN),r<-Math.PI?r+=DN:r>Math.PI&&(r-=DN),this._spherical.theta=i<=r?Math.max(i,Math.min(r,this._spherical.theta)):this._spherical.theta>(i+r)/2?Math.max(i,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),!0===this.enableDamping?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let n=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=e!=this._spherical.radius}if(FN.setFromSpherical(this._spherical),FN.applyQuaternion(this._quatInverse),s.copy(this.target).add(FN),this.object.lookAt(this.target),!0===this.enableDamping?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let t=null;if(this.object.isPerspectiveCamera){const e=FN.length();t=this._clampDistance(e*this._scale);const s=e-t;this.object.position.addScaledVector(this._dollyDirection,s),this.object.updateMatrixWorld(),n=!!s}else if(this.object.isOrthographicCamera){const s=new e.Vector3(this._mouse.x,this._mouse.y,0);s.unproject(this.object);const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),n=i!==this.object.zoom;const r=new e.Vector3(this._mouse.x,this._mouse.y,0);r.unproject(this.object),this.object.position.sub(r).add(s),this.object.updateMatrixWorld(),t=FN.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==t&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(t).add(this.object.position):(RN.origin.copy(this.object.position),RN.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(RN.direction))<BN?this.object.lookAt(this.target):(PN.setFromNormalAndCoplanarPoint(this.object.up,this.target),RN.intersectPlane(PN,this.target))))}else if(this.object.isOrthographicCamera){const e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),n=!0)}return this._scale=1,this._performCursorZoom=!1,!!(n||this._lastPosition.distanceToSquared(this.object.position)>jN||8*(1-this._lastQuaternion.dot(this.object.quaternion))>jN||this._lastTargetPosition.distanceToSquared(this.target)>jN)&&(this.dispatchEvent(EN),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?DN/60*this.autoRotateSpeed*e:DN/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(.01*e);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){FN.setFromMatrixColumn(t,0),FN.multiplyScalar(-e),this._panOffset.add(FN)}_panUp(e,t){!0===this.screenSpacePanning?FN.setFromMatrixColumn(t,1):(FN.setFromMatrixColumn(t,0),FN.crossVectors(this.object.up,FN)),FN.multiplyScalar(e),this._panOffset.add(FN)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;FN.copy(i).sub(this.target);let r=FN.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/s.clientHeight,this.object.matrix),this._panUp(2*t*r/s.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/s.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/s.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const s=this.domElement.getBoundingClientRect(),i=e-s.left,r=t-s.top,n=s.width,a=s.height;this._mouse.x=i/n*2-1,this._mouse.y=-r/a*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(DN*this._rotateDelta.x/t.clientHeight),this._rotateUp(DN*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(DN*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-DN*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(DN*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-DN*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(1===this._pointers.length)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(s,i)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(s,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(s*s+i*i);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateEnd.set(s,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(DN*this._rotateDelta.x/t.clientHeight),this._rotateUp(DN*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(s,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(s*s+i*i);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const n=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(n,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return void this._pointers.splice(t,1)}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(t){let s=this._pointerPositions[t.pointerId];void 0===s&&(s=new e.Vector2,this._pointerPositions[t.pointerId]=s),s.set(t.pageX,t.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,s={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:s.deltaY*=16;break;case 2:s.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(s.deltaY*=10),s}}function WN(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e),"grab"===this._cursorStyle&&(this.domElement.style.cursor="grabbing")))}function HN(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function qN(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(CN),this.state=IN,"grab"===this._cursorStyle&&(this.domElement.style.cursor="grab");break;case 1:const t=this._pointers[0],s=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:s.x,pageY:s.y})}}function XN(t){let s;switch(t.button){case 0:s=this.mouseButtons.LEFT;break;case 1:s=this.mouseButtons.MIDDLE;break;case 2:s=this.mouseButtons.RIGHT;break;default:s=-1}switch(s){case e.MOUSE.DOLLY:if(!1===this.enableZoom)return;this._handleMouseDownDolly(t),this.state=ON;break;case e.MOUSE.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=UN}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=LN}break;case e.MOUSE.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=LN}else{if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=UN}break;default:this.state=IN}this.state!==IN&&this.dispatchEvent(AN)}function YN(e){switch(this.state){case LN:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case ON:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case UN:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function KN(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===IN&&(e.preventDefault(),this.dispatchEvent(AN),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(CN))}function QN(e){!1!==this.enabled&&this._handleKeyDown(e)}function ZN(t){switch(this._trackPointer(t),this._pointers.length){case 1:switch(this.touches.ONE){case e.TOUCH.ROTATE:if(!1===this.enableRotate)return;this._handleTouchStartRotate(t),this.state=kN;break;case e.TOUCH.PAN:if(!1===this.enablePan)return;this._handleTouchStartPan(t),this.state=zN;break;default:this.state=IN}break;case 2:switch(this.touches.TWO){case e.TOUCH.DOLLY_PAN:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(t),this.state=VN;break;case e.TOUCH.DOLLY_ROTATE:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(t),this.state=GN;break;default:this.state=IN}break;default:this.state=IN}this.state!==IN&&this.dispatchEvent(AN)}function JN(e){switch(this._trackPointer(e),this.state){case kN:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case zN:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case VN:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case GN:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=IN}}function eE(e){!1!==this.enabled&&e.preventDefault()}function tE(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function sE(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const iE={type:"change"},rE=1e-6,nE=new e.Quaternion;class aE extends e.Controls{constructor(t,s=null){super(t,s),this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1,this._moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this._moveVector=new e.Vector3(0,0,0),this._rotationVector=new e.Vector3(0,0,0),this._lastQuaternion=new e.Quaternion,this._lastPosition=new e.Vector3,this._status=0,this._onKeyDown=oE.bind(this),this._onKeyUp=hE.bind(this),this._onPointerMove=lE.bind(this),this._onPointerDown=uE.bind(this),this._onPointerUp=cE.bind(this),this._onPointerCancel=dE.bind(this),this._onContextMenu=pE.bind(this),null!==s&&this.connect(s)}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu)}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu)}dispose(){this.disconnect()}update(e){if(!1===this.enabled)return;const t=this.object,s=e*this.movementSpeed,i=e*this.rollSpeed;t.translateX(this._moveVector.x*s),t.translateY(this._moveVector.y*s),t.translateZ(this._moveVector.z*s),nE.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(nE),(this._lastPosition.distanceToSquared(t.position)>rE||8*(1-this._lastQuaternion.dot(t.quaternion))>rE)&&(this.dispatchEvent(iE),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){const e=this._moveState.forward||this.autoForward&&!this._moveState.back?1:0;this._moveVector.x=-this._moveState.left+this._moveState.right,this._moveVector.y=-this._moveState.down+this._moveState.up,this._moveVector.z=-e+this._moveState.back}_updateRotationVector(){this._rotationVector.x=-this._moveState.pitchDown+this._moveState.pitchUp,this._rotationVector.y=-this._moveState.yawRight+this._moveState.yawLeft,this._rotationVector.z=-this._moveState.rollRight+this._moveState.rollLeft}_getContainerDimensions(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}}}function oE(e){if(!e.altKey&&!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this._moveState.forward=1;break;case"KeyS":this._moveState.back=1;break;case"KeyA":this._moveState.left=1;break;case"KeyD":this._moveState.right=1;break;case"KeyR":this._moveState.up=1;break;case"KeyF":this._moveState.down=1;break;case"ArrowUp":this._moveState.pitchUp=1;break;case"ArrowDown":this._moveState.pitchDown=1;break;case"ArrowLeft":this._moveState.yawLeft=1;break;case"ArrowRight":this._moveState.yawRight=1;break;case"KeyQ":this._moveState.rollLeft=1;break;case"KeyE":this._moveState.rollRight=1}this._updateMovementVector(),this._updateRotationVector()}}function hE(e){if(!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this._moveState.forward=0;break;case"KeyS":this._moveState.back=0;break;case"KeyA":this._moveState.left=0;break;case"KeyD":this._moveState.right=0;break;case"KeyR":this._moveState.up=0;break;case"KeyF":this._moveState.down=0;break;case"ArrowUp":this._moveState.pitchUp=0;break;case"ArrowDown":this._moveState.pitchDown=0;break;case"ArrowLeft":this._moveState.yawLeft=0;break;case"ArrowRight":this._moveState.yawRight=0;break;case"KeyQ":this._moveState.rollLeft=0;break;case"KeyE":this._moveState.rollRight=0}this._updateMovementVector(),this._updateRotationVector()}}function uE(e){if(!1!==this.enabled)if(this.dragToLook)this._status++;else{switch(e.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1}this._updateMovementVector()}}function lE(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),s=t.size[0]/2,i=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-s)/s,this._moveState.pitchDown=(e.pageY-t.offset[1]-i)/i,this._updateRotationVector()}}function cE(e){if(!1!==this.enabled){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(e.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0}this._updateMovementVector()}this._updateRotationVector()}}function dE(){!1!==this.enabled&&(this.dragToLook?(this._status=0,this._moveState.yawLeft=this._moveState.pitchDown=0):(this._moveState.forward=0,this._moveState.back=0,this._updateMovementVector()),this._updateRotationVector())}function pE(e){!1!==this.enabled&&e.preventDefault()}const mE={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n\t\tuniform float opacity;\n\n\t\tuniform sampler2D tDiffuse;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 texel = texture2D( tDiffuse, vUv );\n\t\t\tgl_FragColor = opacity * texel;\n\n\n\t\t}"};class gE{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const fE=new e.OrthographicCamera(-1,1,1,-1,0,1);class yE extends e.BufferGeometry{constructor(){super(),this.setAttribute("position",new e.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new e.Float32BufferAttribute([0,2,0,0,2,0],2))}}const bE=new yE;class _E{constructor(t){this._mesh=new e.Mesh(bE,t)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,fE)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class xE extends gE{constructor(t,s="tDiffuse"){super(),this.textureID=s,this.uniforms=null,this.material=null,t instanceof e.ShaderMaterial?(this.uniforms=t.uniforms,this.material=t):t&&(this.uniforms=e.UniformsUtils.clone(t.uniforms),this.material=new e.ShaderMaterial({name:void 0!==t.name?t.name:"unspecified",defines:Object.assign({},t.defines),uniforms:this.uniforms,vertexShader:t.vertexShader,fragmentShader:t.fragmentShader})),this._fsQuad=new _E(this.material)}render(e,t,s){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=s.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}class vE extends gE{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,s){const i=e.getContext(),r=e.state;let n,a;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(n=0,a=1):(n=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),r.buffers.stencil.setFunc(i.ALWAYS,n,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(s),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(i.EQUAL,1,4294967295),r.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),r.buffers.stencil.setLocked(!0)}}class TE extends gE{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class SE{constructor(t,s){if(this.renderer=t,this._pixelRatio=t.getPixelRatio(),void 0===s){const i=t.getSize(new e.Vector2);this._width=i.width,this._height=i.height,(s=new e.WebGLRenderTarget(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:e.HalfFloatType})).texture.name="EffectComposer.rt1"}else this._width=s.width,this._height=s.height;this.renderTarget1=s,this.renderTarget2=s.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new xE(mE),this.copyPass.material.blending=e.NoBlending,this.timer=new e.Timer}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);-1!==t&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){this.timer.update(),void 0===e&&(e=this.timer.getDelta());const t=this.renderer.getRenderTarget();let s=!1;for(let t=0,i=this.passes.length;t<i;t++){const i=this.passes[t];if(!1!==i.enabled){if(i.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),i.render(this.renderer,this.writeBuffer,this.readBuffer,e,s),i.needsSwap){if(s){const t=this.renderer.getContext(),s=this.renderer.state.buffers.stencil;s.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),s.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==vE&&(i instanceof vE?s=!0:i instanceof TE&&(s=!1))}}this.renderer.setRenderTarget(t)}reset(t){if(void 0===t){const s=this.renderer.getSize(new e.Vector2);this._pixelRatio=this.renderer.getPixelRatio(),this._width=s.width,this._height=s.height,(t=this.renderTarget1.clone()).setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=t,this.renderTarget2=t.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget1.setSize(s,i),this.renderTarget2.setSize(s,i);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class wE extends gE{constructor(t,s,i=null,r=null,n=null){super(),this.scene=t,this.camera=s,this.overrideMaterial=i,this.clearColor=r,this.clearAlpha=n,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new e.Color}render(e,t,s){const i=e.autoClear;let r,n;e.autoClear=!1,null!==this.overrideMaterial&&(n=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),null!==this.clearColor&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),null!==this.clearAlpha&&(r=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:s),!0===this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),null!==this.clearColor&&e.setClearColor(this._oldClearColor),null!==this.clearAlpha&&e.setClearAlpha(r),null!==this.overrideMaterial&&(this.scene.overrideMaterial=n),e.autoClear=i}}function ME(){return ME=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},ME.apply(null,arguments)}function NE(e,t){return NE=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},NE(e,t)}function EE(e){return EE=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},EE(e)}function AE(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(AE=function(){return!!e})()}function CE(e){var t="function"==typeof Map?new Map:void 0;return CE=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,s)}function s(){return function(e,t,s){if(AE())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return s&&NE(r,s.prototype),r}(e,arguments,EE(this).constructor)}return s.prototype=Object.create(e.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),NE(s,e)},CE(e)}var RE={1:"Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).\n\n",2:"Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).\n\n",3:"Passed an incorrect argument to a color function, please pass a string representation of a color.\n\n",4:"Couldn't generate valid rgb string from %s, it returned %s.\n\n",5:"Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.\n\n",6:"Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).\n\n",7:"Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).\n\n",8:"Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.\n\n",9:"Please provide a number of steps to the modularScale helper.\n\n",10:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",11:'Invalid value passed as base to modularScale, expected number or em string but got "%s"\n\n',12:'Expected a string ending in "px" or a number passed as the first argument to %s(), got "%s" instead.\n\n',13:'Expected a string ending in "px" or a number passed as the second argument to %s(), got "%s" instead.\n\n',14:'Passed invalid pixel value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',15:'Passed invalid base value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',16:"You must provide a template to this method.\n\n",17:"You passed an unsupported selector state to this method.\n\n",18:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",19:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",20:"expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",21:"expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\n\n",22:"expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\n\n",23:"fontFace expects a name of a font-family.\n\n",24:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",25:"fontFace expects localFonts to be an array.\n\n",26:"fontFace expects fileFormats to be an array.\n\n",27:"radialGradient requries at least 2 color-stops to properly render.\n\n",28:"Please supply a filename to retinaImage() as the first argument.\n\n",29:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",30:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",31:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation\n\n",32:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')\n\n",33:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation\n\n",34:"borderRadius expects a radius value as a string or number as the second argument.\n\n",35:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',36:"Property must be a string value.\n\n",37:"Syntax Error at %s.\n\n",38:"Formula contains a function that needs parentheses at %s.\n\n",39:"Formula is missing closing parenthesis at %s.\n\n",40:"Formula has too many closing parentheses at %s.\n\n",41:"All values in a formula must have the same unit or be unitless.\n\n",42:"Please provide a number of steps to the modularScale helper.\n\n",43:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",44:"Invalid value passed as base to modularScale, expected number or em/rem string but got %s.\n\n",45:"Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.\n\n",46:"Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.\n\n",47:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",48:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",49:"Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",50:"Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.\n\n",51:"Expects the first argument object to have the properties prop, fromSize, and toSize.\n\n",52:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",53:"fontFace expects localFonts to be an array.\n\n",54:"fontFace expects fileFormats to be an array.\n\n",55:"fontFace expects a name of a font-family.\n\n",56:"linearGradient requries at least 2 color-stops to properly render.\n\n",57:"radialGradient requries at least 2 color-stops to properly render.\n\n",58:"Please supply a filename to retinaImage() as the first argument.\n\n",59:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",60:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",61:"Property must be a string value.\n\n",62:"borderRadius expects a radius value as a string or number as the second argument.\n\n",63:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',64:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.\n\n",65:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').\n\n",66:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.\n\n",67:"You must provide a template to this method.\n\n",68:"You passed an unsupported selector state to this method.\n\n",69:'Expected a string ending in "px" or a number passed as the first argument to %s(), got %s instead.\n\n',70:'Expected a string ending in "px" or a number passed as the second argument to %s(), got %s instead.\n\n',71:'Passed invalid pixel value %s to %s(), please pass a value like "12px" or 12.\n\n',72:'Passed invalid base value %s to %s(), please pass a value like "12px" or 12.\n\n',73:"Please provide a valid CSS variable.\n\n",74:"CSS variable not found and no default was provided.\n\n",75:"important requires a valid style object, got a %s instead.\n\n",76:"fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.\n\n",77:'remToPx expects a value in "rem" but you provided it in "%s".\n\n',78:'base must be set in "px" or "%" but you set it in "%s".\n'};function PE(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];var i,r=t[0],n=[];for(i=1;i<t.length;i+=1)n.push(t[i]);return n.forEach(function(e){r=r.replace(/%[a-z]/,e)}),r}var BE=function(e){function t(t){var s;if("production"===process.env.NODE_ENV)s=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+t+" for more information.")||this;else{for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];s=e.call(this,PE.apply(void 0,[RE[t]].concat(r)))||this}return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(s)}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,NE(e,t)}(t,e),t}(CE(Error));function FE(e){return Math.round(255*e)}function DE(e,t,s){return FE(e)+","+FE(t)+","+FE(s)}function IE(e,t,s,i){if(void 0===i&&(i=DE),0===t)return i(s,s,s);var r=(e%360+360)%360/60,n=(1-Math.abs(2*s-1))*t,a=n*(1-Math.abs(r%2-1)),o=0,h=0,u=0;r>=0&&r<1?(o=n,h=a):r>=1&&r<2?(o=a,h=n):r>=2&&r<3?(h=n,u=a):r>=3&&r<4?(h=a,u=n):r>=4&&r<5?(o=a,u=n):r>=5&&r<6&&(o=n,u=a);var l=s-n/2;return i(o+l,h+l,u+l)}var LE={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};var OE=/^#[a-fA-F0-9]{6}$/,UE=/^#[a-fA-F0-9]{8}$/,kE=/^#[a-fA-F0-9]{3}$/,zE=/^#[a-fA-F0-9]{4}$/,VE=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,GE=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,jE=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,$E=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function WE(e){if("string"!=typeof e)throw new BE(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return LE[t]?"#"+LE[t]:e}(e);if(t.match(OE))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(UE)){var s=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:s}}if(t.match(kE))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(zE)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var r=VE.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var n=GE.exec(t.substring(0,50));if(n)return{red:parseInt(""+n[1],10),green:parseInt(""+n[2],10),blue:parseInt(""+n[3],10),alpha:parseFloat(""+n[4])>1?parseFloat(""+n[4])/100:parseFloat(""+n[4])};var a=jE.exec(t);if(a){var o="rgb("+IE(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",h=VE.exec(o);if(!h)throw new BE(4,t,o);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10)}}var u=$E.exec(t.substring(0,50));if(u){var l="rgb("+IE(parseInt(""+u[1],10),parseInt(""+u[2],10)/100,parseInt(""+u[3],10)/100)+")",c=VE.exec(l);if(!c)throw new BE(4,t,l);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10),alpha:parseFloat(""+u[4])>1?parseFloat(""+u[4])/100:parseFloat(""+u[4])}}throw new BE(5)}function HE(e){return function(e){var t,s=e.red/255,i=e.green/255,r=e.blue/255,n=Math.max(s,i,r),a=Math.min(s,i,r),o=(n+a)/2;if(n===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var h=n-a,u=o>.5?h/(2-n-a):h/(n+a);switch(n){case s:t=(i-r)/h+(i<r?6:0);break;case i:t=(r-s)/h+2;break;default:t=(s-i)/h+4}return t*=60,void 0!==e.alpha?{hue:t,saturation:u,lightness:o,alpha:e.alpha}:{hue:t,saturation:u,lightness:o}}(WE(e))}var qE=function(e){return 7===e.length&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function XE(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function YE(e){return XE(Math.round(255*e))}function KE(e,t,s){return qE("#"+YE(e)+YE(t)+YE(s))}function QE(e,t,s){return IE(e,t,s,KE)}function ZE(e,t,s){if("number"==typeof e&&"number"==typeof t&&"number"==typeof s)return qE("#"+XE(e)+XE(t)+XE(s));if("object"==typeof e&&void 0===t&&void 0===s)return qE("#"+XE(e.red)+XE(e.green)+XE(e.blue));throw new BE(6)}function JE(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?ZE(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new BE(7)}function eA(e){if("object"!=typeof e)throw new BE(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return JE(e);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return ZE(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&"number"==typeof e.alpha}(e))return function(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?QE(e.hue,e.saturation,e.lightness):"rgba("+IE(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new BE(2)}(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return function(e,t,s){if("object"==typeof e&&void 0===t&&void 0===s)return QE(e.hue,e.saturation,e.lightness);throw new BE(1)}(e);throw new BE(8)}function tA(e,t,s){return function(){var i=s.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):tA(e,t,i)}}function sA(e){return tA(e,e.length,[])}function iA(e,t,s){return Math.max(e,Math.min(t,s))}sA(function(e,t){if("transparent"===t)return t;var s=HE(t);return eA(ME({},s,{hue:s.hue+parseFloat(e)}))}),sA(function(e,t){if("transparent"===t)return t;var s=HE(t);return eA(ME({},s,{lightness:iA(0,1,s.lightness-parseFloat(e))}))}),sA(function(e,t){if("transparent"===t)return t;var s=HE(t);return eA(ME({},s,{saturation:iA(0,1,s.saturation-parseFloat(e))}))}),sA(function(e,t){if("transparent"===t)return t;var s=HE(t);return eA(ME({},s,{lightness:iA(0,1,s.lightness+parseFloat(e))}))});var rA=sA(function(e,t,s){if("transparent"===t)return s;if("transparent"===s)return t;if(0===e)return s;var i=WE(t),r=ME({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),n=WE(s),a=ME({},n,{alpha:"number"==typeof n.alpha?n.alpha:1}),o=r.alpha-a.alpha,h=2*parseFloat(e)-1,u=((h*o===-1?h:h+o)/(1+h*o)+1)/2,l=1-u;return JE({red:Math.floor(r.red*u+a.red*l),green:Math.floor(r.green*u+a.green*l),blue:Math.floor(r.blue*u+a.blue*l),alpha:r.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),nA=rA;var aA=sA(function(e,t){if("transparent"===t)return t;var s=WE(t);return JE(ME({},s,{alpha:iA(0,1,(100*("number"==typeof s.alpha?s.alpha:1)+100*parseFloat(e))/100)}))}),oA=aA;sA(function(e,t){if("transparent"===t)return t;var s=HE(t);return eA(ME({},s,{saturation:iA(0,1,s.saturation+parseFloat(e))}))}),sA(function(e,t){return"transparent"===t?t:eA(ME({},HE(t),{hue:parseFloat(e)}))}),sA(function(e,t){return"transparent"===t?t:eA(ME({},HE(t),{lightness:parseFloat(e)}))}),sA(function(e,t){return"transparent"===t?t:eA(ME({},HE(t),{saturation:parseFloat(e)}))}),sA(function(e,t){return"transparent"===t?t:nA(parseFloat(e),"rgb(0, 0, 0)",t)}),sA(function(e,t){return"transparent"===t?t:nA(parseFloat(e),"rgb(255, 255, 255)",t)}),sA(function(e,t){if("transparent"===t)return t;var s=WE(t);return JE(ME({},s,{alpha:iA(0,1,+(100*("number"==typeof s.alpha?s.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var hA=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-hA.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*hA.Bounce.In(2*e):.5*hA.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e<Number.EPSILON?Number.EPSILON:e)>1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),uA=function(){return performance.now()},lA=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._tweens={},this._tweensAddedDuringUpdate={},this.add.apply(this,e)}return e.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},e.prototype.removeAll=function(){this._tweens={}},e.prototype.add=function(){for(var e,t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];for(var i=0,r=t;i<r.length;i++){var n=r[i];null===(e=n._group)||void 0===e||e.remove(n),n._group=this,this._tweens[n.getId()]=n,this._tweensAddedDuringUpdate[n.getId()]=n}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var s=0,i=e;s<i.length;s++){var r=i[s];r._group=void 0,delete this._tweens[r.getId()],delete this._tweensAddedDuringUpdate[r.getId()]}},e.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},e.prototype.update=function(e,t){void 0===e&&(e=uA()),void 0===t&&(t=!0);var s=Object.keys(this._tweens);if(0!==s.length)for(;s.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<s.length;i++){var r=this._tweens[s[i]],n=!t;r&&!1===r.update(e,n)&&!t&&this.remove(r)}s=Object.keys(this._tweensAddedDuringUpdate)}},e}(),cA={Linear:function(e,t){var s=e.length-1,i=s*t,r=Math.floor(i),n=cA.Utils.Linear;return t<0?n(e[0],e[1],i):t>1?n(e[s],e[s-1],s-i):n(e[r],e[r+1>s?s:r+1],i-r)},Utils:{Linear:function(e,t,s){return(t-e)*s+e}}},dA=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),pA=new lA,mA=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=hA.Linear.None,this._interpolationFunction=cA.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=dA.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=pA,pA.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=uA()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var s in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(s),this._valuesStart[s]=this._valuesStartRepeat[s];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var r in this._valuesEnd)i[r]=this._valuesEnd[r];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,s,i,r){for(var n in s){var a=e[n],o=Array.isArray(a),h=o?"array":typeof a,u=!o&&Array.isArray(s[n]);if("undefined"!==h&&"function"!==h){if(u){if(0===(f=s[n]).length)continue;for(var l=[a],c=0,d=f.length;c<d;c+=1){var p=this._handleRelativeValue(a,f[c]);if(isNaN(p)){u=!1,console.warn("Found invalid interpolation list. Skipping.");break}l.push(p)}u&&(s[n]=l)}if("object"!==h&&!o||!a||u)(void 0===t[n]||r)&&(t[n]=a),o||(t[n]*=1),i[n]=u?s[n].slice().reverse():t[n]||0;else{t[n]=o?[]:{};var m=a;for(var g in m)t[n][g]=m[g];i[n]=o?[]:{};var f=s[n];if(!this._isDynamic){var y={};for(var g in f)y[g]=f[g];s[n]=f=y}this._setupProperties(m,t[n],f,i[n],r)}}}},e.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},e.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},e.prototype.pause=function(e){return void 0===e&&(e=uA()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=uA()),this._isPaused&&this._isPlaying?(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this):this},e.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},e.prototype.group=function(e){return e?(e.add(this),this):(console.warn("tween.group() without args has been removed, use group.add(tween) instead."),this)},e.prototype.remove=function(){var e;return null===(e=this._group)||void 0===e||e.remove(this),this},e.prototype.delay=function(e){return void 0===e&&(e=0),this._delayTime=e,this},e.prototype.repeat=function(e){return void 0===e&&(e=0),this._initialRepeat=e,this._repeat=e,this},e.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},e.prototype.yoyo=function(e){return void 0===e&&(e=!1),this._yoyo=e,this},e.prototype.easing=function(e){return void 0===e&&(e=hA.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=cA.Linear),this._interpolationFunction=e,this},e.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},e.prototype.onStart=function(e){return this._onStartCallback=e,this},e.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},e.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},e.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},e.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},e.prototype.onStop=function(e){return this._onStopCallback=e,this},e.prototype.update=function(t,s){var i,r,n=this;if(void 0===t&&(t=uA()),void 0===s&&(s=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!s)return!1;this.start(t,!0)}if(this._goToEnd=!1,t<this._startTime)return!0;!1===this._onStartCallbackFired&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),!1===this._onEveryStartCallbackFired&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=t-this._startTime,o=this._duration+(null!==(i=this._repeatDelayTime)&&void 0!==i?i:this._delayTime),h=this._duration+this._repeat*o,u=function(){if(0===n._duration)return 1;if(a>h)return 1;var e=Math.trunc(a/o),t=a-e*o,s=Math.min(t/n._duration,1);return 0===s&&a===n._duration?1:s}(),l=this._easingFunction(u);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,l),this._onUpdateCallback&&this._onUpdateCallback(this._object,u),0===this._duration||a>=this._duration){if(this._repeat>0){var c=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(r in isFinite(this._repeat)&&(this._repeat-=c),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[r]||(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*c,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d<p;d++)this._chainedTweens[d].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},e.prototype._updateProperties=function(e,t,s,i){for(var r in s)if(void 0!==t[r]){var n=t[r]||0,a=s[r],o=Array.isArray(e[r]),h=Array.isArray(a);!o&&h?e[r]=this._interpolationFunction(a,i):"object"==typeof a&&a?this._updateProperties(e[r],n,a,i):"number"==typeof(a=this._handleRelativeValue(n,a))&&(e[r]=n+(a-n)*i)}},e.prototype._handleRelativeValue=function(e,t){return"string"!=typeof t?t:"+"===t.charAt(0)||"-"===t.charAt(0)?e+parseFloat(t):parseFloat(t)},e.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],s=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof s?this._valuesStartRepeat[e]+parseFloat(s):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();dA.nextId;var gA=pA;gA.getAll.bind(gA),gA.removeAll.bind(gA),gA.add.bind(gA),gA.remove.bind(gA),gA.update.bind(gA);function fA(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var yA="object"==typeof global&&global&&global.Object===Object&&global,bA="object"==typeof self&&self&&self.Object===Object&&self,_A=yA||bA||Function("return this")(),xA=function(){return _A.Date.now()},vA=/\s/;var TA=/^\s+/;function SA(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&vA.test(e.charAt(t)););return t}(e)+1).replace(TA,""):e}var wA=_A.Symbol,MA=Object.prototype,NA=MA.hasOwnProperty,EA=MA.toString,AA=wA?wA.toStringTag:void 0;var CA=Object.prototype.toString;var RA=wA?wA.toStringTag:void 0;function PA(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":RA&&RA in Object(e)?function(e){var t=NA.call(e,AA),s=e[AA];try{e[AA]=void 0;var i=!0}catch(e){}var r=EA.call(e);return i&&(t?e[AA]=s:delete e[AA]),r}(e):function(e){return CA.call(e)}(e)}var BA=/^[-+]0x[0-9a-f]+$/i,FA=/^0b[01]+$/i,DA=/^0o[0-7]+$/i,IA=parseInt;function LA(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return null!=e&&"object"==typeof e}(e)&&"[object Symbol]"==PA(e)}(e))return NaN;if(fA(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=fA(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=SA(e);var s=FA.test(e);return s||DA.test(e)?IA(e.slice(2),s?2:8):BA.test(e)?NaN:+e}var OA=Math.max,UA=Math.min;function kA(e,t,s){var i,r,n,a,o,h,u=0,l=!1,c=!1,d=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function p(t){var s=i,n=r;return i=r=void 0,u=t,a=e.apply(n,s)}function m(e){var s=e-h;return void 0===h||s>=t||s<0||c&&e-u>=n}function g(){var e=xA();if(m(e))return f(e);o=setTimeout(g,function(e){var s=t-(e-h);return c?UA(s,n-(e-u)):s}(e))}function f(e){return o=void 0,d&&i?p(e):(i=r=void 0,a)}function y(){var e=xA(),s=m(e);if(i=arguments,r=this,h=e,s){if(void 0===o)return function(e){return u=e,o=setTimeout(g,t),l?p(e):a}(h);if(c)return clearTimeout(o),o=setTimeout(g,t),p(h)}return void 0===o&&(o=setTimeout(g,t)),a}return t=LA(t)||0,fA(s)&&(l=!!s.leading,n=(c="maxWait"in s)?OA(LA(s.maxWait)||0,t):n,d="trailing"in s?!!s.trailing:d),y.cancel=function(){void 0!==o&&clearTimeout(o),u=0,i=h=r=o=void 0},y.flush=function(){return void 0===o?a:f(xA())},y}function zA(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function VA(e,t,s){return Object.defineProperty(e,"prototype",{writable:!1}),e}function GA(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],h=!0,u=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);h=!0);}catch(e){u=!0,r=e}finally{try{if(!h&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return zA(e,t);var s={}.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?zA(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var jA=VA(function e(t,s){var i=s.default,r=void 0===i?null:i,n=s.triggerUpdate,a=void 0===n||n,o=s.onChange,h=void 0===o?function(e,t){}:o;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name=t,this.defaultVal=r,this.triggerUpdate=a,this.onChange=h});function $A(e){var t=e.stateInit,s=void 0===t?function(){return{}}:t,i=e.props,r=void 0===i?{}:i,n=e.methods,a=void 0===n?{}:n,o=e.aliases,h=void 0===o?{}:o,u=e.init,l=void 0===u?function(){}:u,c=e.update,d=void 0===c?function(){}:c,p=Object.keys(r).map(function(e){return new jA(e,r[e])});return function e(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];var n=!!(this instanceof e?this.constructor:void 0),o=n?i.shift():void 0,u=i[0],c=void 0===u?{}:u,m=Object.assign({},s instanceof Function?s(c):s,{initialised:!1}),g={};function f(e){return y(e,c),b(),f}var y=function(e,t){l.call(f,e,m,t),m.initialised=!0},b=kA(function(){m.initialised&&(d.call(f,m,g),g={})},1);return p.forEach(function(e){f[e.name]=function(e){var t=e.name,s=e.triggerUpdate,i=void 0!==s&&s,r=e.onChange,n=void 0===r?function(e,t){}:r,a=e.defaultVal,o=void 0===a?null:a;return function(e){var s=m[t];if(!arguments.length)return s;var r=void 0===e?o:e;return m[t]=r,n.call(f,r,m,s),!g.hasOwnProperty(t)&&(g[t]=s),i&&b(),f}}(e)}),Object.keys(a).forEach(function(e){f[e]=function(){for(var t,s=arguments.length,i=new Array(s),r=0;r<s;r++)i[r]=arguments[r];return(t=a[e]).call.apply(t,[f,m].concat(i))}}),Object.entries(h).forEach(function(e){var t=GA(e,2),s=t[0],i=t[1];return f[s]=f[i]}),f.resetProps=function(){return p.forEach(function(e){f[e.name](e.defaultVal)}),f},f.resetProps(),m._rerender=b,n&&o&&f(o),f}}var WA="http://www.w3.org/1999/xhtml",HA={svg:"http://www.w3.org/2000/svg",xhtml:WA,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function qA(e){var t=e+="",s=t.indexOf(":");return s>=0&&"xmlns"!==(t=e.slice(0,s))&&(e=e.slice(s+1)),HA.hasOwnProperty(t)?{space:HA[t],local:e}:e}function XA(e){return function(){var t=this.ownerDocument,s=this.namespaceURI;return s===WA&&t.documentElement.namespaceURI===WA?t.createElement(e):t.createElementNS(s,e)}}function YA(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function KA(e){var t=qA(e);return(t.local?YA:XA)(t)}function QA(){}function ZA(e){return null==e?QA:function(){return this.querySelector(e)}}function JA(){return[]}function eC(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function tC(e){return function(t){return t.matches(e)}}var sC=Array.prototype.find;function iC(){return this.firstElementChild}var rC=Array.prototype.filter;function nC(){return Array.from(this.children)}function aC(e){return new Array(e.length)}function oC(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function hC(e,t,s,i,r,n){for(var a,o=0,h=t.length,u=n.length;o<u;++o)(a=t[o])?(a.__data__=n[o],i[o]=a):s[o]=new oC(e,n[o]);for(;o<h;++o)(a=t[o])&&(r[o]=a)}function uC(e,t,s,i,r,n,a){var o,h,u,l=new Map,c=t.length,d=n.length,p=new Array(c);for(o=0;o<c;++o)(h=t[o])&&(p[o]=u=a.call(h,h.__data__,o,t)+"",l.has(u)?r[o]=h:l.set(u,h));for(o=0;o<d;++o)u=a.call(e,n[o],o,n)+"",(h=l.get(u))?(i[o]=h,h.__data__=n[o],l.delete(u)):s[o]=new oC(e,n[o]);for(o=0;o<c;++o)(h=t[o])&&l.get(p[o])===h&&(r[o]=h)}function lC(e){return e.__data__}function cC(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function dC(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function pC(e){return function(){this.removeAttribute(e)}}function mC(e){return function(){this.removeAttributeNS(e.space,e.local)}}function gC(e,t){return function(){this.setAttribute(e,t)}}function fC(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function yC(e,t){return function(){var s=t.apply(this,arguments);null==s?this.removeAttribute(e):this.setAttribute(e,s)}}function bC(e,t){return function(){var s=t.apply(this,arguments);null==s?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,s)}}function _C(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function xC(e){return function(){this.style.removeProperty(e)}}function vC(e,t,s){return function(){this.style.setProperty(e,t,s)}}function TC(e,t,s){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,s)}}function SC(e){return function(){delete this[e]}}function wC(e,t){return function(){this[e]=t}}function MC(e,t){return function(){var s=t.apply(this,arguments);null==s?delete this[e]:this[e]=s}}function NC(e){return e.trim().split(/^|\s+/)}function EC(e){return e.classList||new AC(e)}function AC(e){this._node=e,this._names=NC(e.getAttribute("class")||"")}function CC(e,t){for(var s=EC(e),i=-1,r=t.length;++i<r;)s.add(t[i])}function RC(e,t){for(var s=EC(e),i=-1,r=t.length;++i<r;)s.remove(t[i])}function PC(e){return function(){CC(this,e)}}function BC(e){return function(){RC(this,e)}}function FC(e,t){return function(){(t.apply(this,arguments)?CC:RC)(this,e)}}function DC(){this.textContent=""}function IC(e){return function(){this.textContent=e}}function LC(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function OC(){this.innerHTML=""}function UC(e){return function(){this.innerHTML=e}}function kC(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function zC(){this.nextSibling&&this.parentNode.appendChild(this)}function VC(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function GC(){return null}function jC(){var e=this.parentNode;e&&e.removeChild(this)}function $C(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function WC(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function HC(e){return function(){var t=this.__on;if(t){for(var s,i=0,r=-1,n=t.length;i<n;++i)s=t[i],e.type&&s.type!==e.type||s.name!==e.name?t[++r]=s:this.removeEventListener(s.type,s.listener,s.options);++r?t.length=r:delete this.__on}}}function qC(e,t,s){return function(){var i,r=this.__on,n=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var a=0,o=r.length;a<o;++a)if((i=r[a]).type===e.type&&i.name===e.name)return this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=n,i.options=s),void(i.value=t);this.addEventListener(e.type,n,s),i={type:e.type,name:e.name,value:t,listener:n,options:s},r?r.push(i):this.__on=[i]}}function XC(e,t,s){var i=_C(e),r=i.CustomEvent;"function"==typeof r?r=new r(t,s):(r=i.document.createEvent("Event"),s?(r.initEvent(t,s.bubbles,s.cancelable),r.detail=s.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function YC(e,t){return function(){return XC(this,e,t)}}function KC(e,t){return function(){return XC(this,e,t.apply(this,arguments))}}oC.prototype={constructor:oC,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}},AC.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var QC=[null];function ZC(e,t){this._groups=e,this._parents=t}ZC.prototype={constructor:ZC,select:function(e){"function"!=typeof e&&(e=ZA(e));for(var t=this._groups,s=t.length,i=new Array(s),r=0;r<s;++r)for(var n,a,o=t[r],h=o.length,u=i[r]=new Array(h),l=0;l<h;++l)(n=o[l])&&(a=e.call(n,n.__data__,l,o))&&("__data__"in n&&(a.__data__=n.__data__),u[l]=a);return new ZC(i,this._parents)},selectAll:function(e){e="function"==typeof e?eC(e):function(e){return null==e?JA:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,s=t.length,i=[],r=[],n=0;n<s;++n)for(var a,o=t[n],h=o.length,u=0;u<h;++u)(a=o[u])&&(i.push(e.call(a,a.__data__,u,o)),r.push(a));return new ZC(i,r)},selectChild:function(e){return this.select(null==e?iC:function(e){return function(){return sC.call(this.children,e)}}("function"==typeof e?e:tC(e)))},selectChildren:function(e){return this.selectAll(null==e?nC:function(e){return function(){return rC.call(this.children,e)}}("function"==typeof e?e:tC(e)))},filter:function(e){"function"!=typeof e&&(e=function(e){return function(){return this.matches(e)}}(e));for(var t=this._groups,s=t.length,i=new Array(s),r=0;r<s;++r)for(var n,a=t[r],o=a.length,h=i[r]=[],u=0;u<o;++u)(n=a[u])&&e.call(n,n.__data__,u,a)&&h.push(n);return new ZC(i,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,lC);var s=t?uC:hC,i=this._parents,r=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var n=r.length,a=new Array(n),o=new Array(n),h=new Array(n),u=0;u<n;++u){var l=i[u],c=r[u],d=c.length,p=cC(e.call(l,l&&l.__data__,u,i)),m=p.length,g=o[u]=new Array(m),f=a[u]=new Array(m);s(l,c,g,f,h[u]=new Array(d),p,t);for(var y,b,_=0,x=0;_<m;++_)if(y=g[_]){for(_>=x&&(x=_+1);!(b=f[x])&&++x<m;);y._next=b||null}}return(a=new ZC(a,i))._enter=o,a._exit=h,a},enter:function(){return new ZC(this._enter||this._groups.map(aC),this._parents)},exit:function(){return new ZC(this._exit||this._groups.map(aC),this._parents)},join:function(e,t,s){var i=this.enter(),r=this,n=this.exit();return"function"==typeof e?(i=e(i))&&(i=i.selection()):i=i.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==s?n.remove():s(n),i&&r?i.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,s=this._groups,i=t._groups,r=s.length,n=i.length,a=Math.min(r,n),o=new Array(r),h=0;h<a;++h)for(var u,l=s[h],c=i[h],d=l.length,p=o[h]=new Array(d),m=0;m<d;++m)(u=l[m]||c[m])&&(p[m]=u);for(;h<r;++h)o[h]=s[h];return new ZC(o,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,s=e.length;++t<s;)for(var i,r=e[t],n=r.length-1,a=r[n];--n>=0;)(i=r[n])&&(a&&4^i.compareDocumentPosition(a)&&a.parentNode.insertBefore(i,a),a=i);return this},sort:function(e){function t(t,s){return t&&s?e(t.__data__,s.__data__):!t-!s}e||(e=dC);for(var s=this._groups,i=s.length,r=new Array(i),n=0;n<i;++n){for(var a,o=s[n],h=o.length,u=r[n]=new Array(h),l=0;l<h;++l)(a=o[l])&&(u[l]=a);u.sort(t)}return new ZC(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,s=e.length;t<s;++t)for(var i=e[t],r=0,n=i.length;r<n;++r){var a=i[r];if(a)return a}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,s=0,i=t.length;s<i;++s)for(var r,n=t[s],a=0,o=n.length;a<o;++a)(r=n[a])&&e.call(r,r.__data__,a,n);return this},attr:function(e,t){var s=qA(e);if(arguments.length<2){var i=this.node();return s.local?i.getAttributeNS(s.space,s.local):i.getAttribute(s)}return this.each((null==t?s.local?mC:pC:"function"==typeof t?s.local?bC:yC:s.local?fC:gC)(s,t))},style:function(e,t,s){return arguments.length>1?this.each((null==t?xC:"function"==typeof t?TC:vC)(e,t,null==s?"":s)):function(e,t){return e.style.getPropertyValue(t)||_C(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?SC:"function"==typeof t?MC:wC)(e,t)):this.node()[e]},classed:function(e,t){var s=NC(e+"");if(arguments.length<2){for(var i=EC(this.node()),r=-1,n=s.length;++r<n;)if(!i.contains(s[r]))return!1;return!0}return this.each(("function"==typeof t?FC:t?PC:BC)(s,t))},text:function(e){return arguments.length?this.each(null==e?DC:("function"==typeof e?LC:IC)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?OC:("function"==typeof e?kC:UC)(e)):this.node().innerHTML},raise:function(){return this.each(zC)},lower:function(){return this.each(VC)},append:function(e){var t="function"==typeof e?e:KA(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var s="function"==typeof e?e:KA(e),i=null==t?GC:"function"==typeof t?t:ZA(t);return this.select(function(){return this.insertBefore(s.apply(this,arguments),i.apply(this,arguments)||null)})},remove:function(){return this.each(jC)},clone:function(e){return this.select(e?WC:$C)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,s){var i,r,n=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",s=e.indexOf(".");return s>=0&&(t=e.slice(s+1),e=e.slice(0,s)),{type:e,name:t}})}(e+""),a=n.length;if(!(arguments.length<2)){for(o=t?qC:HC,i=0;i<a;++i)this.each(o(n[i],t,s));return this}var o=this.node().__on;if(o)for(var h,u=0,l=o.length;u<l;++u)for(i=0,h=o[u];i<a;++i)if((r=n[i]).type===h.type&&r.name===h.name)return h.value},dispatch:function(e,t){return this.each(("function"==typeof t?KC:YC)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,s=e.length;t<s;++t)for(var i,r=e[t],n=0,a=r.length;n<a;++n)(i=r[n])&&(yield i)}};var JC,eR,tR,sR,iR,rR,nR,aR,oR,hR,uR,lR,cR,dR,pR,mR={},gR=[],fR=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,yR=Array.isArray;function bR(e,t){for(var s in t)e[s]=t[s];return e}function _R(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function xR(e,t,s,i,r){var n={type:e,props:t,key:s,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++tR:r,__i:-1,__u:0};return null==r&&null!=eR.vnode&&eR.vnode(n),n}function vR(e){return e.children}function TR(e,t){this.props=e,this.context=t}function SR(e,t){if(null==t)return e.__?SR(e.__,e.__i+1):null;for(var s;t<e.__k.length;t++)if(null!=(s=e.__k[t])&&null!=s.__e)return s.__e;return"function"==typeof e.type?SR(e):null}function wR(e){if(e.__P&&e.__d){var t=e.__v,s=t.__e,i=[],r=[],n=bR({},t);n.__v=t.__v+1,eR.vnode&&eR.vnode(n),IR(e.__P,n,t,e.__n,e.__P.namespaceURI,32&t.__u?[s]:null,i,null==s?SR(t):s,!!(32&t.__u),r),n.__v=t.__v,n.__.__k[n.__i]=n,OR(i,n,r),t.__e=t.__=null,n.__e!=s&&MR(n)}}function MR(e){if(null!=(e=e.__)&&null!=e.__c)return e.__e=e.__c.base=null,e.__k.some(function(t){if(null!=t&&null!=t.__e)return e.__e=e.__c.base=t.__e}),MR(e)}function NR(e){(!e.__d&&(e.__d=!0)&&iR.push(e)&&!ER.__r++||rR!=eR.debounceRendering)&&((rR=eR.debounceRendering)||nR)(ER)}function ER(){try{for(var e,t=1;iR.length;)iR.length>t&&iR.sort(aR),e=iR.shift(),t=iR.length,wR(e)}finally{iR.length=ER.__r=0}}function AR(e,t,s,i,r,n,a,o,h,u,l){var c,d,p,m,g,f,y,b=i&&i.__k||gR,_=t.length;for(h=CR(s,t,b,h,_),c=0;c<_;c++)null!=(p=s.__k[c])&&(d=-1!=p.__i&&b[p.__i]||mR,p.__i=c,f=IR(e,p,d,r,n,a,o,h,u,l),m=p.__e,p.ref&&d.ref!=p.ref&&(d.ref&&zR(d.ref,null,p),l.push(p.ref,p.__c||m,p)),null==g&&null!=m&&(g=m),(y=!!(4&p.__u))||d.__k===p.__k?(h=RR(p,h,e,y),y&&d.__e&&(d.__e=null)):"function"==typeof p.type&&void 0!==f?h=f:m&&(h=m.nextSibling),p.__u&=-7);return s.__e=g,h}function CR(e,t,s,i,r){var n,a,o,h,u,l=s.length,c=l,d=0;for(e.__k=new Array(r),n=0;n<r;n++)null!=(a=t[n])&&"boolean"!=typeof a&&"function"!=typeof a?("string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?a=e.__k[n]=xR(null,a,null,null,null):yR(a)?a=e.__k[n]=xR(vR,{children:a},null,null,null):void 0===a.constructor&&a.__b>0?a=e.__k[n]=xR(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[n]=a,h=n+d,a.__=e,a.__b=e.__b+1,o=null,-1!=(u=a.__i=PR(a,s,h,c))&&(c--,(o=s[u])&&(o.__u|=2)),null==o||null==o.__v?(-1==u&&(r>l?d--:r<l&&d++),"function"!=typeof a.type&&(a.__u|=4)):u!=h&&(u==h-1?d--:u==h+1?d++:(u>h?d--:d++,a.__u|=4))):e.__k[n]=null;if(c)for(n=0;n<l;n++)null!=(o=s[n])&&!(2&o.__u)&&(o.__e==i&&(i=SR(o)),VR(o,o));return i}function RR(e,t,s,i){var r,n;if("function"==typeof e.type){for(r=e.__k,n=0;r&&n<r.length;n++)r[n]&&(r[n].__=e,t=RR(r[n],t,s,i));return t}e.__e!=t&&(i&&(t&&e.type&&!t.parentNode&&(t=SR(e)),s.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function PR(e,t,s,i){var r,n,a,o=e.key,h=e.type,u=t[s],l=null!=u&&!(2&u.__u);if(null===u&&null==o||l&&o==u.key&&h==u.type)return s;if(i>(l?1:0))for(r=s-1,n=s+1;r>=0||n<t.length;)if(null!=(u=t[a=r>=0?r--:n++])&&!(2&u.__u)&&o==u.key&&h==u.type)return a;return-1}function BR(e,t,s){"-"==t[0]?e.setProperty(t,null==s?"":s):e[t]=null==s?"":"number"!=typeof s||fR.test(t)?s:s+"px"}function FR(e,t,s,i,r){var n,a;e:if("style"==t)if("string"==typeof s)e.style.cssText=s;else{if("string"==typeof i&&(e.style.cssText=i=""),i)for(t in i)s&&t in s||BR(e.style,t,"");if(s)for(t in s)i&&s[t]==i[t]||BR(e.style,t,s[t])}else if("o"==t[0]&&"n"==t[1])n=t!=(t=t.replace(lR,"$1")),a=t.toLowerCase(),t=a in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+n]=s,s?i?s[uR]=i[uR]:(s[uR]=cR,e.addEventListener(t,n?pR:dR,n)):e.removeEventListener(t,n?pR:dR,n);else{if("http://www.w3.org/2000/svg"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==s?"":s;break e}catch(e){}"function"==typeof s||(null==s||!1===s&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==s?"":s))}}function DR(e){return function(t){if(this.l){var s=this.l[t.type+e];if(null==t[hR])t[hR]=cR++;else if(t[hR]<s[uR])return;return s(eR.event?eR.event(t):t)}}}function IR(e,t,s,i,r,n,a,o,h,u){var l,c,d,p,m,g,f,y,b,_,x,v,T,S,w,M=t.type;if(void 0!==t.constructor)return null;128&s.__u&&(h=!!(32&s.__u),n=[o=t.__e=s.__e]),(l=eR.__b)&&l(t);e:if("function"==typeof M)try{if(y=t.props,b=M.prototype&&M.prototype.render,_=(l=M.contextType)&&i[l.__c],x=l?_?_.props.value:l.__:i,s.__c?f=(c=t.__c=s.__c).__=c.__E:(b?t.__c=c=new M(y,x):(t.__c=c=new TR(y,x),c.constructor=M,c.render=GR),_&&_.sub(c),c.state||(c.state={}),c.__n=i,d=c.__d=!0,c.__h=[],c._sb=[]),b&&null==c.__s&&(c.__s=c.state),b&&null!=M.getDerivedStateFromProps&&(c.__s==c.state&&(c.__s=bR({},c.__s)),bR(c.__s,M.getDerivedStateFromProps(y,c.__s))),p=c.props,m=c.state,c.__v=t,d)b&&null==M.getDerivedStateFromProps&&null!=c.componentWillMount&&c.componentWillMount(),b&&null!=c.componentDidMount&&c.__h.push(c.componentDidMount);else{if(b&&null==M.getDerivedStateFromProps&&y!==p&&null!=c.componentWillReceiveProps&&c.componentWillReceiveProps(y,x),t.__v==s.__v||!c.__e&&null!=c.shouldComponentUpdate&&!1===c.shouldComponentUpdate(y,c.__s,x)){t.__v!=s.__v&&(c.props=y,c.state=c.__s,c.__d=!1),t.__e=s.__e,t.__k=s.__k,t.__k.some(function(e){e&&(e.__=t)}),gR.push.apply(c.__h,c._sb),c._sb=[],c.__h.length&&a.push(c);break e}null!=c.componentWillUpdate&&c.componentWillUpdate(y,c.__s,x),b&&null!=c.componentDidUpdate&&c.__h.push(function(){c.componentDidUpdate(p,m,g)})}if(c.context=x,c.props=y,c.__P=e,c.__e=!1,v=eR.__r,T=0,b)c.state=c.__s,c.__d=!1,v&&v(t),l=c.render(c.props,c.state,c.context),gR.push.apply(c.__h,c._sb),c._sb=[];else do{c.__d=!1,v&&v(t),l=c.render(c.props,c.state,c.context),c.state=c.__s}while(c.__d&&++T<25);c.state=c.__s,null!=c.getChildContext&&(i=bR(bR({},i),c.getChildContext())),b&&!d&&null!=c.getSnapshotBeforeUpdate&&(g=c.getSnapshotBeforeUpdate(p,m)),S=null!=l&&l.type===vR&&null==l.key?UR(l.props.children):l,o=AR(e,yR(S)?S:[S],t,s,i,r,n,a,o,h,u),c.base=t.__e,t.__u&=-161,c.__h.length&&a.push(c),f&&(c.__E=c.__=null)}catch(e){if(t.__v=null,h||null!=n)if(e.then){for(t.__u|=h?160:128;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;n[n.indexOf(o)]=null,t.__e=o}else{for(w=n.length;w--;)_R(n[w]);LR(t)}else t.__e=s.__e,t.__k=s.__k,e.then||LR(t);eR.__e(e,t,s)}else null==n&&t.__v==s.__v?(t.__k=s.__k,t.__e=s.__e):o=t.__e=kR(s.__e,t,s,i,r,n,a,h,u);return(l=eR.diffed)&&l(t),128&t.__u?void 0:o}function LR(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(LR))}function OR(e,t,s){for(var i=0;i<s.length;i++)zR(s[i],s[++i],s[++i]);eR.__c&&eR.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){eR.__e(e,t.__v)}})}function UR(e){return"object"!=typeof e||null==e||e.__b>0?e:yR(e)?e.map(UR):bR({},e)}function kR(e,t,s,i,r,n,a,o,h){var u,l,c,d,p,m,g,f=s.props||mR,y=t.props,b=t.type;if("svg"==b?r="http://www.w3.org/2000/svg":"math"==b?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=n)for(u=0;u<n.length;u++)if((p=n[u])&&"setAttribute"in p==!!b&&(b?p.localName==b:3==p.nodeType)){e=p,n[u]=null;break}if(null==e){if(null==b)return document.createTextNode(y);e=document.createElementNS(r,b,y.is&&y),o&&(eR.__m&&eR.__m(t,n),o=!1),n=null}if(null==b)f===y||o&&e.data==y||(e.data=y);else{if(n=n&&JC.call(e.childNodes),!o&&null!=n)for(f={},u=0;u<e.attributes.length;u++)f[(p=e.attributes[u]).name]=p.value;for(u in f)p=f[u],"dangerouslySetInnerHTML"==u?c=p:"children"==u||u in y||"value"==u&&"defaultValue"in y||"checked"==u&&"defaultChecked"in y||FR(e,u,null,p,r);for(u in y)p=y[u],"children"==u?d=p:"dangerouslySetInnerHTML"==u?l=p:"value"==u?m=p:"checked"==u?g=p:o&&"function"!=typeof p||f[u]===p||FR(e,u,p,f[u],r);if(l)o||c&&(l.__html==c.__html||l.__html==e.innerHTML)||(e.innerHTML=l.__html),t.__k=[];else if(c&&(e.innerHTML=""),AR("template"==t.type?e.content:e,yR(d)?d:[d],t,s,i,"foreignObject"==b?"http://www.w3.org/1999/xhtml":r,n,a,n?n[0]:s.__k&&SR(s,0),o,h),null!=n)for(u=n.length;u--;)_R(n[u]);o||(u="value","progress"==b&&null==m?e.removeAttribute("value"):null!=m&&(m!==e[u]||"progress"==b&&!m||"option"==b&&m!=f[u])&&FR(e,u,m,f[u],r),u="checked",null!=g&&g!=e[u]&&FR(e,u,g,f[u],r))}return e}function zR(e,t,s){try{if("function"==typeof e){var i="function"==typeof e.__u;i&&e.__u(),i&&null==t||(e.__u=e(t))}else e.current=t}catch(e){eR.__e(e,s)}}function VR(e,t,s){var i,r;if(eR.unmount&&eR.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||zR(i,null,t)),null!=(i=e.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(e){eR.__e(e,t)}i.base=i.__P=null}if(i=e.__k)for(r=0;r<i.length;r++)i[r]&&VR(i[r],t,s||"function"!=typeof e.type);s||_R(e.__e),e.__c=e.__=e.__e=void 0}function GR(e,t,s){return this.constructor(e,s)}function jR(e,t,s){var i,r,n;t==document&&(t=document.documentElement),eR.__&&eR.__(e,t),i=!1?null:t.__k,r=[],n=[],IR(t,e=t.__k=function(e,t,s){var i,r,n,a={};for(n in t)"key"==n?i=t[n]:"ref"==n?r=t[n]:a[n]=t[n];if(arguments.length>2&&(a.children=arguments.length>3?JC.call(arguments,2):s),"function"==typeof e&&null!=e.defaultProps)for(n in e.defaultProps)void 0===a[n]&&(a[n]=e.defaultProps[n]);return xR(e,a,i,r,null)}(vR,null,[e]),i||mR,mR,t.namespaceURI,i?null:t.firstChild?JC.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,n),OR(r,e,n)}function $R(e,t,s){var i,r,n,a,o=bR({},e.props);for(n in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==n?i=t[n]:"ref"==n?r=t[n]:o[n]=void 0===t[n]&&null!=a?a[n]:t[n];return arguments.length>2&&(o.children=arguments.length>3?JC.call(arguments,2):s),xR(e.type,o,i||e.key,r||e.ref,null)}function WR(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function HR(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function qR(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),s.push.apply(s,i)}return s}function XR(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],h=!0,u=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);h=!0);}catch(e){u=!0,r=e}finally{try{if(!h&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return WR(e,t);var s={}.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?WR(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function YR(e){return YR="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},YR(e)}JC=gR.slice,eR={__e:function(e,t,s,i){for(var r,n,a;t=t.__;)if((r=t.__c)&&!r.__)try{if((n=r.constructor)&&null!=n.getDerivedStateFromError&&(r.setState(n.getDerivedStateFromError(e)),a=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(e,i||{}),a=r.__d),a)return r.__E=r}catch(t){e=t}throw e}},tR=0,sR=function(e){return null!=e&&void 0===e.constructor},TR.prototype.setState=function(e,t){var s;s=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=bR({},this.state),"function"==typeof e&&(e=e(bR({},s),this.props)),e&&bR(s,e),null!=e&&this.__v&&(t&&this._sb.push(t),NR(this))},TR.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),NR(this))},TR.prototype.render=vR,iR=[],nR="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,aR=function(e,t){return e.__v.__b-t.__v.__b},ER.__r=0,oR=Math.random().toString(8),hR="__d"+oR,uR="__a"+oR,lR=/(PointerCapture)$|Capture$/i,cR=0,dR=DR(!1),pR=DR(!0);var KR=function(e){if("object"!==YR(e))return e;var t,s=$R(e);s.props&&(s.props=function(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?qR(Object(s),!0).forEach(function(t){HR(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):qR(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}({},s.props),null!=s&&null!==(t=s.props)&&void 0!==t&&t.children&&(s.props.children=Array.isArray(s.props.children)?s.props.children.map(KR):KR(s.props.children)));return s};!function(e,t){void 0===t&&(t={});var s=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===s&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".float-tooltip-kap {\n position: absolute;\n width: max-content; /* prevent shrinking near right edge */\n max-width: max(50%, 150px);\n padding: 3px 5px;\n border-radius: 3px;\n font: 12px sans-serif;\n color: #eee;\n background: rgba(0,0,0,0.6);\n pointer-events: none;\n}\n");var QR=$A({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(e,t){var s=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).style,i=void 0===s?{}:s,r=function(e){return"string"==typeof e?new ZC([[document.querySelector(e)]],[document.documentElement]):new ZC([[e]],QC)}(!!e&&"object"===YR(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===r.style("position")&&r.style("position","relative"),t.tooltipEl=r.append("div").attr("class","float-tooltip-kap"),Object.entries(i).forEach(function(e){var s=XR(e,2),i=s[0],r=s[1];return t.tooltipEl.style(i,r)}),t.tooltipEl.style("left","-10000px").style("display","none");var n="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,r.on("mousemove.".concat(n),function(e){t.mouseInside=!0;var s=function(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var s=t.ownerSVGElement||t;if(s.createSVGPoint){var i=s.createSVGPoint();return i.x=e.clientX,i.y=e.clientY,[(i=i.matrixTransform(t.getScreenCTM().inverse())).x,i.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),i=r.node(),n=i.offsetWidth,a=i.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(s[0]/n*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-s[1]<100?"calc(-100% - 6px)":"21px":"number"==typeof t.offsetY?t.offsetY<0?"calc(-100% - ".concat(Math.abs(t.offsetY),"px)"):"".concat(t.offsetY,"px"):t.offsetY];t.tooltipEl.style("left",s[0]+"px").style("top",s[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseover.".concat(n),function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseout.".concat(n),function(){t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){var t,s;e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append(function(){return e.content})):"string"==typeof e.content?e.tooltipEl.html(e.content):!function(e){return sR($R(e))}(e.content)?(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):(e.tooltipEl.text(""),t=e.content,delete(s=e.tooltipEl.node()).__k,jR(KR(t),s)):e.tooltipEl.text("")}}),ZR=function(e){e instanceof Array?e.forEach(ZR):(e.map&&e.map.dispose(),e.dispose())},JR=function(e){e.geometry&&e.geometry.dispose(),e.material&&ZR(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(JR)},eP=window.THREE?window.THREE:{WebGLRenderer:e.WebGLRenderer,Scene:e.Scene,PerspectiveCamera:e.PerspectiveCamera,Raycaster:e.Raycaster,SRGBColorSpace:e.SRGBColorSpace,TextureLoader:e.TextureLoader,Vector2:e.Vector2,Vector3:e.Vector3,Box3:e.Box3,Color:e.Color,Mesh:e.Mesh,SphereGeometry:e.SphereGeometry,MeshBasicMaterial:e.MeshBasicMaterial,BackSide:e.BackSide,Timer:e.Timer},tP=$A({props:{width:{default:window.innerWidth,onChange:function(e,t,s){isNaN(e)&&(t.width=s)}},height:{default:window.innerHeight,onChange:function(e,t,s){isNaN(e)&&(t.height=s)}},viewOffset:{default:[0,0]},backgroundColor:{default:"#000011"},backgroundImageUrl:{},onBackgroundImageLoaded:{},showNavInfo:{default:!0},skyRadius:{default:5e4},objects:{default:[]},lights:{default:[]},enablePointerInteraction:{default:!0,onChange:function(e,t){t.hoverObj=null,t.tooltip&&t.tooltip.content(null)},triggerUpdate:!1},pointerRaycasterThrottleMs:{default:50,triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},pointsHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{triggerUpdate:!1},hoverFilter:{default:function(){return!0},triggerUpdate:!1},tooltipContent:{triggerUpdate:!1},hoverDuringDrag:{default:!1,triggerUpdate:!1},clickAfterDrag:{default:!1,triggerUpdate:!1},onHover:{default:function(){},triggerUpdate:!1},onClick:{default:function(){},triggerUpdate:!1},onRightClick:{triggerUpdate:!1}},methods:{tick:function(e){if(e.initialised){e.controls.enabled&&e.controls.update&&e.controls.update(Math.min(1,e.timer.update().getDelta())),e.postProcessingComposer?e.postProcessingComposer.render():e.renderer.render(e.scene,e.camera),e.extraRenderers.forEach(function(t){return t.render(e.scene,e.camera)});var t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;var s=null;if(e.hoverDuringDrag||!e.isPointerDragging){var i=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&i.sort(function(t,s){return e.hoverOrderComparator(t.object,s.object)});var r=i.find(function(t){return e.hoverFilter(t.object)})||null;s=r?r.object:null,e.intersection=r||null}s!==e.hoverObj&&(e.onHover(s,e.hoverObj,e.intersection),e.tooltip.content(s&&function(e){return"function"==typeof e?e:"string"==typeof e?function(t){return t[e]}:function(t){return e}}(e.tooltipContent)(s,e.intersection)||null),e.hoverObj=s)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos;return{x:t.x,y:t.y}},cameraPosition:function(e,t,s,i){var r=e.camera;if(t&&e.initialised){var n=t,a=s||{x:0,y:0,z:0};if(i){var o=Object.assign({},r.position),h=c();e.tweenGroup.add(new mA(o).to(n,i).easing(hA.Quadratic.Out).onUpdate(u).onComplete(function(){e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(new mA(h).to(a,i/3).easing(hA.Quadratic.Out).onUpdate(l).onComplete(function(){e.tweenGroup.remove(this)}).start())}else u(n),l(a);return this}return Object.assign({},r.position,{lookAt:c()});function u(e){var t=e.x,s=e.y,i=e.z;void 0!==t&&(r.position.x=t),void 0!==s&&(r.position.y=s),void 0!==i&&(r.position.z=i)}function l(t){var s=new eP.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=s:r.lookAt(s)}function c(){return Object.assign(new eP.Vector3(0,0,-1e3).applyQuaternion(r.quaternion).add(r.position))}},zoomToFit:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10,i=arguments.length,r=new Array(i>3?i-3:0),n=3;n<i;n++)r[n-3]=arguments[n];return this.fitToBbox(this.getBbox.apply(this,r),t,s)},fitToBbox:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:10,a=e.camera;if(t){var o=new eP.Vector3(0,0,0),h=2*Math.max.apply(Math,r(Object.entries(t).map(function(e){var t=i(e,2),s=t[0],n=t[1];return Math.max.apply(Math,r(n.map(function(e){return Math.abs(o[s]-e)})))}))),u=(1-2*n/e.height)*a.fov,l=h/Math.atan(u*Math.PI/180),c=l/a.aspect,d=Math.max(l,c);if(d>0){var p=o.clone().sub(a.position).normalize().multiplyScalar(-d);this.cameraPosition(p,o,s)}}return this},getBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0},i=new eP.Box3(new eP.Vector3(0,0,0),new eP.Vector3(0,0,0)),n=e.objects.filter(t);return n.length?(n.forEach(function(e){return i.expandByObject(e)}),Object.assign.apply(Object,r(["x","y","z"].map(function(e){return s({},e,[i.min[e],i.max[e]])})))):null},getScreenCoords:function(e,t,s,i){var r=new eP.Vector3(t,s,i);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,s){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=new eP.Vector2(t/e.width*2-1,-s/e.height*2+1),n=new eP.Raycaster;return n.setFromCamera(r,e.camera),Object.assign({},n.ray.at(i,new eP.Vector3))},intersectingObjects:function(e,t,s){var i=new eP.Vector2(t/e.width*2-1,-s/e.height*2+1),r=new eP.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(i,e.camera),r.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls},_destructor:function(e){var t,s,i;!function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),JR(t)}}(e.scene),null===(t=e.controls)||void 0===t||t.dispose(),null===(s=e.renderer)||void 0===s||s.dispose(),null===(i=e.postProcessingComposer)||void 0===i||i.dispose()}},stateInit:function(){return{scene:new eP.Scene,camera:new eP.PerspectiveCamera,timer:new eP.Timer,tweenGroup:new lA,lastRaycasterCheck:0}},init:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=s.controlType,n=void 0===i?"trackball":i,a=s.useWebGPU,o=void 0!==a&&a,h=s.rendererConfig,u=void 0===h?{}:h,l=s.extraRenderers,c=void 0===l?[]:l,d=s.waitForLoadComplete,p=void 0===d||d;e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[n]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new QR(t.container),t.pointerPos=new eP.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(e){return t.container.addEventListener(e,function(s){if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===s.type&&(s.pressure>0||t.isPointerPressed)&&("mouse"===s.pointerType||void 0===s.movementX||[s.movementX,s.movementY].some(function(e){return Math.abs(e)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var i=(r=t.container,n=r.getBoundingClientRect(),a=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,{top:n.top+o,left:n.left+a});t.pointerPos.x=s.pageX-i.left,t.pointerPos.y=s.pageY-i.top}var r,n,a,o},{passive:!0})}),t.container.addEventListener("pointerup",function(e){t.isPointerPressed&&(t.isPointerPressed=!1,t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag)||requestAnimationFrame(function(){0===e.button&&t.onClick(t.hoverObj||null,e,t.intersection),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",function(e){t.onRightClick&&e.preventDefault()}),t.renderer=new(o?WM:eP.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},u)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=c,t.extraRenderers.forEach(function(e){e.domElement.style.position="absolute",e.domElement.style.top="0px",e.domElement.style.pointerEvents="none",t.container.appendChild(e.domElement)}),t.postProcessingComposer=new SE(t.renderer),t.postProcessingComposer.addPass(new wE(t.scene,t.camera)),t.controls=new{trackball:dN,orbit:$N,fly:aE}[n](t.camera,t.renderer.domElement),"fly"===n&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==n&&"orbit"!==n||(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",function(){t.controlsEngaged=!0}),t.controls.addEventListener("change",function(){t.controlsEngaged&&(t.controlsDragging=!0)}),t.controls.addEventListener("end",function(){t.controlsEngaged=!1,t.controlsDragging=!1})),[t.renderer,t.postProcessingComposer].concat(r(t.extraRenderers)).forEach(function(e){return e.setSize(t.width,t.height)}),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new eP.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!p,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var s,i=e.width,n=e.height;e.container.style.width="".concat(i,"px"),e.container.style.height="".concat(n,"px"),[e.renderer,e.postProcessingComposer].concat(r(e.extraRenderers)).forEach(function(e){return e.setSize(i,n)}),e.camera.aspect=i/n;var a=e.viewOffset.slice(0,2);a.some(function(e){return e})&&(s=e.camera).setViewOffset.apply(s,[i,n].concat(r(a),[i,n])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var o,h=e.width,u=e.height,l=e.viewOffset.slice(0,2);l.some(function(e){return e})?(o=e.camera).setViewOffset.apply(o,[h,u].concat(r(l),[h,u])):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=2.5*e.skyRadius,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new eP.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=WE(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new eP.Color(oA(1,e.backgroundColor)),c)}function d(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new eP.TextureLoader).load(e.backgroundImageUrl,function(t){t.colorSpace=eP.SRGBColorSpace,e.skysphere.material=new eP.MeshBasicMaterial({map:t,side:eP.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&d()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&d())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(function(t){return e.scene.remove(t)}),e.lights.forEach(function(t){return e.scene.add(t)})),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(function(t){return e.scene.remove(t)}),e.objects.forEach(function(t){return e.scene.add(t)}))}});return tP});
1
+ // Version 1.42.0 three-render-objects - https://github.com/vasturiano/three-render-objects
2
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("three")):"function"==typeof define&&define.amd?define(["three"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).ThreeRenderObjects=t(e.THREE)}(this,function(e){"use strict";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function s(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function i(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],h=!0,l=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);h=!0);}catch(e){l=!0,r=e}finally{try{if(!h&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(l)throw r}}return o}}(e,t)||n(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e){return function(e){if(Array.isArray(e))return t(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||n(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(e,s){if(e){if("string"==typeof e)return t(e,s);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(e,s):void 0}}!function(e,t){void 0===t&&(t={});var s=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===s&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".scene-nav-info {\n position: absolute;\n bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n font-family: sans-serif;\n pointer-events: none;\n user-select: none;\n}\n\n.scene-container canvas:focus {\n outline: none;\n}");const a="184",o=0,h=1,l=2,u=100,c=101,d=102,p=200,m=201,g=202,f=203,y=204,b=205,_=206,x=207,v=208,T=209,S=210,w=0,M=1,N=2,A=3,E=4,R=5,C=6,P=7,B=301,F=302,L=1e3,D=1001,I=1002,O=1003,U=1004,k=1005,z=1006,V=1007,G=1008,j=1009,$=1010,W=1011,H=1012,q=1013,X=1014,Y=1015,K=1016,Q=1017,Z=1018,J=1020,ee=35902,te=35899,se=1021,ie=1022,re=1023,ne=1026,ae=1027,oe=1028,he=1029,le=1030,ue=1031,ce=1033,de=33776,pe=33777,me=33778,ge=33779,fe=35840,ye=35841,be=35842,_e=35843,xe=36196,ve=37492,Te=37496,Se=37488,we=37489,Me=37490,Ne=37491,Ae=37808,Ee=37809,Re=37810,Ce=37811,Pe=37812,Be=37813,Fe=37814,Le=37815,De=37816,Ie=37817,Oe=37818,Ue=37819,ke=37820,ze=37821,Ve=36492,Ge=36283,je=36284,$e=36285,We=36286,He="",qe="srgb",Xe="srgb-linear",Ye="linear",Ke="srgb",Qe=7680,Ze=512,Je=513,et=514,tt=515,st=516,it=517,rt=518,nt=519,at=35044,ot=35048,ht=2e3,lt=2001,ut="compute",ct="render",dt="depthTextureCompare";function pt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function mt(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const gt={};function ft(...e){const t="THREE."+e.shift();console.log(t,...e)}function yt(e){const t=e[0];if("string"==typeof t&&t.startsWith("TSL:")){const t=e[1];t&&t.isStackTrace?e[0]+=" "+t.getLocation():e[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return e}function bt(...e){const t="THREE."+(e=yt(e)).shift();{const s=e[0];s&&s.isStackTrace?console.warn(s.getError(t)):console.warn(t,...e)}}function _t(...e){const t="THREE."+(e=yt(e)).shift();{const s=e[0];s&&s.isStackTrace?console.error(s.getError(t)):console.error(t,...e)}}function xt(...e){const t=e.join(" ");t in gt||(gt[t]=!0,bt(...e))}function vt(){return"undefined"!=typeof self&&void 0!==self.scheduler&&void 0!==self.scheduler.yield?self.scheduler.yield():new Promise(e=>{requestAnimationFrame(e)})}const Tt={[w]:1,[N]:6,[E]:7,[A]:5,[M]:0,[C]:2,[P]:4,[R]:3};class St{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const s=this._listeners;void 0===s[e]&&(s[e]=[]),-1===s[e].indexOf(t)&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return void 0!==s&&(void 0!==s[e]&&-1!==s[e].indexOf(t))}removeEventListener(e,t){const s=this._listeners;if(void 0===s)return;const i=s[e];if(void 0!==i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}dispatchEvent(e){const t=this._listeners;if(void 0===t)return;const s=t[e.type];if(void 0!==s){e.target=this;const t=s.slice(0);for(let s=0,i=t.length;s<i;s++)t[s].call(this,e);e.target=null}}}const wt=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let Mt=1234567;const Nt=Math.PI/180,At=180/Math.PI;function Et(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(wt[255&e]+wt[e>>8&255]+wt[e>>16&255]+wt[e>>24&255]+"-"+wt[255&t]+wt[t>>8&255]+"-"+wt[t>>16&15|64]+wt[t>>24&255]+"-"+wt[63&s|128]+wt[s>>8&255]+"-"+wt[s>>16&255]+wt[s>>24&255]+wt[255&i]+wt[i>>8&255]+wt[i>>16&255]+wt[i>>24&255]).toLowerCase()}function Rt(e,t,s){return Math.max(t,Math.min(s,e))}function Ct(e,t){return(e%t+t)%t}function Pt(e,t,s){return(1-s)*e+s*t}function Bt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function Ft(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const Lt={DEG2RAD:Nt,RAD2DEG:At,generateUUID:Et,clamp:Rt,euclideanModulo:Ct,mapLinear:function(e,t,s,i,r){return i+(e-t)*(r-i)/(s-t)},inverseLerp:function(e,t,s){return e!==t?(s-e)/(t-e):0},lerp:Pt,damp:function(e,t,s,i){return Pt(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(Ct(e,2*t)-t)},smoothstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*(3-2*e)},smootherstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Mt=e);let t=Mt+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*Nt},radToDeg:function(e){return e*At},isPowerOfTwo:function(e){return!(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,s,i,r){const n=Math.cos,a=Math.sin,o=n(s/2),h=a(s/2),l=n((t+i)/2),u=a((t+i)/2),c=n((t-i)/2),d=a((t-i)/2),p=n((i-t)/2),m=a((i-t)/2);switch(r){case"XYX":e.set(o*u,h*c,h*d,o*l);break;case"YZY":e.set(h*d,o*u,h*c,o*l);break;case"ZXZ":e.set(h*c,h*d,o*u,o*l);break;case"XZX":e.set(o*u,h*m,h*p,o*l);break;case"YXY":e.set(h*p,o*u,h*m,o*l);break;case"ZYZ":e.set(h*m,h*p,o*u,o*l);break;default:bt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Ft,denormalize:Bt};class Dt{static{Dt.prototype.isVector2=!0}constructor(e=0,t=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,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Rt(this.x,e.x,t.x),this.y=Rt(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Rt(this.x,e,t),this.y=Rt(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Rt(s,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(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Rt(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,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 s=Math.cos(t),i=Math.sin(t),r=this.x-e.x,n=this.y-e.y;return this.x=r*s-n*i+e.x,this.y=r*i+n*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class It{constructor(e=0,t=0,s=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=s,this._w=i}static slerpFlat(e,t,s,i,r,n,a){let o=s[i+0],h=s[i+1],l=s[i+2],u=s[i+3],c=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(u!==m||o!==c||h!==d||l!==p){let e=o*c+h*d+l*p+u*m;e<0&&(c=-c,d=-d,p=-p,m=-m,e=-e);let t=1-a;if(e<.9995){const s=Math.acos(e),i=Math.sin(s);t=Math.sin(t*s)/i,o=o*t+c*(a=Math.sin(a*s)/i),h=h*t+d*a,l=l*t+p*a,u=u*t+m*a}else{o=o*t+c*a,h=h*t+d*a,l=l*t+p*a,u=u*t+m*a;const e=1/Math.sqrt(o*o+h*h+l*l+u*u);o*=e,h*=e,l*=e,u*=e}}e[t]=o,e[t+1]=h,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,s,i,r,n){const a=s[i],o=s[i+1],h=s[i+2],l=s[i+3],u=r[n],c=r[n+1],d=r[n+2],p=r[n+3];return e[t]=a*p+l*u+o*d-h*c,e[t+1]=o*p+l*c+h*u-a*d,e[t+2]=h*p+l*d+a*c-o*u,e[t+3]=l*p-a*u-o*c-h*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,i=e._y,r=e._z,n=e._order,a=Math.cos,o=Math.sin,h=a(s/2),l=a(i/2),u=a(r/2),c=o(s/2),d=o(i/2),p=o(r/2);switch(n){case"XYZ":this._x=c*l*u+h*d*p,this._y=h*d*u-c*l*p,this._z=h*l*p+c*d*u,this._w=h*l*u-c*d*p;break;case"YXZ":this._x=c*l*u+h*d*p,this._y=h*d*u-c*l*p,this._z=h*l*p-c*d*u,this._w=h*l*u+c*d*p;break;case"ZXY":this._x=c*l*u-h*d*p,this._y=h*d*u+c*l*p,this._z=h*l*p+c*d*u,this._w=h*l*u-c*d*p;break;case"ZYX":this._x=c*l*u-h*d*p,this._y=h*d*u+c*l*p,this._z=h*l*p-c*d*u,this._w=h*l*u+c*d*p;break;case"YZX":this._x=c*l*u+h*d*p,this._y=h*d*u+c*l*p,this._z=h*l*p-c*d*u,this._w=h*l*u-c*d*p;break;case"XZY":this._x=c*l*u-h*d*p,this._y=h*d*u-c*l*p,this._z=h*l*p+c*d*u,this._w=h*l*u+c*d*p;break;default:bt("Quaternion: .setFromEuler() encountered an unknown order: "+n)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],r=t[8],n=t[1],a=t[5],o=t[9],h=t[2],l=t[6],u=t[10],c=s+a+u;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(l-o)*e,this._y=(r-h)*e,this._z=(n-i)*e}else if(s>a&&s>u){const e=2*Math.sqrt(1+s-a-u);this._w=(l-o)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+h)/e}else if(a>u){const e=2*Math.sqrt(1+a-s-u);this._w=(r-h)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(o+l)/e}else{const e=2*Math.sqrt(1+u-s-a);this._w=(n-i)/e,this._x=(r+h)/e,this._y=(o+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return s<1e-8?(s=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*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=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Rt(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(0===s)return this;const i=Math.min(1,t/s);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(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 s=e._x,i=e._y,r=e._z,n=e._w,a=t._x,o=t._y,h=t._z,l=t._w;return this._x=s*l+n*a+i*h-r*o,this._y=i*l+n*o+r*a-s*h,this._z=r*l+n*h+s*o-i*a,this._w=n*l-s*a-i*o-r*h,this._onChangeCallback(),this}slerp(e,t){let s=e._x,i=e._y,r=e._z,n=e._w,a=this.dot(e);a<0&&(s=-s,i=-i,r=-r,n=-n,a=-a);let o=1-t;if(a<.9995){const e=Math.acos(a),h=Math.sin(e);o=Math.sin(o*e)/h,t=Math.sin(t*e)/h,this._x=this._x*o+s*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+n*t,this._onChangeCallback()}else this._x=this._x*o+s*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+n*t,this.normalize();return this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),r=Math.sqrt(s);return this.set(i*Math.sin(e),i*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 Ot{static{Ot.prototype.isVector3=!0}constructor(e=0,t=0,s=0){this.x=e,this.y=t,this.z=s}set(e,t,s){return void 0===s&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,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(kt.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(kt.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*s+r[6]*i,this.y=r[1]*t+r[4]*s+r[7]*i,this.z=r[2]*t+r[5]*s+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=e.elements,n=1/(r[3]*t+r[7]*s+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*s+r[8]*i+r[12])*n,this.y=(r[1]*t+r[5]*s+r[9]*i+r[13])*n,this.z=(r[2]*t+r[6]*s+r[10]*i+r[14])*n,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,r=e.x,n=e.y,a=e.z,o=e.w,h=2*(n*i-a*s),l=2*(a*t-r*i),u=2*(r*s-n*t);return this.x=t+o*h+n*u-a*l,this.y=s+o*l+a*h-r*u,this.z=i+o*u+r*l-n*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,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i,this.y=r[1]*t+r[5]*s+r[9]*i,this.z=r[2]*t+r[6]*s+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Rt(this.x,e.x,t.x),this.y=Rt(this.y,e.y,t.y),this.z=Rt(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Rt(this.x,e,t),this.y=Rt(this.y,e,t),this.z=Rt(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Rt(s,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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,r=e.z,n=t.x,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*n-s*o,this.z=s*a-i*n,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return Ut.copy(this).projectOnVector(e),this.sub(Ut)}reflect(e){return this.sub(Ut.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(Rt(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,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(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ut=new Ot,kt=new It;class zt{static{zt.prototype.isMatrix3=!0}constructor(e,t,s,i,r,n,a,o,h){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,a,o,h)}set(e,t,s,i,r,n,a,o,h){const l=this.elements;return l[0]=e,l[1]=i,l[2]=a,l[3]=t,l[4]=r,l[5]=o,l[6]=s,l[7]=n,l[8]=h,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.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 s=e.elements,i=t.elements,r=this.elements,n=s[0],a=s[3],o=s[6],h=s[1],l=s[4],u=s[7],c=s[2],d=s[5],p=s[8],m=i[0],g=i[3],f=i[6],y=i[1],b=i[4],_=i[7],x=i[2],v=i[5],T=i[8];return r[0]=n*m+a*y+o*x,r[3]=n*g+a*b+o*v,r[6]=n*f+a*_+o*T,r[1]=h*m+l*y+u*x,r[4]=h*g+l*b+u*v,r[7]=h*f+l*_+u*T,r[2]=c*m+d*y+p*x,r[5]=c*g+d*b+p*v,r[8]=c*f+d*_+p*T,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],s=e[1],i=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],l=e[8];return t*n*l-t*a*h-s*r*l+s*a*o+i*r*h-i*n*o}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],l=e[8],u=l*n-a*h,c=a*o-l*r,d=h*r-n*o,p=t*u+s*c+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=u*m,e[1]=(i*h-l*s)*m,e[2]=(a*s-i*n)*m,e[3]=c*m,e[4]=(l*t-i*o)*m,e[5]=(i*r-a*t)*m,e[6]=d*m,e[7]=(s*o-h*t)*m,e[8]=(n*t-s*r)*m,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,s,i,r,n,a){const o=Math.cos(r),h=Math.sin(r);return this.set(s*o,s*h,-s*(o*n+h*a)+n+e,-i*h,i*o,-i*(-h*n+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Vt.makeScale(e,t)),this}rotate(e){return this.premultiply(Vt.makeRotation(-e)),this}translate(e,t){return this.premultiply(Vt.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),s=Math.sin(e);return this.set(t,-s,0,s,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,s=e.elements;for(let e=0;e<9;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const Vt=new zt,Gt=(new zt).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),jt=(new zt).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function $t(){const e={enabled:!0,workingColorSpace:Xe,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Ke&&(e.r=Ht(e.r),e.g=Ht(e.g),e.b=Ht(e.b)),this.spaces[t].primaries!==this.spaces[s].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===Ke&&(e.r=qt(e.r),e.g=qt(e.g),e.b=qt(e.b)),e):e},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===He?Ye:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,s){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,s){return xt("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,s)},toWorkingColorSpace:function(t,s){return xt("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(t,s)}},t=[.64,.33,.3,.6,.15,.06],s=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[Xe]:{primaries:t,whitePoint:i,transfer:Ye,toXYZ:Gt,fromXYZ:jt,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:qe},outputColorSpaceConfig:{drawingBufferColorSpace:qe}},[qe]:{primaries:t,whitePoint:i,transfer:Ke,toXYZ:Gt,fromXYZ:jt,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:qe}}}),e}const Wt=$t();function Ht(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function qt(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Xt;class Yt{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let s;if(e instanceof HTMLCanvasElement)s=e;else{void 0===Xt&&(Xt=mt("canvas")),Xt.width=e.width,Xt.height=e.height;const t=Xt.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),s=Xt}return s.toDataURL(t)}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=mt("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e<r.length;e++)r[e]=255*Ht(r[e]/255);return s.putImageData(i,0,0),t}if(e.data){const t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(255*Ht(t[e]/255)):t[e]=Ht(t[e]);return{data:t,width:e.width,height:e.height}}return bt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Kt=0;class Qt{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Kt++}),this.uuid=Et(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):null!==t?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){!0===e&&this.version++}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.images[this.uuid])return e.images[this.uuid];const s={uuid:this.uuid,url:""},i=this.data;if(null!==i){let e;if(Array.isArray(i)){e=[];for(let t=0,s=i.length;t<s;t++)i[t].isDataTexture?e.push(Zt(i[t].image)):e.push(Zt(i[t]))}else e=Zt(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function Zt(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?Yt.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(bt("Texture: Unable to serialize Texture."),{})}let Jt=0;const es=new Ot;class ts extends St{constructor(e=ts.DEFAULT_IMAGE,t=ts.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,a=1023,o=1009,h=ts.DEFAULT_ANISOTROPY,l=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Jt++}),this.uuid=Et(),this.name="",this.source=new Qt(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=s,this.wrapT=i,this.magFilter=r,this.minFilter=n,this.anisotropy=h,this.format=a,this.internalFormat=null,this.type=o,this.offset=new Dt(0,0),this.repeat=new Dt(1,1),this.center=new Dt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new zt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=l,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(es).x}get height(){return this.source.getSize(es).y}get depth(){return this.source.getSize(es).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,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.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const s=e[t];if(void 0===s){bt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&s&&i.isVector2&&s.isVector2||i&&s&&i.isVector3&&s.isVector3||i&&s&&i.isMatrix3&&s.isMatrix3?i.copy(s):this[t]=s:bt(`Texture.setValues(): property '${t}' does not exist.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.textures[this.uuid])return e.textures[this.uuid];const s={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(300!==this.mapping)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case L:e.x=e.x-Math.floor(e.x);break;case D:e.x=e.x<0?0:1;break;case I:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case L:e.y=e.y-Math.floor(e.y);break;case D:e.y=e.y<0?0:1;break;case I:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}ts.DEFAULT_IMAGE=null,ts.DEFAULT_MAPPING=300,ts.DEFAULT_ANISOTROPY=1;class ss{static{ss.prototype.isVector4=!0}constructor(e=0,t=0,s=0,i=1){this.x=e,this.y=t,this.z=s,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?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,s=this.y,i=this.z,r=this.w,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i+n[12]*r,this.y=n[1]*t+n[5]*s+n[9]*i+n[13]*r,this.z=n[2]*t+n[6]*s+n[10]*i+n[14]*r,this.w=n[3]*t+n[7]*s+n[11]*i+n[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,s,i,r;const n=.01,a=.1,o=e.elements,h=o[0],l=o[4],u=o[8],c=o[1],d=o[5],p=o[9],m=o[2],g=o[6],f=o[10];if(Math.abs(l-c)<n&&Math.abs(u-m)<n&&Math.abs(p-g)<n){if(Math.abs(l+c)<a&&Math.abs(u+m)<a&&Math.abs(p+g)<a&&Math.abs(h+d+f-3)<a)return this.set(1,0,0,0),this;t=Math.PI;const e=(h+1)/2,o=(d+1)/2,y=(f+1)/2,b=(l+c)/4,_=(u+m)/4,x=(p+g)/4;return e>o&&e>y?e<n?(s=0,i=.707106781,r=.707106781):(s=Math.sqrt(e),i=b/s,r=_/s):o>y?o<n?(s=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),s=b/i,r=x/i):y<n?(s=.707106781,i=.707106781,r=0):(r=Math.sqrt(y),s=_/r,i=x/r),this.set(s,i,r,t),this}let y=Math.sqrt((g-p)*(g-p)+(u-m)*(u-m)+(c-l)*(c-l));return Math.abs(y)<.001&&(y=1),this.x=(g-p)/y,this.y=(u-m)/y,this.z=(c-l)/y,this.w=Math.acos((h+d+f-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=Rt(this.x,e.x,t.x),this.y=Rt(this.y,e.y,t.y),this.z=Rt(this.z,e.z,t.z),this.w=Rt(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Rt(this.x,e,t),this.y=Rt(this.y,e,t),this.z=Rt(this.z,e,t),this.w=Rt(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Rt(s,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,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this.w=e.w+(t.w-e.w)*s,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,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 is extends St{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:z,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},s),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=s.depth,this.scissor=new ss(0,0,e,t),this.scissorTest=!1,this.viewport=new ss(0,0,e,t),this.textures=[];const i={width:e,height:t,depth:s.depth},r=new ts(i),n=s.count;for(let e=0;e<n;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(s),this.depthBuffer=s.depthBuffer,this.stencilBuffer=s.stencilBuffer,this.resolveDepthBuffer=s.resolveDepthBuffer,this.resolveStencilBuffer=s.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=s.depthTexture,this.samples=s.samples,this.multiview=s.multiview}_setTextureOptions(e={}){const t={minFilter:z,generateMipmaps:!1,flipY:!1,internalFormat:null};void 0!==e.mapping&&(t.mapping=e.mapping),void 0!==e.wrapS&&(t.wrapS=e.wrapS),void 0!==e.wrapT&&(t.wrapT=e.wrapT),void 0!==e.wrapR&&(t.wrapR=e.wrapR),void 0!==e.magFilter&&(t.magFilter=e.magFilter),void 0!==e.minFilter&&(t.minFilter=e.minFilter),void 0!==e.format&&(t.format=e.format),void 0!==e.type&&(t.type=e.type),void 0!==e.anisotropy&&(t.anisotropy=e.anisotropy),void 0!==e.colorSpace&&(t.colorSpace=e.colorSpace),void 0!==e.flipY&&(t.flipY=e.flipY),void 0!==e.generateMipmaps&&(t.generateMipmaps=e.generateMipmaps),void 0!==e.internalFormat&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++){this.textures[e].setValues(t)}}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){null!==this._depthTexture&&(this._depthTexture.renderTarget=null),null!==e&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,s=1){if(this.width!==e||this.height!==t||this.depth!==s){this.width=e,this.height=t,this.depth=s;for(let i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=s,!0!==this.textures[i].isData3DTexture&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return(new this.constructor).copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,s=e.textures.length;t<s;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new Qt(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,null!==e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this.multiview=e.multiview,this}dispose(){this.dispatchEvent({type:"dispose"})}}class rs extends ts{constructor(e=null,t=1,s=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:s,depth:i},this.magFilter=O,this.minFilter=O,this.wrapR=D,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class ns{static{ns.prototype.isMatrix4=!0}constructor(e,t,s,i,r,n,a,o,h,l,u,c,d,p,m,g){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,a,o,h,l,u,c,d,p,m,g)}set(e,t,s,i,r,n,a,o,h,l,u,c,d,p,m,g){const f=this.elements;return f[0]=e,f[4]=t,f[8]=s,f[12]=i,f[1]=r,f[5]=n,f[9]=a,f[13]=o,f[2]=h,f[6]=l,f[10]=u,f[14]=c,f[3]=d,f[7]=p,f[11]=m,f[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new ns).fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[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,s){return 0===this.determinant()?(e.set(1,0,0),t.set(0,1,0),s.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this)}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){if(0===e.determinant())return this.identity();const t=this.elements,s=e.elements,i=1/as.setFromMatrixColumn(e,0).length(),r=1/as.setFromMatrixColumn(e,1).length(),n=1/as.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*r,t[5]=s[5]*r,t[6]=s[6]*r,t[7]=0,t[8]=s[8]*n,t[9]=s[9]*n,t[10]=s[10]*n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,r=e.z,n=Math.cos(s),a=Math.sin(s),o=Math.cos(i),h=Math.sin(i),l=Math.cos(r),u=Math.sin(r);if("XYZ"===e.order){const e=n*l,s=n*u,i=a*l,r=a*u;t[0]=o*l,t[4]=-o*u,t[8]=h,t[1]=s+i*h,t[5]=e-r*h,t[9]=-a*o,t[2]=r-e*h,t[6]=i+s*h,t[10]=n*o}else if("YXZ"===e.order){const e=o*l,s=o*u,i=h*l,r=h*u;t[0]=e+r*a,t[4]=i*a-s,t[8]=n*h,t[1]=n*u,t[5]=n*l,t[9]=-a,t[2]=s*a-i,t[6]=r+e*a,t[10]=n*o}else if("ZXY"===e.order){const e=o*l,s=o*u,i=h*l,r=h*u;t[0]=e-r*a,t[4]=-n*u,t[8]=i+s*a,t[1]=s+i*a,t[5]=n*l,t[9]=r-e*a,t[2]=-n*h,t[6]=a,t[10]=n*o}else if("ZYX"===e.order){const e=n*l,s=n*u,i=a*l,r=a*u;t[0]=o*l,t[4]=i*h-s,t[8]=e*h+r,t[1]=o*u,t[5]=r*h+e,t[9]=s*h-i,t[2]=-h,t[6]=a*o,t[10]=n*o}else if("YZX"===e.order){const e=n*o,s=n*h,i=a*o,r=a*h;t[0]=o*l,t[4]=r-e*u,t[8]=i*u+s,t[1]=u,t[5]=n*l,t[9]=-a*l,t[2]=-h*l,t[6]=s*u+i,t[10]=e-r*u}else if("XZY"===e.order){const e=n*o,s=n*h,i=a*o,r=a*h;t[0]=o*l,t[4]=-u,t[8]=h*l,t[1]=e*u+r,t[5]=n*l,t[9]=s*u-i,t[2]=i*u-s,t[6]=a*l,t[10]=r*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(hs,e,ls)}lookAt(e,t,s){const i=this.elements;return ds.subVectors(e,t),0===ds.lengthSq()&&(ds.z=1),ds.normalize(),us.crossVectors(s,ds),0===us.lengthSq()&&(1===Math.abs(s.z)?ds.x+=1e-4:ds.z+=1e-4,ds.normalize(),us.crossVectors(s,ds)),us.normalize(),cs.crossVectors(ds,us),i[0]=us.x,i[4]=cs.x,i[8]=ds.x,i[1]=us.y,i[5]=cs.y,i[9]=ds.y,i[2]=us.z,i[6]=cs.z,i[10]=ds.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],a=s[4],o=s[8],h=s[12],l=s[1],u=s[5],c=s[9],d=s[13],p=s[2],m=s[6],g=s[10],f=s[14],y=s[3],b=s[7],_=s[11],x=s[15],v=i[0],T=i[4],S=i[8],w=i[12],M=i[1],N=i[5],A=i[9],E=i[13],R=i[2],C=i[6],P=i[10],B=i[14],F=i[3],L=i[7],D=i[11],I=i[15];return r[0]=n*v+a*M+o*R+h*F,r[4]=n*T+a*N+o*C+h*L,r[8]=n*S+a*A+o*P+h*D,r[12]=n*w+a*E+o*B+h*I,r[1]=l*v+u*M+c*R+d*F,r[5]=l*T+u*N+c*C+d*L,r[9]=l*S+u*A+c*P+d*D,r[13]=l*w+u*E+c*B+d*I,r[2]=p*v+m*M+g*R+f*F,r[6]=p*T+m*N+g*C+f*L,r[10]=p*S+m*A+g*P+f*D,r[14]=p*w+m*E+g*B+f*I,r[3]=y*v+b*M+_*R+x*F,r[7]=y*T+b*N+_*C+x*L,r[11]=y*S+b*A+_*P+x*D,r[15]=y*w+b*E+_*B+x*I,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],s=e[4],i=e[8],r=e[12],n=e[1],a=e[5],o=e[9],h=e[13],l=e[2],u=e[6],c=e[10],d=e[14],p=e[3],m=e[7],g=e[11],f=e[15],y=o*d-h*c,b=a*d-h*u,_=a*c-o*u,x=n*d-h*l,v=n*c-o*l,T=n*u-a*l;return t*(m*y-g*b+f*_)-s*(p*y-g*x+f*v)+i*(p*b-m*x+f*T)-r*(p*_-m*v+g*T)}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,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],l=e[8],u=e[9],c=e[10],d=e[11],p=e[12],m=e[13],g=e[14],f=e[15],y=t*a-s*n,b=t*o-i*n,_=t*h-r*n,x=s*o-i*a,v=s*h-r*a,T=i*h-r*o,S=l*m-u*p,w=l*g-c*p,M=l*f-d*p,N=u*g-c*m,A=u*f-d*m,E=c*f-d*g,R=y*E-b*A+_*N+x*M-v*w+T*S;if(0===R)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const C=1/R;return e[0]=(a*E-o*A+h*N)*C,e[1]=(i*A-s*E-r*N)*C,e[2]=(m*T-g*v+f*x)*C,e[3]=(c*v-u*T-d*x)*C,e[4]=(o*M-n*E-h*w)*C,e[5]=(t*E-i*M+r*w)*C,e[6]=(g*_-p*T-f*b)*C,e[7]=(l*T-c*_+d*b)*C,e[8]=(n*A-a*M+h*S)*C,e[9]=(s*M-t*A-r*S)*C,e[10]=(p*v-m*_+f*y)*C,e[11]=(u*_-l*v-d*y)*C,e[12]=(a*w-n*N-o*S)*C,e[13]=(t*N-s*w+i*S)*C,e[14]=(m*b-p*x-g*y)*C,e[15]=(l*x-u*b+c*y)*C,this}scale(e){const t=this.elements,s=e.x,i=e.y,r=e.z;return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){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,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),r=1-s,n=e.x,a=e.y,o=e.z,h=r*n,l=r*a;return this.set(h*n+s,h*a-i*o,h*o+i*a,0,h*a+i*o,l*a+s,l*o-i*n,0,h*o-i*a,l*o+i*n,r*o*o+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,r,n){return this.set(1,s,r,0,e,1,n,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,r=t._x,n=t._y,a=t._z,o=t._w,h=r+r,l=n+n,u=a+a,c=r*h,d=r*l,p=r*u,m=n*l,g=n*u,f=a*u,y=o*h,b=o*l,_=o*u,x=s.x,v=s.y,T=s.z;return i[0]=(1-(m+f))*x,i[1]=(d+_)*x,i[2]=(p-b)*x,i[3]=0,i[4]=(d-_)*v,i[5]=(1-(c+f))*v,i[6]=(g+y)*v,i[7]=0,i[8]=(p+b)*T,i[9]=(g-y)*T,i[10]=(1-(c+m))*T,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;e.x=i[12],e.y=i[13],e.z=i[14];const r=this.determinant();if(0===r)return s.set(1,1,1),t.identity(),this;let n=as.set(i[0],i[1],i[2]).length();const a=as.set(i[4],i[5],i[6]).length(),o=as.set(i[8],i[9],i[10]).length();r<0&&(n=-n),os.copy(this);const h=1/n,l=1/a,u=1/o;return os.elements[0]*=h,os.elements[1]*=h,os.elements[2]*=h,os.elements[4]*=l,os.elements[5]*=l,os.elements[6]*=l,os.elements[8]*=u,os.elements[9]*=u,os.elements[10]*=u,t.setFromRotationMatrix(os),s.x=n,s.y=a,s.z=o,this}makePerspective(e,t,s,i,r,n,a=2e3,o=!1){const h=this.elements,l=2*r/(t-e),u=2*r/(s-i),c=(t+e)/(t-e),d=(s+i)/(s-i);let p,m;if(o)p=r/(n-r),m=n*r/(n-r);else if(a===ht)p=-(n+r)/(n-r),m=-2*n*r/(n-r);else{if(a!==lt)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);p=-n/(n-r),m=-n*r/(n-r)}return h[0]=l,h[4]=0,h[8]=c,h[12]=0,h[1]=0,h[5]=u,h[9]=d,h[13]=0,h[2]=0,h[6]=0,h[10]=p,h[14]=m,h[3]=0,h[7]=0,h[11]=-1,h[15]=0,this}makeOrthographic(e,t,s,i,r,n,a=2e3,o=!1){const h=this.elements,l=2/(t-e),u=2/(s-i),c=-(t+e)/(t-e),d=-(s+i)/(s-i);let p,m;if(o)p=1/(n-r),m=n/(n-r);else if(a===ht)p=-2/(n-r),m=-(n+r)/(n-r);else{if(a!==lt)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=-1/(n-r),m=-r/(n-r)}return h[0]=l,h[4]=0,h[8]=0,h[12]=c,h[1]=0,h[5]=u,h[9]=0,h[13]=d,h[2]=0,h[6]=0,h[10]=p,h[14]=m,h[3]=0,h[7]=0,h[11]=0,h[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<16;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const as=new Ot,os=new ns,hs=new Ot(0,0,0),ls=new Ot(1,1,1),us=new Ot,cs=new Ot,ds=new Ot,ps=new ns,ms=new It;class gs{constructor(e=0,t=0,s=0,i=gs.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const i=e.elements,r=i[0],n=i[4],a=i[8],o=i[1],h=i[5],l=i[9],u=i[2],c=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Rt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-l,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(c,h),this._z=0);break;case"YXZ":this._x=Math.asin(-Rt(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,h)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Rt(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(-u,d),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Rt(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(Rt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Rt(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,h),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-l,d),this._y=0);break;default:bt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return ps.makeRotationFromQuaternion(e),this.setFromRotationMatrix(ps,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ms.setFromEuler(this),this.setFromQuaternion(ms,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],void 0!==e[3]&&(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}}gs.DEFAULT_ORDER="XYZ";class fs{constructor(){this.mask=1}set(e){this.mask=1<<e>>>0}enable(e){this.mask|=1<<e}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e}disable(e){this.mask&=~(1<<e)}disableAll(){this.mask=0}test(e){return 0!==(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let ys=0;const bs=new Ot,_s=new It,xs=new ns,vs=new Ot,Ts=new Ot,Ss=new Ot,ws=new It,Ms=new Ot(1,0,0),Ns=new Ot(0,1,0),As=new Ot(0,0,1),Es={type:"added"},Rs={type:"removed"},Cs={type:"childadded",child:null},Ps={type:"childremoved",child:null};class Bs extends St{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:ys++}),this.uuid=Et(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Bs.DEFAULT_UP.clone();const e=new Ot,t=new gs,s=new It,i=new Ot(1,1,1);t._onChange(function(){s.setFromEuler(t,!1)}),s._onChange(function(){t.setFromQuaternion(s,void 0,!1)}),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:s},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new ns},normalMatrix:{value:new zt}}),this.matrix=new ns,this.matrixWorld=new ns,this.matrixAutoUpdate=Bs.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Bs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new fs,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return _s.setFromAxisAngle(e,t),this.quaternion.multiply(_s),this}rotateOnWorldAxis(e,t){return _s.setFromAxisAngle(e,t),this.quaternion.premultiply(_s),this}rotateX(e){return this.rotateOnAxis(Ms,e)}rotateY(e){return this.rotateOnAxis(Ns,e)}rotateZ(e){return this.rotateOnAxis(As,e)}translateOnAxis(e,t){return bs.copy(e).applyQuaternion(this.quaternion),this.position.add(bs.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Ms,e)}translateY(e){return this.translateOnAxis(Ns,e)}translateZ(e){return this.translateOnAxis(As,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(xs.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?vs.copy(e):vs.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),Ts.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?xs.lookAt(Ts,vs,this.up):xs.lookAt(vs,Ts,this.up),this.quaternion.setFromRotationMatrix(xs),i&&(xs.extractRotation(i.matrixWorld),_s.setFromRotationMatrix(xs),this.quaternion.premultiply(_s.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(_t("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Es),Cs.child=e,this.dispatchEvent(Cs),Cs.child=null):_t("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}const t=this.children.indexOf(e);return-1!==t&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(Rs),Ps.child=e,this.dispatchEvent(Ps),Ps.child=null),this}removeFromParent(){const e=this.parent;return null!==e&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),xs.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),xs.multiply(e.parent.matrixWorld)),e.applyMatrix4(xs),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Es),Cs.child=e,this.dispatchEvent(Cs),Cs.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let s=0,i=this.children.length;s<i;s++){const i=this.children[s].getObjectByProperty(e,t);if(void 0!==i)return i}}getObjectsByProperty(e,t,s=[]){this[e]===t&&s.push(this);const i=this.children;for(let r=0,n=i.length;r<n;r++)i[r].getObjectsByProperty(e,t,s);return s}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ts,e,Ss),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ts,ws,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverse(e)}traverseVisible(e){if(!1===this.visible)return;e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverseVisible(e)}traverseAncestors(e){const t=this.parent;null!==t&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(null!==e){const t=e.x,s=e.y,i=e.z,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*s-r[8]*i,r[13]+=s-r[1]*t-r[5]*s-r[9]*i,r[14]+=i-r[2]*t-r[6]*s-r[10]*i}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}updateWorldMatrix(e,t){const s=this.parent;if(!0===e&&null!==s&&s.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),!0===t){const e=this.children;for(let t=0,s=e.length;t<s;t++){e[t].updateWorldMatrix(!1,!0)}}}toJSON(e){const t=void 0===e||"string"==typeof e,s={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},s.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};function r(t,s){return void 0===t[s.uuid]&&(t[s.uuid]=s.toJSON(e)),s.uuid}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),!0===this.castShadow&&(i.castShadow=!0),!0===this.receiveShadow&&(i.receiveShadow=!0),!1===this.visible&&(i.visible=!1),!1===this.frustumCulled&&(i.frustumCulled=!1),0!==this.renderOrder&&(i.renderOrder=this.renderOrder),!1!==this.static&&(i.static=this.static),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),null!==this.pivot&&(i.pivot=this.pivot.toArray()),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),void 0!==this.morphTargetDictionary&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(e=>({...e})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(i.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const s=t.shapes;if(Array.isArray(s))for(let t=0,i=s.length;t<i;t++){const i=s[t];r(e.shapes,i)}else r(e.shapes,s)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let s=0,i=this.material.length;s<i;s++)t.push(r(e.materials,this.material[s]));i.material=t}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let t=0;t<this.children.length;t++)i.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let t=0;t<this.animations.length;t++){const s=this.animations[t];i.animations.push(r(e.animations,s))}}if(t){const t=n(e.geometries),i=n(e.materials),r=n(e.textures),a=n(e.images),o=n(e.shapes),h=n(e.skeletons),l=n(e.animations),u=n(e.nodes);t.length>0&&(s.geometries=t),i.length>0&&(s.materials=i),r.length>0&&(s.textures=r),a.length>0&&(s.images=a),o.length>0&&(s.shapes=o),h.length>0&&(s.skeletons=h),l.length>0&&(s.animations=l),u.length>0&&(s.nodes=u)}return s.object=i,s;function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=null!==e.pivot?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t<e.children.length;t++){const s=e.children[t];this.add(s.clone())}return this}}Bs.DEFAULT_UP=new Ot(0,1,0),Bs.DEFAULT_MATRIX_AUTO_UPDATE=!0,Bs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;let Fs=class extends Bs{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Ls={type:"move"};class Ds{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Fs,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new Fs,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Ot,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Ot),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Fs,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Ot,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Ot,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const s of e.hand.values())this._getHandJoint(t,s)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(e,t,s){let i=null,r=null,n=null;const a=this._targetRay,o=this._grip,h=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(h&&e.hand){n=!0;for(const i of e.hand.values()){const e=t.getJointPose(i,s),r=this._getHandJoint(h,i);null!==e&&(r.matrix.fromArray(e.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=e.radius),r.visible=null!==e}const i=h.joints["index-finger-tip"],r=h.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,l=.005;h.inputState.pinching&&a>o+l?(h.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!h.inputState.pinching&&a<=o-l&&(h.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,s),null!==r&&(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,o.eventsEnabled&&o.dispatchEvent({type:"gripUpdated",data:e,target:this})));null!==a&&(i=t.getPose(e.targetRaySpace,s),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Ls)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==h&&(h.visible=null!==n),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const s=new Fs;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}const Is={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},Os={h:0,s:0,l:0},Us={h:0,s:0,l:0};function ks(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+6*(t-e)*(2/3-s):e}class zs{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(void 0===t&&void 0===s){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=qe){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,Wt.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=Wt.workingColorSpace){return this.r=e,this.g=t,this.b=s,Wt.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=Wt.workingColorSpace){if(e=Ct(e,1),t=Rt(t,0,1),s=Rt(s,0,1),0===t)this.r=this.g=this.b=s;else{const i=s<=.5?s*(1+t):s+t-s*t,r=2*s-i;this.r=ks(r,i,e+1/3),this.g=ks(r,i,e),this.b=ks(r,i,e-1/3)}return Wt.colorSpaceToWorking(this,i),this}setStyle(e,t=qe){function s(t){void 0!==t&&parseFloat(t)<1&&bt("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],a=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return s(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(a))return s(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(a))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:bt("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],r=s.length;if(3===r)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(s,16),t);bt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=qe){const s=Is[e.toLowerCase()];return void 0!==s?this.setHex(s,t):bt("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=Ht(e.r),this.g=Ht(e.g),this.b=Ht(e.b),this}copyLinearToSRGB(e){return this.r=qt(e.r),this.g=qt(e.g),this.b=qt(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=qe){return Wt.workingToColorSpace(Vs.copy(this),e),65536*Math.round(Rt(255*Vs.r,0,255))+256*Math.round(Rt(255*Vs.g,0,255))+Math.round(Rt(255*Vs.b,0,255))}getHexString(e=qe){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Wt.workingColorSpace){Wt.workingToColorSpace(Vs.copy(this),t);const s=Vs.r,i=Vs.g,r=Vs.b,n=Math.max(s,i,r),a=Math.min(s,i,r);let o,h;const l=(a+n)/2;if(a===n)o=0,h=0;else{const e=n-a;switch(h=l<=.5?e/(n+a):e/(2-n-a),n){case s:o=(i-r)/e+(i<r?6:0);break;case i:o=(r-s)/e+2;break;case r:o=(s-i)/e+4}o/=6}return e.h=o,e.s=h,e.l=l,e}getRGB(e,t=Wt.workingColorSpace){return Wt.workingToColorSpace(Vs.copy(this),t),e.r=Vs.r,e.g=Vs.g,e.b=Vs.b,e}getStyle(e=qe){Wt.workingToColorSpace(Vs.copy(this),e);const t=Vs.r,s=Vs.g,i=Vs.b;return e!==qe?`color(${e} ${t.toFixed(3)} ${s.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*s)},${Math.round(255*i)})`}offsetHSL(e,t,s){return this.getHSL(Os),this.setHSL(Os.h+e,Os.s+t,Os.l+s)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,s){return this.r=e.r+(t.r-e.r)*s,this.g=e.g+(t.g-e.g)*s,this.b=e.b+(t.b-e.b)*s,this}lerpHSL(e,t){this.getHSL(Os),e.getHSL(Us);const s=Pt(Os.h,Us.h,t),i=Pt(Os.s,Us.s,t),r=Pt(Os.l,Us.l,t);return this.setHSL(s,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,s=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*s+r[6]*i,this.g=r[1]*t+r[4]*s+r[7]*i,this.b=r[2]*t+r[5]*s+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Vs=new zs;zs.NAMES=Is;class Gs extends Bs{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 gs,this.environmentIntensity=1,this.environmentRotation=new gs,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(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),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const js=new Ot,$s=new Ot,Ws=new Ot,Hs=new Ot,qs=new Ot,Xs=new Ot,Ys=new Ot,Ks=new Ot,Qs=new Ot,Zs=new Ot,Js=new ss,ei=new ss,ti=new ss;class si{constructor(e=new Ot,t=new Ot,s=new Ot){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),js.subVectors(e,t),i.cross(js);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,s,i,r){js.subVectors(i,t),$s.subVectors(s,t),Ws.subVectors(e,t);const n=js.dot(js),a=js.dot($s),o=js.dot(Ws),h=$s.dot($s),l=$s.dot(Ws),u=n*h-a*a;if(0===u)return r.set(0,0,0),null;const c=1/u,d=(h*o-a*l)*c,p=(n*l-a*o)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,Hs)&&(Hs.x>=0&&Hs.y>=0&&Hs.x+Hs.y<=1)}static getInterpolation(e,t,s,i,r,n,a,o){return null===this.getBarycoord(e,t,s,i,Hs)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,Hs.x),o.addScaledVector(n,Hs.y),o.addScaledVector(a,Hs.z),o)}static getInterpolatedAttribute(e,t,s,i,r,n){return Js.setScalar(0),ei.setScalar(0),ti.setScalar(0),Js.fromBufferAttribute(e,t),ei.fromBufferAttribute(e,s),ti.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Js,r.x),n.addScaledVector(ei,r.y),n.addScaledVector(ti,r.z),n}static isFrontFacing(e,t,s,i){return js.subVectors(s,t),$s.subVectors(e,t),js.cross($s).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return js.subVectors(this.c,this.b),$s.subVectors(this.a,this.b),.5*js.cross($s).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return si.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return si.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return si.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return si.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return si.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,r=this.c;let n,a;qs.subVectors(i,s),Xs.subVectors(r,s),Ks.subVectors(e,s);const o=qs.dot(Ks),h=Xs.dot(Ks);if(o<=0&&h<=0)return t.copy(s);Qs.subVectors(e,i);const l=qs.dot(Qs),u=Xs.dot(Qs);if(l>=0&&u<=l)return t.copy(i);const c=o*u-l*h;if(c<=0&&o>=0&&l<=0)return n=o/(o-l),t.copy(s).addScaledVector(qs,n);Zs.subVectors(e,r);const d=qs.dot(Zs),p=Xs.dot(Zs);if(p>=0&&d<=p)return t.copy(r);const m=d*h-o*p;if(m<=0&&h>=0&&p<=0)return a=h/(h-p),t.copy(s).addScaledVector(Xs,a);const g=l*p-d*u;if(g<=0&&u-l>=0&&d-p>=0)return Ys.subVectors(r,i),a=(u-l)/(u-l+(d-p)),t.copy(i).addScaledVector(Ys,a);const f=1/(g+m+c);return n=m*f,a=c*f,t.copy(s).addScaledVector(qs,n).addScaledVector(Xs,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class ii{constructor(e=new Ot(1/0,1/0,1/0),t=new Ot(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t+=3)this.expandByPoint(ni.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(ni.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const s=ni.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(s),this.max.copy(e).add(s),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return(new this.constructor).copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const s=e.geometry;if(void 0!==s){const i=s.getAttribute("position");if(!0===t&&void 0!==i&&!0!==e.isInstancedMesh)for(let t=0,s=i.count;t<s;t++)!0===e.isMesh?e.getVertexPosition(t,ni):ni.fromBufferAttribute(i,t),ni.applyMatrix4(e.matrixWorld),this.expandByPoint(ni);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),ai.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),ai.copy(s.boundingBox)),ai.applyMatrix4(e.matrixWorld),this.union(ai)}const i=e.children;for(let e=0,s=i.length;e<s;e++)this.expandByObject(i[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,ni),ni.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(pi),mi.subVectors(this.max,pi),oi.subVectors(e.a,pi),hi.subVectors(e.b,pi),li.subVectors(e.c,pi),ui.subVectors(hi,oi),ci.subVectors(li,hi),di.subVectors(oi,li);let t=[0,-ui.z,ui.y,0,-ci.z,ci.y,0,-di.z,di.y,ui.z,0,-ui.x,ci.z,0,-ci.x,di.z,0,-di.x,-ui.y,ui.x,0,-ci.y,ci.x,0,-di.y,di.x,0];return!!yi(t,oi,hi,li,mi)&&(t=[1,0,0,0,1,0,0,0,1],!!yi(t,oi,hi,li,mi)&&(gi.crossVectors(ui,ci),t=[gi.x,gi.y,gi.z],yi(t,oi,hi,li,mi)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ni).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(ni).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(ri[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),ri[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),ri[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),ri[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),ri[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),ri[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),ri[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),ri[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(ri)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}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 ri=[new Ot,new Ot,new Ot,new Ot,new Ot,new Ot,new Ot,new Ot],ni=new Ot,ai=new ii,oi=new Ot,hi=new Ot,li=new Ot,ui=new Ot,ci=new Ot,di=new Ot,pi=new Ot,mi=new Ot,gi=new Ot,fi=new Ot;function yi(e,t,s,i,r){for(let n=0,a=e.length-3;n<=a;n+=3){fi.fromArray(e,n);const a=r.x*Math.abs(fi.x)+r.y*Math.abs(fi.y)+r.z*Math.abs(fi.z),o=t.dot(fi),h=s.dot(fi),l=i.dot(fi);if(Math.max(-Math.max(o,h,l),Math.min(o,h,l))>a)return!1}return!0}const bi=_i();function _i(){const e=new ArrayBuffer(4),t=new Float32Array(e),s=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const n=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,s=0;for(;!(8388608&t);)t<<=1,s-=8388608;t&=-8388609,s+=947912704,n[e]=t|s}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:a,offsetTable:o}}function xi(e){Math.abs(e)>65504&&bt("DataUtils.toHalfFloat(): Value out of range."),e=Rt(e,-65504,65504),bi.floatView[0]=e;const t=bi.uint32View[0],s=t>>23&511;return bi.baseTable[s]+((8388607&t)>>bi.shiftTable[s])}function vi(e){const t=e>>10;return bi.uint32View[0]=bi.mantissaTable[bi.offsetTable[t]+(1023&e)]+bi.exponentTable[t],bi.floatView[0]}const Ti=new Ot,Si=new Dt;let wi=0;class Mi extends St{constructor(e,t,s=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:wi++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=at,this.updateRanges=[],this.gpuType=Y,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[e+i]=t.array[s+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,s=this.count;t<s;t++)Si.fromBufferAttribute(this,t),Si.applyMatrix3(e),this.setXY(t,Si.x,Si.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)Ti.fromBufferAttribute(this,t),Ti.applyMatrix3(e),this.setXYZ(t,Ti.x,Ti.y,Ti.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)Ti.fromBufferAttribute(this,t),Ti.applyMatrix4(e),this.setXYZ(t,Ti.x,Ti.y,Ti.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Ti.fromBufferAttribute(this,t),Ti.applyNormalMatrix(e),this.setXYZ(t,Ti.x,Ti.y,Ti.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Ti.fromBufferAttribute(this,t),Ti.transformDirection(e),this.setXYZ(t,Ti.x,Ti.y,Ti.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let s=this.array[e*this.itemSize+t];return this.normalized&&(s=Bt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=Ft(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Bt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Bt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Bt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Bt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array)),this.array[e+0]=t,this.array[e+1]=s,this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array),r=Ft(r,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return""!==this.name&&(e.name=this.name),this.usage!==at&&(e.usage=this.usage),e}dispose(){this.dispatchEvent({type:"dispose"})}}class Ni extends Mi{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Ai extends Mi{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class Ei extends Mi{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=vi(this.array[e*this.itemSize]);return this.normalized&&(t=Bt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize]=xi(t),this}getY(e){let t=vi(this.array[e*this.itemSize+1]);return this.normalized&&(t=Bt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+1]=xi(t),this}getZ(e){let t=vi(this.array[e*this.itemSize+2]);return this.normalized&&(t=Bt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+2]=xi(t),this}getW(e){let t=vi(this.array[e*this.itemSize+3]);return this.normalized&&(t=Bt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+3]=xi(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array)),this.array[e+0]=xi(t),this.array[e+1]=xi(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array)),this.array[e+0]=xi(t),this.array[e+1]=xi(s),this.array[e+2]=xi(i),this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array),r=Ft(r,this.array)),this.array[e+0]=xi(t),this.array[e+1]=xi(s),this.array[e+2]=xi(i),this.array[e+3]=xi(r),this}}class Ri extends Mi{constructor(e,t,s){super(new Float32Array(e),t,s)}}const Ci=new ii,Pi=new Ot,Bi=new Ot;class Fi{constructor(e=new Ot,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 s=this.center;void 0!==t?s.copy(t):Ci.setFromPoints(e).getCenter(s);let i=0;for(let t=0,r=e.length;t<r;t++)i=Math.max(i,s.distanceToSquared(e[t]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const s=this.center.distanceToSquared(e);return t.copy(e),s>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=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;Pi.subVectors(e,this.center);const t=Pi.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Pi,s/e),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(Bi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Pi.copy(e.center).add(Bi)),this.expandByPoint(Pi.copy(e.center).sub(Bi))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}let Li=0;const Di=new ns,Ii=new Bs,Oi=new Ot,Ui=new ii,ki=new ii,zi=new Ot;class Vi extends St{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Li++}),this.uuid=Et(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(e)?Ai:Ni)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(void 0!==s){const t=(new zt).getNormalMatrix(e);s.applyNormalMatrix(t),s.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return Di.makeRotationFromQuaternion(e),this.applyMatrix4(Di),this}rotateX(e){return Di.makeRotationX(e),this.applyMatrix4(Di),this}rotateY(e){return Di.makeRotationY(e),this.applyMatrix4(Di),this}rotateZ(e){return Di.makeRotationZ(e),this.applyMatrix4(Di),this}translate(e,t,s){return Di.makeTranslation(e,t,s),this.applyMatrix4(Di),this}scale(e,t,s){return Di.makeScale(e,t,s),this.applyMatrix4(Di),this}lookAt(e){return Ii.lookAt(e),Ii.updateMatrix(),this.applyMatrix4(Ii.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Oi).negate(),this.translate(Oi.x,Oi.y,Oi.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let s=0,i=e.length;s<i;s++){const i=e[s];t.push(i.x,i.y,i.z||0)}this.setAttribute("position",new Ri(t,3))}else{const s=Math.min(e.length,t.count);for(let i=0;i<s;i++){const s=e[i];t.setXYZ(i,s.x,s.y,s.z||0)}e.length>t.count&&bt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new ii);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return _t("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Ot(-1/0,-1/0,-1/0),new Ot(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];Ui.setFromBufferAttribute(s),this.morphTargetsRelative?(zi.addVectors(this.boundingBox.min,Ui.min),this.boundingBox.expandByPoint(zi),zi.addVectors(this.boundingBox.max,Ui.max),this.boundingBox.expandByPoint(zi)):(this.boundingBox.expandByPoint(Ui.min),this.boundingBox.expandByPoint(Ui.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&_t('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new Fi);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return _t("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new Ot,1/0);if(e){const s=this.boundingSphere.center;if(Ui.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];ki.setFromBufferAttribute(s),this.morphTargetsRelative?(zi.addVectors(Ui.min,ki.min),Ui.expandByPoint(zi),zi.addVectors(Ui.max,ki.max),Ui.expandByPoint(zi)):(Ui.expandByPoint(ki.min),Ui.expandByPoint(ki.max))}Ui.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)zi.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(zi));if(t)for(let r=0,n=t.length;r<n;r++){const n=t[r],a=this.morphTargetsRelative;for(let t=0,r=n.count;t<r;t++)zi.fromBufferAttribute(n,t),a&&(Oi.fromBufferAttribute(e,t),zi.add(Oi)),i=Math.max(i,s.distanceToSquared(zi))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&_t('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(null===e||void 0===t.position||void 0===t.normal||void 0===t.uv)return void _t("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const s=t.position,i=t.normal,r=t.uv;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new Mi(new Float32Array(4*s.count),4));const n=this.getAttribute("tangent"),a=[],o=[];for(let e=0;e<s.count;e++)a[e]=new Ot,o[e]=new Ot;const h=new Ot,l=new Ot,u=new Ot,c=new Dt,d=new Dt,p=new Dt,m=new Ot,g=new Ot;function f(e,t,i){h.fromBufferAttribute(s,e),l.fromBufferAttribute(s,t),u.fromBufferAttribute(s,i),c.fromBufferAttribute(r,e),d.fromBufferAttribute(r,t),p.fromBufferAttribute(r,i),l.sub(h),u.sub(h),d.sub(c),p.sub(c);const n=1/(d.x*p.y-p.x*d.y);isFinite(n)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-d.y).multiplyScalar(n),g.copy(u).multiplyScalar(d.x).addScaledVector(l,-p.x).multiplyScalar(n),a[e].add(m),a[t].add(m),a[i].add(m),o[e].add(g),o[t].add(g),o[i].add(g))}let y=this.groups;0===y.length&&(y=[{start:0,count:e.count}]);for(let t=0,s=y.length;t<s;++t){const s=y[t],i=s.start;for(let t=i,r=i+s.count;t<r;t+=3)f(e.getX(t+0),e.getX(t+1),e.getX(t+2))}const b=new Ot,_=new Ot,x=new Ot,v=new Ot;function T(e){x.fromBufferAttribute(i,e),v.copy(x);const t=a[e];b.copy(t),b.sub(x.multiplyScalar(x.dot(t))).normalize(),_.crossVectors(v,t);const s=_.dot(o[e])<0?-1:1;n.setXYZW(e,b.x,b.y,b.z,s)}for(let t=0,s=y.length;t<s;++t){const s=y[t],i=s.start;for(let t=i,r=i+s.count;t<r;t+=3)T(e.getX(t+0)),T(e.getX(t+1)),T(e.getX(t+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(void 0!==t){let s=this.getAttribute("normal");if(void 0===s)s=new Mi(new Float32Array(3*t.count),3),this.setAttribute("normal",s);else for(let e=0,t=s.count;e<t;e++)s.setXYZ(e,0,0,0);const i=new Ot,r=new Ot,n=new Ot,a=new Ot,o=new Ot,h=new Ot,l=new Ot,u=new Ot;if(e)for(let c=0,d=e.count;c<d;c+=3){const d=e.getX(c+0),p=e.getX(c+1),m=e.getX(c+2);i.fromBufferAttribute(t,d),r.fromBufferAttribute(t,p),n.fromBufferAttribute(t,m),l.subVectors(n,r),u.subVectors(i,r),l.cross(u),a.fromBufferAttribute(s,d),o.fromBufferAttribute(s,p),h.fromBufferAttribute(s,m),a.add(l),o.add(l),h.add(l),s.setXYZ(d,a.x,a.y,a.z),s.setXYZ(p,o.x,o.y,o.z),s.setXYZ(m,h.x,h.y,h.z)}else for(let e=0,a=t.count;e<a;e+=3)i.fromBufferAttribute(t,e+0),r.fromBufferAttribute(t,e+1),n.fromBufferAttribute(t,e+2),l.subVectors(n,r),u.subVectors(i,r),l.cross(u),s.setXYZ(e+0,l.x,l.y,l.z),s.setXYZ(e+1,l.x,l.y,l.z),s.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),s.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,s=e.count;t<s;t++)zi.fromBufferAttribute(e,t),zi.normalize(),e.setXYZ(t,zi.x,zi.y,zi.z)}toNonIndexed(){function e(e,t){const s=e.array,i=e.itemSize,r=e.normalized,n=new s.constructor(t.length*i);let a=0,o=0;for(let r=0,h=t.length;r<h;r++){a=e.isInterleavedBufferAttribute?t[r]*e.data.stride+e.offset:t[r]*i;for(let e=0;e<i;e++)n[o++]=s[a++]}return new Mi(n,i,r)}if(null===this.index)return bt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Vi,s=this.index.array,i=this.attributes;for(const r in i){const n=e(i[r],s);t.setAttribute(r,n)}const r=this.morphAttributes;for(const i in r){const n=[],a=r[i];for(let t=0,i=a.length;t<i;t++){const i=e(a[t],s);n.push(i)}t.morphAttributes[i]=n}t.morphTargetsRelative=this.morphTargetsRelative;const n=this.groups;for(let e=0,s=n.length;e<s;e++){const s=n[e];t.addGroup(s.start,s.count,s.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,""!==this.name&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const s in t)void 0!==t[s]&&(e[s]=t[s]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const t in s){const i=s[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const s=this.morphAttributes[t],n=[];for(let t=0,i=s.length;t<i;t++){const i=s[t];n.push(i.toJSON(e.data))}n.length>0&&(i[t]=n,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const n=this.groups;n.length>0&&(e.data.groups=JSON.parse(JSON.stringify(n)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere=a.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 s=e.index;null!==s&&this.setIndex(s.clone());const i=e.attributes;for(const e in i){const s=i[e];this.setAttribute(e,s.clone(t))}const r=e.morphAttributes;for(const e in r){const s=[],i=r[e];for(let e=0,r=i.length;e<r;e++)s.push(i[e].clone(t));this.morphAttributes[e]=s}this.morphTargetsRelative=e.morphTargetsRelative;const n=e.groups;for(let e=0,t=n.length;e<t;e++){const t=n[e];this.addGroup(t.start,t.count,t.materialIndex)}const a=e.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=e.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Gi{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=at,this.updateRanges=[],this.version=0,this.uuid=Et()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,s){e*=this.stride,s*=t.stride;for(let i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[s+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=Et()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),s=new this.constructor(t,this.stride);return s.setUsage(this.usage),s}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=Et()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const ji=new Ot;class $i{constructor(e,t,s,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=s,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,s=this.data.count;t<s;t++)ji.fromBufferAttribute(this,t),ji.applyMatrix4(e),this.setXYZ(t,ji.x,ji.y,ji.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)ji.fromBufferAttribute(this,t),ji.applyNormalMatrix(e),this.setXYZ(t,ji.x,ji.y,ji.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)ji.fromBufferAttribute(this,t),ji.transformDirection(e),this.setXYZ(t,ji.x,ji.y,ji.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=Bt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=Ft(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=Bt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Bt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Bt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Bt(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this}setXYZ(e,t,s,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this}setXYZW(e,t,s,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array),r=Ft(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this.data.array[e+3]=r,this}clone(e){if(void 0===e){ft("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const s=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[s+t])}return new Mi(new this.array.constructor(e),this.itemSize,this.normalized)}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new $i(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){ft("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const s=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[s+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}let Wi=0;class Hi extends St{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Wi++}),this.uuid=Et(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=y,this.blendDst=b,this.blendEquation=u,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new zs(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Qe,this.stencilZFail=Qe,this.stencilZPass=Qe,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const s=e[t];if(void 0===s){bt(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s:bt(`Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const s={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(s.uuid=this.uuid,s.type=this.type,""!==this.name&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),void 0!==this.roughness&&(s.roughness=this.roughness),void 0!==this.metalness&&(s.metalness=this.metalness),void 0!==this.sheen&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(s.shininess=this.shininess),void 0!==this.clearcoat&&(s.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(s.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(s.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),void 0!==this.dispersion&&(s.dispersion=this.dispersion),void 0!==this.iridescence&&(s.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(s.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(s.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(s.combine=this.combine)),void 0!==this.envMapRotation&&(s.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(s.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(s.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(s.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(s.size=this.size),null!==this.shadowSide&&(s.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(s.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(s.blending=this.blending),0!==this.side&&(s.side=this.side),!0===this.vertexColors&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),!0===this.transparent&&(s.transparent=!0),this.blendSrc!==y&&(s.blendSrc=this.blendSrc),this.blendDst!==b&&(s.blendDst=this.blendDst),this.blendEquation!==u&&(s.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(s.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(s.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(s.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(s.depthFunc=this.depthFunc),!1===this.depthTest&&(s.depthTest=this.depthTest),!1===this.depthWrite&&(s.depthWrite=this.depthWrite),!1===this.colorWrite&&(s.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(s.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(s.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(s.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Qe&&(s.stencilFail=this.stencilFail),this.stencilZFail!==Qe&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==Qe&&(s.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(s.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(s.rotation=this.rotation),!0===this.polygonOffset&&(s.polygonOffset=!0),0!==this.polygonOffsetFactor&&(s.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(s.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(s.linewidth=this.linewidth),void 0!==this.dashSize&&(s.dashSize=this.dashSize),void 0!==this.gapSize&&(s.gapSize=this.gapSize),void 0!==this.scale&&(s.scale=this.scale),!0===this.dithering&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),!0===this.alphaHash&&(s.alphaHash=!0),!0===this.alphaToCoverage&&(s.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(s.premultipliedAlpha=!0),!0===this.forceSinglePass&&(s.forceSinglePass=!0),!1===this.allowOverride&&(s.allowOverride=!1),!0===this.wireframe&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(s.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(s.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(s.flatShading=!0),!1===this.visible&&(s.visible=!1),!1===this.toneMapped&&(s.toneMapped=!1),!1===this.fog&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(s.textures=t),r.length>0&&(s.images=r)}return s}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 s=null;if(null!==t){const e=t.length;s=new Array(e);for(let i=0;i!==e;++i)s[i]=t[i].clone()}return this.clippingPlanes=s,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}class qi extends Hi{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new zs(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const Xi=new Ot,Yi=new Ot,Ki=new Ot,Qi=new Ot,Zi=new Ot,Ji=new Ot,er=new Ot;class tr{constructor(e=new Ot,t=new Ot(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,Xi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Xi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Xi.copy(this.origin).addScaledVector(this.direction,t),Xi.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){Yi.copy(e).add(t).multiplyScalar(.5),Ki.copy(t).sub(e).normalize(),Qi.copy(this.origin).sub(Yi);const r=.5*e.distanceTo(t),n=-this.direction.dot(Ki),a=Qi.dot(this.direction),o=-Qi.dot(Ki),h=Qi.lengthSq(),l=Math.abs(1-n*n);let u,c,d,p;if(l>0)if(u=n*o-a,c=n*a-o,p=r*l,u>=0)if(c>=-p)if(c<=p){const e=1/l;u*=e,c*=e,d=u*(u+n*c+2*a)+c*(n*u+c+2*o)+h}else c=r,u=Math.max(0,-(n*c+a)),d=-u*u+c*(c+2*o)+h;else c=-r,u=Math.max(0,-(n*c+a)),d=-u*u+c*(c+2*o)+h;else c<=-p?(u=Math.max(0,-(-n*r+a)),c=u>0?-r:Math.min(Math.max(-r,-o),r),d=-u*u+c*(c+2*o)+h):c<=p?(u=0,c=Math.min(Math.max(-r,-o),r),d=c*(c+2*o)+h):(u=Math.max(0,-(n*r+a)),c=u>0?r:Math.min(Math.max(-r,-o),r),d=-u*u+c*(c+2*o)+h);else c=n>0?-r:r,u=Math.max(0,-(n*c+a)),d=-u*u+c*(c+2*o)+h;return s&&s.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(Yi).addScaledVector(Ki,c),d}intersectSphere(e,t){Xi.subVectors(e.center,this.origin);const s=Xi.dot(this.direction),i=Xi.dot(Xi)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),a=s-n,o=s+n;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return!(e.radius<0)&&this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return null===s?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,r,n,a,o;const h=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,c=this.origin;return h>=0?(s=(e.min.x-c.x)*h,i=(e.max.x-c.x)*h):(s=(e.max.x-c.x)*h,i=(e.min.x-c.x)*h),l>=0?(r=(e.min.y-c.y)*l,n=(e.max.y-c.y)*l):(r=(e.max.y-c.y)*l,n=(e.min.y-c.y)*l),s>n||r>i?null:((r>s||isNaN(s))&&(s=r),(n<i||isNaN(i))&&(i=n),u>=0?(a=(e.min.z-c.z)*u,o=(e.max.z-c.z)*u):(a=(e.max.z-c.z)*u,o=(e.min.z-c.z)*u),s>o||a>i?null:((a>s||s!=s)&&(s=a),(o<i||i!=i)&&(i=o),i<0?null:this.at(s>=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Xi)}intersectTriangle(e,t,s,i,r){Zi.subVectors(t,e),Ji.subVectors(s,e),er.crossVectors(Zi,Ji);let n,a=this.direction.dot(er);if(a>0){if(i)return null;n=1}else{if(!(a<0))return null;n=-1,a=-a}Qi.subVectors(this.origin,e);const o=n*this.direction.dot(Ji.crossVectors(Qi,Ji));if(o<0)return null;const h=n*this.direction.dot(Zi.cross(Qi));if(h<0)return null;if(o+h>a)return null;const l=-n*Qi.dot(er);return l<0?null:this.at(l/a,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 sr extends Hi{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new zs(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 gs,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const ir=new ns,rr=new tr,nr=new Fi,ar=new Ot,or=new Ot,hr=new Ot,lr=new Ot,ur=new Ot,cr=new Ot,dr=new Ot,pr=new Ot;class mr extends Bs{constructor(e=new Vi,t=new sr){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),void 0!==e.morphTargetInfluences&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),void 0!==e.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;e<t;e++){const t=s[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){const s=this.geometry,i=s.attributes.position,r=s.morphAttributes.position,n=s.morphTargetsRelative;t.fromBufferAttribute(i,e);const a=this.morphTargetInfluences;if(r&&a){cr.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=a[s],o=r[s];0!==i&&(ur.fromBufferAttribute(o,e),n?cr.addScaledVector(ur,i):cr.addScaledVector(ur.sub(t),i))}t.add(cr)}return t}raycast(e,t){const s=this.geometry,i=this.material,r=this.matrixWorld;if(void 0!==i){if(null===s.boundingSphere&&s.computeBoundingSphere(),nr.copy(s.boundingSphere),nr.applyMatrix4(r),rr.copy(e.ray).recast(e.near),!1===nr.containsPoint(rr.origin)){if(null===rr.intersectSphere(nr,ar))return;if(rr.origin.distanceToSquared(ar)>(e.far-e.near)**2)return}ir.copy(r).invert(),rr.copy(e.ray).applyMatrix4(ir),null!==s.boundingBox&&!1===rr.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,rr)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,a=r.index,o=r.attributes.position,h=r.attributes.uv,l=r.attributes.uv1,u=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(n))for(let r=0,o=c.length;r<o;r++){const o=c[r],p=n[o.materialIndex];for(let r=Math.max(o.start,d.start),n=Math.min(a.count,Math.min(o.start+o.count,d.start+d.count));r<n;r+=3){i=gr(this,p,e,s,h,l,u,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=o.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);r<o;r+=3){i=gr(this,n,e,s,h,l,u,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}else if(void 0!==o)if(Array.isArray(n))for(let r=0,a=c.length;r<a;r++){const a=c[r],p=n[a.materialIndex];for(let r=Math.max(a.start,d.start),n=Math.min(o.count,Math.min(a.start+a.count,d.start+d.count));r<n;r+=3){i=gr(this,p,e,s,h,l,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=a.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);r<a;r+=3){i=gr(this,n,e,s,h,l,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function gr(e,t,s,i,r,n,a,o,h,l){e.getVertexPosition(o,or),e.getVertexPosition(h,hr),e.getVertexPosition(l,lr);const u=function(e,t,s,i,r,n,a,o){let h;if(h=1===t.side?i.intersectTriangle(a,n,r,!0,o):i.intersectTriangle(r,n,a,0===t.side,o),null===h)return null;pr.copy(o),pr.applyMatrix4(e.matrixWorld);const l=s.ray.origin.distanceTo(pr);return l<s.near||l>s.far?null:{distance:l,point:pr.clone(),object:e}}(e,t,s,i,or,hr,lr,dr);if(u){const e=new Ot;si.getBarycoord(dr,or,hr,lr,e),r&&(u.uv=si.getInterpolatedAttribute(r,o,h,l,e,new Dt)),n&&(u.uv1=si.getInterpolatedAttribute(n,o,h,l,e,new Dt)),a&&(u.normal=si.getInterpolatedAttribute(a,o,h,l,e,new Ot),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const t={a:o,b:h,c:l,normal:new Ot,materialIndex:0};si.getNormal(or,hr,lr,t.normal),u.face=t,u.barycoord=e}return u}class fr extends ts{constructor(e=null,t=1,s=1,i,r,n,a,o,h=1003,l=1003,u,c){super(null,n,a,o,h,l,i,r,u,c),this.isDataTexture=!0,this.image={data:e,width:t,height:s},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class yr extends Mi{constructor(e,t,s,i=1){super(e,t,s),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const br=new Ot,_r=new Ot,xr=new zt;class vr{constructor(e=new Ot(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,s,i){return this.normal.set(e,t,s),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,s){const i=br.subVectors(s,t).cross(_r.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,s=!0){const i=e.delta(br),r=this.normal.dot(i);if(0===r)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const n=-(e.start.dot(this.normal)+this.constant)/r;return!0===s&&(n<0||n>1)?null:t.copy(e.start).addScaledVector(i,n)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<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 s=t||xr.getNormalMatrix(e),i=this.coplanarPoint(br).applyMatrix4(e),r=this.normal.applyMatrix3(s).normalize();return this.constant=-i.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 Tr=new Fi,Sr=new Dt(.5,.5),wr=new Ot;class Mr{constructor(e=new vr,t=new vr,s=new vr,i=new vr,r=new vr,n=new vr){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(s),a[3].copy(i),a[4].copy(r),a[5].copy(n),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=2e3,s=!1){const i=this.planes,r=e.elements,n=r[0],a=r[1],o=r[2],h=r[3],l=r[4],u=r[5],c=r[6],d=r[7],p=r[8],m=r[9],g=r[10],f=r[11],y=r[12],b=r[13],_=r[14],x=r[15];if(i[0].setComponents(h-n,d-l,f-p,x-y).normalize(),i[1].setComponents(h+n,d+l,f+p,x+y).normalize(),i[2].setComponents(h+a,d+u,f+m,x+b).normalize(),i[3].setComponents(h-a,d-u,f-m,x-b).normalize(),s)i[4].setComponents(o,c,g,_).normalize(),i[5].setComponents(h-o,d-c,f-g,x-_).normalize();else if(i[4].setComponents(h-o,d-c,f-g,x-_).normalize(),t===ht)i[5].setComponents(h+o,d+c,f+g,x+_).normalize();else{if(t!==lt)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(o,c,g,_).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Tr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Tr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Tr)}intersectsSprite(e){Tr.center.set(0,0,0);const t=Sr.distanceTo(e.center);return Tr.radius=.7071067811865476+t,Tr.applyMatrix4(e.matrixWorld),this.intersectsSphere(Tr)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(s)<i)return!1}return!0}intersectsBox(e){const t=this.planes;for(let s=0;s<6;s++){const i=t[s];if(wr.x=i.normal.x>0?e.max.x:e.min.x,wr.y=i.normal.y>0?e.max.y:e.min.y,wr.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(wr)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}const Nr=new ns,Ar=new Mr;class Er{constructor(){this.coordinateSystem=ht}intersectsObject(e,t){if(!t.isArrayCamera||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Nr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ar.setFromProjectionMatrix(Nr,i.coordinateSystem,i.reversedDepth),Ar.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Nr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ar.setFromProjectionMatrix(Nr,i.coordinateSystem,i.reversedDepth),Ar.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Nr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ar.setFromProjectionMatrix(Nr,i.coordinateSystem,i.reversedDepth),Ar.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Nr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ar.setFromProjectionMatrix(Nr,i.coordinateSystem,i.reversedDepth),Ar.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(Nr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ar.setFromProjectionMatrix(Nr,i.coordinateSystem,i.reversedDepth),Ar.containsPoint(e))return!0}return!1}clone(){return new Er}}class Rr extends Hi{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new zs(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}class Cr extends Hi{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new zs(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class Pr extends ts{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=O,this.minFilter=O,this.generateMipmaps=!1,this.needsUpdate=!0}}class Br extends ts{constructor(e=[],t=301,s,i,r,n,a,o,h,l){super(e,t,s,i,r,n,a,o,h,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Fr extends ts{constructor(e,t,s=1014,i,r,n,a=1003,o=1003,h,l=1026,u=1){if(l!==ne&&l!==ae)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:u},i,r,n,a,o,l,s,h),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Qt(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class Lr extends Fr{constructor(e,t=1014,s=301,i,r,n=1003,a=1003,o,h=1026){const l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,s,i,r,n,a,o,h),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class Dr extends Vi{constructor(e=1,t=1,s=1,i=1,r=1,n=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:r,depthSegments:n};const a=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const o=[],h=[],l=[],u=[];let c=0,d=0;function p(e,t,s,i,r,n,p,m,g,f,y){const b=n/g,_=p/f,x=n/2,v=p/2,T=m/2,S=g+1,w=f+1;let M=0,N=0;const A=new Ot;for(let n=0;n<w;n++){const a=n*_-v;for(let o=0;o<S;o++){const c=o*b-x;A[e]=c*i,A[t]=a*r,A[s]=T,h.push(A.x,A.y,A.z),A[e]=0,A[t]=0,A[s]=m>0?1:-1,l.push(A.x,A.y,A.z),u.push(o/g),u.push(1-n/f),M+=1}}for(let e=0;e<f;e++)for(let t=0;t<g;t++){const s=c+t+S*e,i=c+t+S*(e+1),r=c+(t+1)+S*(e+1),n=c+(t+1)+S*e;o.push(s,i,n),o.push(i,r,n),N+=6}a.addGroup(d,N,y),d+=N,c+=M}p("z","y","x",-1,-1,s,t,e,n,r,0),p("z","y","x",1,-1,s,t,-e,n,r,1),p("x","z","y",1,1,e,s,t,i,n,2),p("x","z","y",1,-1,e,s,-t,i,n,3),p("x","y","z",1,-1,e,t,s,i,r,4),p("x","y","z",-1,-1,e,t,-s,i,r,5),this.setIndex(o),this.setAttribute("position",new Ri(h,3)),this.setAttribute("normal",new Ri(l,3)),this.setAttribute("uv",new Ri(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Dr(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class Ir extends Vi{constructor(e=1,t=1,s=1,i=32,r=1,n=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:r,openEnded:n,thetaStart:a,thetaLength:o};const h=this;i=Math.floor(i),r=Math.floor(r);const l=[],u=[],c=[],d=[];let p=0;const m=[],g=s/2;let f=0;function y(s){const r=p,n=new Dt,m=new Ot;let y=0;const b=!0===s?e:t,_=!0===s?1:-1;for(let e=1;e<=i;e++)u.push(0,g*_,0),c.push(0,_,0),d.push(.5,.5),p++;const x=p;for(let e=0;e<=i;e++){const t=e/i*o+a,s=Math.cos(t),r=Math.sin(t);m.x=b*r,m.y=g*_,m.z=b*s,u.push(m.x,m.y,m.z),c.push(0,_,0),n.x=.5*s+.5,n.y=.5*r*_+.5,d.push(n.x,n.y),p++}for(let e=0;e<i;e++){const t=r+e,i=x+e;!0===s?l.push(i,i+1,t):l.push(i+1,i,t),y+=3}h.addGroup(f,y,!0===s?1:2),f+=y}!function(){const n=new Ot,y=new Ot;let b=0;const _=(t-e)/s;for(let h=0;h<=r;h++){const l=[],f=h/r,b=f*(t-e)+e;for(let e=0;e<=i;e++){const t=e/i,r=t*o+a,h=Math.sin(r),m=Math.cos(r);y.x=b*h,y.y=-f*s+g,y.z=b*m,u.push(y.x,y.y,y.z),n.set(h,_,m).normalize(),c.push(n.x,n.y,n.z),d.push(t,1-f),l.push(p++)}m.push(l)}for(let s=0;s<i;s++)for(let i=0;i<r;i++){const n=m[i][s],a=m[i+1][s],o=m[i+1][s+1],h=m[i][s+1];(e>0||0!==i)&&(l.push(n,a,h),b+=3),(t>0||i!==r-1)&&(l.push(a,o,h),b+=3)}h.addGroup(f,b,0),f+=b}(),!1===n&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(l),this.setAttribute("position",new Ri(u,3)),this.setAttribute("normal",new Ri(c,3)),this.setAttribute("uv",new Ri(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ir(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Or extends Vi{constructor(e=1,t=1,s=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:s,heightSegments:i};const r=e/2,n=t/2,a=Math.floor(s),o=Math.floor(i),h=a+1,l=o+1,u=e/a,c=t/o,d=[],p=[],m=[],g=[];for(let e=0;e<l;e++){const t=e*c-n;for(let s=0;s<h;s++){const i=s*u-r;p.push(i,-t,0),m.push(0,0,1),g.push(s/a),g.push(1-e/o)}}for(let e=0;e<o;e++)for(let t=0;t<a;t++){const s=t+h*e,i=t+h*(e+1),r=t+1+h*(e+1),n=t+1+h*e;d.push(s,i,n),d.push(i,r,n)}this.setIndex(d),this.setAttribute("position",new Ri(p,3)),this.setAttribute("normal",new Ri(m,3)),this.setAttribute("uv",new Ri(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Or(e.width,e.height,e.widthSegments,e.heightSegments)}}class Ur extends Vi{constructor(e=1,t=32,s=16,i=0,r=2*Math.PI,n=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:r,thetaStart:n,thetaLength:a},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const o=Math.min(n+a,Math.PI);let h=0;const l=[],u=new Ot,c=new Ot,d=[],p=[],m=[],g=[];for(let d=0;d<=s;d++){const f=[],y=d/s;let b=0;0===d&&0===n?b=.5/t:d===s&&o===Math.PI&&(b=-.5/t);for(let s=0;s<=t;s++){const o=s/t;u.x=-e*Math.cos(i+o*r)*Math.sin(n+y*a),u.y=e*Math.cos(n+y*a),u.z=e*Math.sin(i+o*r)*Math.sin(n+y*a),p.push(u.x,u.y,u.z),c.copy(u).normalize(),m.push(c.x,c.y,c.z),g.push(o+b,1-y),f.push(h++)}l.push(f)}for(let e=0;e<s;e++)for(let i=0;i<t;i++){const t=l[e][i+1],r=l[e][i],a=l[e+1][i],h=l[e+1][i+1];(0!==e||n>0)&&d.push(t,r,h),(e!==s-1||o<Math.PI)&&d.push(r,a,h)}this.setIndex(d),this.setAttribute("position",new Ri(p,3)),this.setAttribute("normal",new Ri(m,3)),this.setAttribute("uv",new Ri(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ur(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class kr extends Hi{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new zs(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}class zr extends Hi{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new zs(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new gs,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Vr extends zr{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new Dt(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Rt(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new zs(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new zs(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new zs(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=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 Gr extends Hi{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new zs(16777215),this.specular=new zs(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new gs,this.combine=0,this.reflectivity=1,this.envMapIntensity=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.envMapIntensity=e.envMapIntensity,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 jr extends Hi{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new zs(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(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 $r extends Hi{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(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 Wr extends Hi{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new zs(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new gs,this.combine=0,this.reflectivity=1,this.envMapIntensity=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.envMapIntensity=e.envMapIntensity,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 Hr extends Hi{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new zs(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(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 qr extends Rr{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}}class Xr extends Bs{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new zs(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}class Yr extends Xr{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Bs.DEFAULT_UP),this.updateMatrix(),this.groundColor=new zs(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){const t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}}const Kr=new ns,Qr=new Ot,Zr=new Ot;class Jr{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Dt(512,512),this.mapType=j,this.map=null,this.mapPass=null,this.matrix=new ns,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Mr,this._frameExtents=new Dt(1,1),this._viewportCount=1,this._viewports=[new ss(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;Qr.setFromMatrixPosition(e.matrixWorld),t.position.copy(Qr),Zr.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Zr),t.updateMatrixWorld(),Kr.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Kr,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===lt||t.reversedDepth?s.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(Kr)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return(new this.constructor).copy(this)}toJSON(){const e={};return 1!==this.intensity&&(e.intensity=this.intensity),0!==this.bias&&(e.bias=this.bias),0!==this.normalBias&&(e.normalBias=this.normalBias),1!==this.radius&&(e.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const en=new Ot,tn=new It,sn=new Ot;class rn extends Bs{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ns,this.projectionMatrix=new ns,this.projectionMatrixInverse=new ns,this.coordinateSystem=ht,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.matrixWorld.decompose(en,tn,sn),1===sn.x&&1===sn.y&&1===sn.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(en,tn,sn.set(1,1,1)).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorld.decompose(en,tn,sn),1===sn.x&&1===sn.y&&1===sn.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(en,tn,sn.set(1,1,1)).invert()}clone(){return(new this.constructor).copy(this)}}const nn=new Ot,an=new Dt,on=new Dt;class hn extends rn{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*At*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Nt*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*At*Math.atan(Math.tan(.5*Nt*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,s){nn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(nn.x,nn.y).multiplyScalar(-e/nn.z),nn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(nn.x,nn.y).multiplyScalar(-e/nn.z)}getViewSize(e,t){return this.getViewBounds(e,an,on),t.subVectors(on,an)}setViewOffset(e,t,s,i,r,n){this.aspect=e/t,null===this.view&&(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=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*Nt*this.fov)/this.zoom,s=2*t,i=this.aspect*s,r=-.5*i;const n=this.view;if(null!==this.view&&this.view.enabled){const e=n.fullWidth,a=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/a,i*=n.width/e,s*=n.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-s,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,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}class ln extends Jr{constructor(){super(new hn(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=2*At*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,r=e.distance||t.far;s===t.fov&&i===t.aspect&&r===t.far||(t.fov=s,t.aspect=i,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class un extends Xr{constructor(e,t,s=0,i=Math.PI/3,r=0,n=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Bs.DEFAULT_UP),this.updateMatrix(),this.target=new Bs,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new ln}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}}class cn extends Jr{constructor(){super(new hn(90,1,.5,500)),this.isPointLightShadow=!0}}class dn extends Xr{constructor(e,t,s=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=s,this.decay=i,this.shadow=new cn}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}}class pn extends rn{constructor(e=-1,t=1,s=1,i=-1,r=.1,n=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=s,this.bottom=i,this.near=r,this.far=n,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,s,i,r,n){null===this.view&&(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=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),s=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=s-e,n=s+e,a=i+t,o=i-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=e*this.view.offsetX,n=r+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(r,n,a,o,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}class mn extends Jr{constructor(){super(new pn(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class gn extends Xr{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Bs.DEFAULT_UP),this.updateMatrix(),this.target=new Bs,this.shadow=new mn}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class fn extends Xr{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class yn extends Xr{constructor(e,t,s=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=s,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class bn{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new Ot)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const s=e.x,i=e.y,r=e.z,n=this.coefficients;return t.copy(n[0]).multiplyScalar(.282095),t.addScaledVector(n[1],.488603*i),t.addScaledVector(n[2],.488603*r),t.addScaledVector(n[3],.488603*s),t.addScaledVector(n[4],s*i*1.092548),t.addScaledVector(n[5],i*r*1.092548),t.addScaledVector(n[6],.315392*(3*r*r-1)),t.addScaledVector(n[7],s*r*1.092548),t.addScaledVector(n[8],.546274*(s*s-i*i)),t}getIrradianceAt(e,t){const s=e.x,i=e.y,r=e.z,n=this.coefficients;return t.copy(n[0]).multiplyScalar(.886227),t.addScaledVector(n[1],1.023328*i),t.addScaledVector(n[2],1.023328*r),t.addScaledVector(n[3],1.023328*s),t.addScaledVector(n[4],.858086*s*i),t.addScaledVector(n[5],.858086*i*r),t.addScaledVector(n[6],.743125*r*r-.247708),t.addScaledVector(n[7],.858086*s*r),t.addScaledVector(n[8],.429043*(s*s-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let s=0;s<9;s++)this.coefficients[s].addScaledVector(e.coefficients[s],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let s=0;s<9;s++)this.coefficients[s].lerp(e.coefficients[s],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(e,t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].fromArray(e,t+3*i);return this}toArray(e=[],t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].toArray(e,t+3*i);return e}static getBasisAt(e,t){const s=e.x,i=e.y,r=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*r,t[3]=.488603*s,t[4]=1.092548*s*i,t[5]=1.092548*i*r,t[6]=.315392*(3*r*r-1),t[7]=1.092548*s*r,t[8]=.546274*(s*s-i*i)}}class _n extends Xr{constructor(e=new bn,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}const xn=-90;class vn extends Bs{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new hn(xn,1,e,t);i.layers=this.layers,this.add(i);const r=new hn(xn,1,e,t);r.layers=this.layers,this.add(r);const n=new hn(xn,1,e,t);n.layers=this.layers,this.add(n);const a=new hn(xn,1,e,t);a.layers=this.layers,this.add(a);const o=new hn(xn,1,e,t);o.layers=this.layers,this.add(o);const h=new hn(xn,1,e,t);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,a,o]=t;for(const e of t)this.remove(e);if(e===ht)s.up.set(0,1,0),s.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),n.up.set(0,0,1),n.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==lt)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);s.up.set(0,-1,0),s.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),n.up.set(0,0,-1),n.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,n,a,o,h,l]=this.children,u=e.getRenderTarget(),c=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=s.texture.generateMipmaps;s.texture.generateMipmaps=!1;let g=!1;g=!0===e.isWebGLRenderer?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(s,0,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,r),e.setRenderTarget(s,1,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,n),e.setRenderTarget(s,2,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,a),e.setRenderTarget(s,3,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,o),e.setRenderTarget(s,4,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,h),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class Tn extends hn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Sn extends Gi{constructor(e,t,s=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=s}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}class wn{static{wn.prototype.isMatrix2=!0}constructor(e,t,s,i){this.elements=[1,0,0,1],void 0!==e&&this.set(e,t,s,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let s=0;s<4;s++)this.elements[s]=e[s+t];return this}set(e,t,s,i){const r=this.elements;return r[0]=e,r[2]=t,r[1]=s,r[3]=i,this}}function Mn(e,t,s,i){const r=function(e){switch(e){case j:case $:return{byteLength:1,components:1};case H:case W:case K:return{byteLength:2,components:1};case Q:case Z:return{byteLength:2,components:4};case X:case q:case Y:return{byteLength:4,components:1};case ee:case te:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(i);switch(s){case se:return e*t;case oe:case he:return e*t/r.components*r.byteLength;case le:case ue:return e*t*2/r.components*r.byteLength;case ie:return e*t*3/r.components*r.byteLength;case re:case ce:return e*t*4/r.components*r.byteLength;case de:case pe:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case me:case ge:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case ye:case _e:return Math.max(e,16)*Math.max(t,8)/4;case fe:case be:return Math.max(e,8)*Math.max(t,8)/2;case xe:case ve:case Se:case we:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Te:case Me:case Ne:case Ae:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ee:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Re:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Ce:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Pe:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case Be:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Fe:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Le:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case De:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case Ie:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case Oe:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case Ue:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case ke:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case ze:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case Ve:case 36494:case 36495:return Math.ceil(e/4)*Math.ceil(t/4)*16;case Ge:case je:return Math.ceil(e/4)*Math.ceil(t/4)*8;case $e:case We:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${s} format.`)}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:a}})),"undefined"!=typeof window&&(window.__THREE__?bt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=a);const Nn=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],An=new WeakMap,En=new WeakMap,Rn=new WeakMap;class Cn{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Nn,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:s,object:i}=e;if(t={geometryId:s.id,worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),e.material.transmission>0){const{width:s,height:i}=e.context;t.bufferWidth=s,t.bufferHeight=i}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={id:i.id,version:i.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getGeometryData(e){let t=Rn.get(e);return void 0===t&&(t={_renderId:-1,_equal:!1,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},Rn.set(e,t)),t}getMaterialData(e){let t=En.get(e);if(void 0===t){t={_renderId:-1,_equal:!1};for(const s of this.refreshUniforms){const i=e[s];null!=i&&("object"==typeof i&&void 0!==i.clone?!0===i.isTexture?t[s]={id:i.id,version:i.version}:t[s]=i.clone():t[s]=i)}En.set(e,t)}return t}equals(e,t,s){const{object:i,material:r,geometry:n}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(i.matrixWorld))return a.worldMatrix.copy(i.matrixWorld),!1;const o=this.getMaterialData(e.material);if(o._renderId!==s){o._renderId=s;for(const e in o){const t=o[e],s=r[e];if("_renderId"!==e&&"_equal"!==e)if(void 0!==t.equals){if(!1===t.equals(s))return t.copy(s),o._equal=!1,!1}else if(!0===s.isTexture){if(t.id!==s.id||t.version!==s.version)return t.id=s.id,t.version=s.version,o._equal=!1,!1}else if(t!==s)return o[e]=s,o._equal=!1,!1}if(o.transmission>0){const{width:t,height:s}=e.context;if(a.bufferWidth!==t||a.bufferHeight!==s)return a.bufferWidth=t,a.bufferHeight=s,o._equal=!1,!1}o._equal=!0}else if(!1===o._equal)return!1;if(a.geometryId!==n.id)return a.geometryId=n.id,!1;const h=this.getGeometryData(e.geometry);if(h._renderId!==s){h._renderId=s;const e=n.attributes,t=h.attributes;let i=0,r=0;for(const t in e)i++;for(const s in t){r++;const i=t[s],n=e[s];if(void 0===n)return delete t[s],h._equal=!1,!1;if(i.id!==n.id||i.version!==n.version)return i.id=n.id,i.version=n.version,h._equal=!1,!1}if(r!==i)return h.attributes=this.getAttributesData(e),h._equal=!1,!1;const a=n.index,o=h.indexId,l=h.indexVersion,u=a?a.id:null,c=a?a.version:null;if(o!==u||l!==c)return h.indexId=u,h.indexVersion=c,h._equal=!1,!1;if(h.drawRange.start!==n.drawRange.start||h.drawRange.count!==n.drawRange.count)return h.drawRange.start=n.drawRange.start,h.drawRange.count=n.drawRange.count,h._equal=!1,!1;h._equal=!0}else if(!1===h._equal)return!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t<a.morphTargetInfluences.length;t++)a.morphTargetInfluences[t]!==i.morphTargetInfluences[t]&&(a.morphTargetInfluences[t]=i.morphTargetInfluences[t],e=!0);if(e)return!1}if(a.lights)for(let e=0;e<t.length;e++)if(a.lights[e].map!==t[e].map)return!1;return a.center&&!1===a.center.equals(i.center)?(a.center.copy(i.center),!0):(null!==e.bundle&&(a.version=e.bundle.version),!0)}getLightsData(e){const t=[];for(const s of e)!0===s.isSpotLight&&null!==s.map&&t.push({map:s.map.version});return t}getLights(e,t){if(An.has(e)){const s=An.get(e);if(s.renderId===t)return s.lightsData}const s=this.getLightsData(e.getLights());return An.set(e,{renderId:t,lightsData:s}),s}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:s}=t;if(this.renderId!==s)return this.renderId=s,!0;const i=!0===e.object.static,r=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(i||r)return!1;const n=this.getLights(e.lightsNode,s);return!0!==this.equals(e,n,s)}}const Pn=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];class Bn{constructor(e=null){this.isStackTrace=!0,this.stack=function(e){const t=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return e.split("\n").map(e=>{const s=e.match(t);if(!s)return null;const i=s[1]||s[2]||"",r=s[3].split("?")[0],n=parseInt(s[4],10),a=parseInt(s[5],10);return{fn:i,file:r.split("/").pop(),line:n,column:a}}).filter(e=>e&&!Pn.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;return`${e}\n${this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n")}`}}function Fn(e,t=0){let s=3735928559^t,i=1103547991^t;if(Array.isArray(e))for(let t,r=0;r<e.length;r++)t=e[r],s=Math.imul(s^t,2654435761),i=Math.imul(i^t,1597334677);else for(let t,r=0;r<e.length;r++)t=e.charCodeAt(r),s=Math.imul(s^t,2654435761),i=Math.imul(i^t,1597334677);return s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(s^s>>>13,3266489909),4294967296*(2097151&i)+(s>>>0)}const Ln=e=>Fn(e),Dn=e=>Fn(e),In=(...e)=>Fn(e),On=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Un=new WeakMap;function kn(e){return On.get(e)}function zn(e){if(null==e)return null;const t=typeof e;return!0===e.isNode?"node":"number"===t?"float":"boolean"===t?"bool":"string"===t?"string":"function"===t?"shader":!0===e.isVector2?"vec2":!0===e.isVector3?"vec3":!0===e.isVector4?"vec4":!0===e.isMatrix2?"mat2":!0===e.isMatrix3?"mat3":!0===e.isMatrix4?"mat4":!0===e.isColor?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function Vn(e,...t){const s=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===s?t=[t[0],t[0]]:"vec3"===s?t=[t[0],t[0],t[0]]:"vec4"===s&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new zs(...t):"vec2"===s?new Dt(...t):"vec3"===s?new Ot(...t):"vec4"===s?new ss(...t):"mat2"===s?new wn(...t):"mat3"===s?new zt(...t):"mat4"===s?new ns(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?(i=t[0],Uint8Array.from(atob(i),e=>e.charCodeAt(0)).buffer):null;var i}function Gn(e){let t=Un.get(e);return void 0===t&&(t={},Un.set(e,t)),t}const jn="vertex",$n="none",Wn="frame",Hn="render",qn="object",Xn="readOnly",Yn="writeOnly",Kn="readWrite",Qn=["setup","analyze","generate"],Zn=["fragment","vertex","compute"],Jn=["x","y","z","w"],ea={analyze:"setup",generate:"analyze"};let ta=0;class sa extends St{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=$n,this.updateBeforeType=$n,this.updateAfterType=$n,this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=ta++,this.stackTrace=null,!0===sa.captureStackTrace&&(this.stackTrace=new Bn)}set needsUpdate(e){!0===e&&this.version++}get uuid(){return null===this._uuid&&(this._uuid=Lt.generateUUID()),this._uuid}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,Wn)}onRenderUpdate(e){return this.onUpdate(e,Hn)}onObjectUpdate(e){return this.onUpdate(e,qn)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const s of Object.getOwnPropertyNames(this)){const i=this[s];if(!0!==s.startsWith("_")&&!e.has(i))if(!0===Array.isArray(i))for(let e=0;e<i.length;e++){const r=i[e];r&&!0===r.isNode&&t.push({property:s,index:e,childNode:r})}else if(i&&!0===i.isNode)t.push({property:s,childNode:i});else if(i&&Object.getPrototypeOf(i)===Object.prototype)for(const e in i){if(!0===e.startsWith("_"))continue;const r=i[e];r&&!0===r.isNode&&t.push({property:s,index:e,childNode:r})}}return t}getCacheKey(e=!1,t=null){if(!0===(e=e||this.version!==this._cacheKeyVersion)||null===this._cacheKey){null===t&&(t=new Set);const s=[];for(const{property:i,childNode:r}of this._getChildren(t))s.push(Ln(i.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=In(Dn(s),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return String(this.id)}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e,t=null){const s=e.getDataFromNode(this);let i;return null!==t?(s.typeFromOutput=s.typeFromOutput||{},i=s.typeFromOutput[t],void 0===i&&(i=this.generateNodeType(e,t),s.typeFromOutput[t]=i)):(i=s.type,void 0===i&&(i=this.generateNodeType(e),s.type=i)),i}generateNodeType(e,t=null){const s=e.getNodeProperties(this);return s.outputNode?s.outputNode.getNodeType(e,t):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let s=0;for(const e of this.getChildren())t["node"+s++]=e;return t.outputNode||null}analyze(e,t=null){const s=e.increaseUsage(this);if(!0===this.parents){const s=e.getDataFromNode(this,"any");s.stages=s.stages||{},s.stages[e.shaderStage]=s.stages[e.shaderStage]||[],s.stages[e.shaderStage].push(t)}if(1===s){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e,this)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){bt("Abstract function.")}updateAfter(){bt("Abstract function.")}update(){bt("Abstract function.")}before(e){return null===this._beforeNodes&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);if(null!==this._beforeNodes){const s=this._beforeNodes;this._beforeNodes=null;for(const i of s)i.build(e,t);this._beforeNodes=s}const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const r=ea[e.buildStage];if(r&&!0!==i.buildStages[r]){const t=e.getBuildStage();e.setBuildStage(r),this.build(e),e.setBuildStage(t)}e.addChain(this);let n=null;const a=e.getBuildStage();if("setup"===a){e.addNode(this),this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const s of Object.values(t))if(s&&!0===s.isNode){if(!0===s.parents){const t=e.getNodeProperties(s);t.parents=t.parents||[],t.parents.push(this)}s.build(e)}e.addSequentialNode(this)}n=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(this.generate.length<2){const s=this.getNodeType(e),i=e.getDataFromNode(this);n=i.snippet,void 0===n?void 0===i.generated?(i.generated=!0,n=this.generate(e)||"",i.snippet=n):(bt("Node: Recursion detected.",this),n="/* Recursion detected. */"):void 0!==i.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),n=e.format(n,s,t)}else n=this.generate(e,t)||"";""===n&&null!==t&&"void"!==t&&"OutputType"!==t&&(_t(`TSL: Invalid generated code, expected a "${t}".`),n=e.generateConst(t))}return e.removeChain(this),n}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:r,childNode:n}of t)void 0!==r?(void 0===s[i]&&(s[i]=Number.isInteger(r)?[]:{}),s[i][r]=n.toJSON(e.meta).uuid):s[i]=n.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const r of e.inputNodes[s])i.push(t[r]);this[s]=i}else if("object"==typeof e.inputNodes[s]){const i={};for(const r in e.inputNodes[s]){const n=e.inputNodes[s][r];i[r]=t[n]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:s,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=n(e.textures),s=n(e.images),i=n(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),i.length>0&&(r.nodes=i)}return r}}sa.captureStackTrace=!1;class ia extends sa{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}generateNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class ra extends sa{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))null!==s&&e.getTypeLength(t)!==e.getTypeLength(i)||(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),r=s.build(e,i);return e.format(r,i,t)}}class na extends sa{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const s=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,s,t);if("void"!==s&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,s),n=e.getVarFromNode(this,null,s),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${r}`,this),i.snippet=r,i.propertyName=a,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class aa extends na{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,s)=>t+e.getTypeLength(s.getNodeType(e)),0))}generate(e,t){const s=this.getNodeType(e),i=e.getTypeLength(s),r=this.nodes,n=e.getComponentType(s),a=[];let o=0;for(const t of r){if(o>=i){_t(`TSL: Length of parameters exceeds maximum length of function '${s}()' type.`,this.stackTrace);break}let r,h=t.getNodeType(e),l=e.getTypeLength(h);o+l>i&&(_t(`TSL: Length of '${s}()' data exceeds maximum length of output type.`,this.stackTrace),l=i-o,h=e.getTypeFromLength(l)),o+=l,r=t.build(e,h);if(e.getComponentType(h)!==n){const t=e.getTypeFromLength(l,n);r=e.format(r,h,t)}a.push(r)}const h=`${e.getType(s)}( ${a.join(", ")} )`;return e.format(h,s,t)}}const oa=Jn.join("");class ha extends sa{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(Jn.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let r=null;if(i>1){let n=null;this.getVectorLength()>=i&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=s.build(e,n);r=this.components.length===i&&this.components===oa.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else r=s.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class la extends na{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,r=this.getNodeType(e),n=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(s.length,n),o=i.build(e,a),h=t.build(e,r),l=e.getTypeLength(r),u=[];for(let e=0;e<l;e++){const t=Jn[e];t===s[0]?(u.push(o),e+=s.length-1):u.push(h+"."+t)}return`${e.getType(r)}( ${u.join(", ")} )`}}class ua extends na{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:s}=this,i=this.getNodeType(e),r=s.build(e),n=e.getVarFromNode(this),a=e.getPropertyName(n);e.addLineFlowCode(a+" = "+r,this);const o=e.getTypeLength(i),h=[];let l=0;for(let e=0;e<o;e++){const s=Jn[e];s===t[l]?(h.push("1.0 - "+a+"."+s),l++):h.push(a+"."+s)}return`${e.getType(i)}( ${h.join(", ")} )`}}class ca extends sa{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}generateNodeType(){return null===this.nodeType?zn(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=zn(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=function(e){let t="";const s=new Uint8Array(e);for(let e=0;e<s.length;e++)t+=String.fromCharCode(s[e]);return btoa(t)}(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?Vn(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){bt("Abstract function.")}}const da=/float|u?int/;class pa extends ca{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const s=this.getNodeType(e);return da.test(s)&&da.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class ma extends sa{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return(!this.structNode.isMemberNode||!1!==this.structNode.hasMember(e))&&"void"!==this.structNode.getMemberType(e,this.property)}generateNodeType(e){return!1===this.hasMember(e)?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(!1===this.hasMember(e))return"float";const s=this.getNodeType(e);return e.getStructTypeNode(s).getMemberType(e,t)}generate(e){if(!1===this.hasMember(e)){bt(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+"."+this.property}}let ga=null;const fa=new Map;function ya(e,t){if(fa.has(e))bt(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);fa.set(e,t),"assign"!==e&&(sa.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},sa.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const ba=e=>(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");sa.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==ga?ga.assign(this,...e):_t("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Bn),this;{const t=fa.get("assign");return this.addToStack(t(...e))}},sa.prototype.toVarIntent=function(){return this},sa.prototype.get=function(e){return new ma(this,e)};const _a={};function xa(e,t,s){_a[e]=_a[t]=_a[s]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new ha(this,e),this._cache[e]=t),t},set(t){this[e].assign(Wa(t))}};const i=e.toUpperCase(),r=t.toUpperCase(),n=s.toUpperCase();sa.prototype["set"+i]=sa.prototype["set"+r]=sa.prototype["set"+n]=function(t){const s=ba(e);return new la(this,s,Wa(t))},sa.prototype["flip"+i]=sa.prototype["flip"+r]=sa.prototype["flip"+n]=function(){const t=ba(e);return new ua(this,t)}}const va=["x","y","z","w"],Ta=["r","g","b","a"],Sa=["s","t","p","q"];for(let e=0;e<4;e++){let t=va[e],s=Ta[e],i=Sa[e];xa(t,s,i);for(let r=0;r<4;r++){t=va[e]+va[r],s=Ta[e]+Ta[r],i=Sa[e]+Sa[r],xa(t,s,i);for(let n=0;n<4;n++){t=va[e]+va[r]+va[n],s=Ta[e]+Ta[r]+Ta[n],i=Sa[e]+Sa[r]+Sa[n],xa(t,s,i);for(let a=0;a<4;a++)t=va[e]+va[r]+va[n]+va[a],s=Ta[e]+Ta[r]+Ta[n]+Ta[a],i=Sa[e]+Sa[r]+Sa[n]+Sa[a],xa(t,s,i)}}}for(let e=0;e<32;e++)_a[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new ia(this,new pa(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(Wa(t))}};Object.defineProperties(sa.prototype,_a);const wa=new WeakMap,Ma=function(e,t=null){for(const s in e)e[s]=Wa(e[s],t);return e},Na=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=Wa(e[i],t);return e},Aa=function(e,t=null,s=null,i=null){function r(e){return null!==i?(e=Wa(Object.assign(e,i)),!0===i.intent&&(e=e.toVarIntent())):e=Wa(e),e}let n,a,o,h=t;function l(t){let s;return s=h?/[a-z]/i.test(h)?h+"()":h:e.type,void 0!==a&&t.length<a?(_t(`TSL: "${s}" parameter length is less than minimum required.`,new Bn),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(_t(`TSL: "${s}" parameter length exceeds limit.`,new Bn),t.slice(0,o)):t}return null===t?n=(...t)=>r(new e(...Xa(l(t)))):null!==s?(s=Wa(s),n=(...i)=>r(new e(t,...Xa(l(i)),s))):n=(...s)=>r(new e(t,...Xa(l(s)))),n.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),n),n.setName=e=>(h=e,n),n},Ea=function(e,...t){return new e(...Xa(t))};class Ra extends sa{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}generateNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:s}=this,i=e.getNodeProperties(t),r=e.getClosestSubBuild(t.subBuilds)||"",n=r||"default";if(i[n])return i[n];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=r,e.fnCall=this;let h=null;if(t.layout){let i=wa.get(e.constructor);void 0===i&&(i=new WeakMap,wa.set(e.constructor,i));let r=i.get(t);void 0===r&&(r=Wa(e.buildFunctionNode(t)),i.set(t,r)),e.addInclude(r);const n=s?function(e){let t;qa(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(s):null;h=Wa(r.call(n))}else{const i=new Proxy(e,{get:(e,t,s)=>{let i;return i=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,s),i}}),r=s?function(e){let t=0;return qa(e),new Proxy(e,{get:(s,i,r)=>{let n;if("length"===i)return n=e.length,n;if(Symbol.iterator===i)n=function*(){for(const t of e)yield Wa(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const s=e[0];n=void 0===s[i]?s[t++]:Reflect.get(s,i,r)}else e[0]instanceof sa&&(n=void 0===e[i]?e[t++]:Reflect.get(e,i,r));else n=Reflect.get(s,i,r);n=Wa(n)}return n}})}(s):null,n=Array.isArray(s)?s.length>0:null!==s,a=t.jsFunc,o=n||a.length>1?a(r,i):a(i);h=Wa(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(i[n]=h),h}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),s=e.getSubBuildOutput(this);return t[s]=t[s]||this.setupOutput(e),t[s].subBuild=e.getClosestSubBuild(this),t[s]}build(e,t=null){let s=null;const i=e.getBuildStage(),r=e.getNodeProperties(this),n=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===i){const t=e.getSubBuildProperty("initialized",this);if(!0!==r[t]&&(r[t]=!0,r[n]=this.getOutputNode(e),r[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const s=e.getDataFromNode(t,"any");s.subBuilds=s.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)s.subBuilds.add(e)}s=r[n]}else"analyze"===i?a.build(e,t):"generate"===i&&(s=a.build(e,t)||"");return e.fnCall=o,s}}class Ca extends sa{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new Ra(this,e)}setup(){return this.call()}}const Pa=[!1,!0],Ba=[0,1,2,3],Fa=[-1,-2],La=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],Da=new Map;for(const e of Pa)Da.set(e,new pa(e));const Ia=new Map;for(const e of Ba)Ia.set(e,new pa(e,"uint"));const Oa=new Map([...Ia].map(e=>new pa(e.value,"int")));for(const e of Fa)Oa.set(e,new pa(e,"int"));const Ua=new Map([...Oa].map(e=>new pa(e.value)));for(const e of La)Ua.set(e,new pa(e));for(const e of La)Ua.set(-e,new pa(-e));const ka={bool:Da,uint:Ia,ints:Oa,float:Ua},za=new Map([...Da,...Ua]),Va=(e,t)=>za.has(e)?za.get(e):!0===e.isNode?e:new pa(e,t),Ga=function(e,t=null){return(...s)=>{for(const t of s)if(void 0===t)return _t(`TSL: Invalid parameter for the type "${e}".`,new Bn),new pa(0,e);if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(s=[Vn(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return Ha(t.get(s[0]));if(1===s.length){const t=Va(s[0],e);return t.nodeType===e?Ha(t):Ha(new ra(t,e))}const i=s.map(e=>Va(e));return Ha(new aa(i,e))}};function ja(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}function $a(e,t){return new Ca(e,t)}const Wa=(e,t=null)=>function(e,t=null){const s=zn(e);return"node"===s?e:null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?Wa(Va(e,t)):"shader"===s?e.isFn?e:eo(e):e}(e,t),Ha=(e,t=null)=>Wa(e,t).toVarIntent(),qa=(e,t=null)=>new Ma(e,t),Xa=(e,t=null)=>new Na(e,t),Ya=(e,t=null,s=null,i=null)=>new Aa(e,t,s,i),Ka=(e,...t)=>new Ea(e,...t),Qa=(e,t=null,s=null,i={})=>new Aa(e,t,s,{...i,intent:!0});let Za=0;class Ja extends sa{constructor(e,t=null){super();let s=null;null!==t&&("object"==typeof t?s=t.return:("string"==typeof t?s=t:_t("TSL: Invalid layout type.",new Bn),t=null)),this.shaderNode=new $a(e,s),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const s={name:"fn"+Za++,type:t,inputs:[]};for(const t in e)"return"!==t&&s.inputs.push({name:t,type:e[t]});e=s}return this.shaderNode.setLayout(e),this}generateNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return _t('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function eo(e,t=null){const s=new Ja(e,t);return new Proxy(()=>{},{apply:(e,t,i)=>s.call(...i),get:(e,t,i)=>Reflect.get(s,t,i),set:(e,t,i,r)=>Reflect.set(s,t,i,r)})}const to=e=>{ga=e},so=()=>ga,io=(...e)=>ga.If(...e);function ro(e){return ga&&ga.addToStack(e),e}ya("toStack",ro);const no=new Ga("color"),ao=new Ga("float",ka.float),oo=new Ga("int",ka.ints),ho=new Ga("uint",ka.uint),lo=new Ga("bool",ka.bool),uo=new Ga("vec2"),co=new Ga("ivec2"),po=new Ga("uvec2"),mo=new Ga("bvec2"),go=new Ga("vec3"),fo=new Ga("ivec3"),yo=new Ga("uvec3"),bo=new Ga("bvec3"),_o=new Ga("vec4"),xo=new Ga("ivec4"),vo=new Ga("uvec4"),To=new Ga("bvec4"),So=new Ga("mat2"),wo=new Ga("mat3"),Mo=new Ga("mat4");ya("toColor",no),ya("toFloat",ao),ya("toInt",oo),ya("toUint",ho),ya("toBool",lo),ya("toVec2",uo),ya("toIVec2",co),ya("toUVec2",po),ya("toBVec2",mo),ya("toVec3",go),ya("toIVec3",fo),ya("toUVec3",yo),ya("toBVec3",bo),ya("toVec4",_o),ya("toIVec4",xo),ya("toUVec4",vo),ya("toBVec4",To),ya("toMat2",So),ya("toMat3",wo),ya("toMat4",Mo);ya("element",Ya(ia).setParameterLength(2)),ya("convert",(e,t)=>new ra(Wa(e),t)),ya("append",e=>(bt("TSL: .append() has been renamed to .toStack().",new Bn),ro(e)));class No extends sa{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return Ln(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Ao=(e,t)=>new No(e,t),Eo=(e,t)=>new No(e,t,!0),Ro=Ka(No,"vec4","DiffuseColor"),Co=Ka(No,"vec3","DiffuseContribution"),Po=Ka(No,"vec3","EmissiveColor"),Bo=Ka(No,"float","Roughness"),Fo=Ka(No,"float","Metalness"),Lo=Ka(No,"float","Clearcoat"),Do=Ka(No,"float","ClearcoatRoughness"),Io=Ka(No,"vec3","Sheen"),Oo=Ka(No,"float","SheenRoughness"),Uo=Ka(No,"float","Iridescence"),ko=Ka(No,"float","IridescenceIOR"),zo=Ka(No,"float","IridescenceThickness"),Vo=Ka(No,"float","AlphaT"),Go=Ka(No,"float","Anisotropy"),jo=Ka(No,"vec3","AnisotropyT"),$o=Ka(No,"vec3","AnisotropyB"),Wo=Ka(No,"color","SpecularColor"),Ho=Ka(No,"color","SpecularColorBlended"),qo=Ka(No,"float","SpecularF90"),Xo=Ka(No,"float","Shininess"),Yo=Ka(No,"vec4","Output"),Ko=Ka(No,"float","dashSize"),Qo=Ka(No,"float","gapSize"),Zo=Ka(No,"float","IOR"),Jo=Ka(No,"float","Transmission"),eh=Ka(No,"float","Thickness"),th=Ka(No,"float","AttenuationDistance"),sh=Ka(No,"color","AttenuationColor"),ih=Ka(No,"float","Dispersion");class rh extends sa{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1,i=null){super("string"),this.name=e,this.shared=t,this.order=s,this.updateType=i,this.isUniformGroup=!0}update(){this.needsUpdate=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const nh=(e,t=1,s=null)=>new rh(e,!1,t,s),ah=(e,t=0,s=null)=>new rh(e,!0,t,s),oh=ah("render",0,Hn),hh=nh("object",1,qn);class lh extends ca{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=hh}setName(e){return this.name=e,this}label(e){return bt('TSL: "label()" has been deprecated. Use "setName()" instead.',new Bn),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const s=e(t,this);void 0!==s&&(this.value=s)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const n=r.getInputType(e),a=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let h=o;if("bool"===s){const t=e.getDataFromNode(this);let i=t.propertyName;if(void 0===i){const r=e.getVarFromNode(this,null,"bool");i=e.getPropertyName(r),t.propertyName=i,h=e.format(o,n,s),e.addLineFlowCode(`${i} = ${h}`,this)}h=i}return e.format(h,s,t)}}const uh=(e,t)=>{const s=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e);if(s===e&&(e=Vn(s)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new lh(e,s)};class ch extends na{static get type(){return"ArrayNode"}constructor(e,t,s=null){super(e),this.count=t,this.values=s,this.isArrayNode=!0}getArrayCount(){return this.count}generateNodeType(e){return null===this.nodeType?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return null===this.nodeType?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}ya("toArray",(e,t)=>((...e)=>{let t;if(1===e.length){const s=e[0];t=new ch(null,s.length,s)}else{const s=e[0],i=e[1];t=new ch(s,i)}return Wa(t)})(Array(t).fill(e)));class dh extends na{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}generateNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const s=e.getTypeLength(t.node.getNodeType(e));return Jn.join("").slice(0,s)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:s}=this,i=t.getScope();e.getDataFromNode(i).assign=!0;const r=e.getNodeProperties(this);r.sourceNode=s,r.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:s,sourceNode:i}=e.getNodeProperties(this),r=this.needsSplitAssign(e),n=s.build(e),a=s.getNodeType(e),o=i.build(e,a),h=i.getNodeType(e),l=e.getDataFromNode(this);let u;if(!0===l.initialized)"void"!==t&&(u=n);else if(r){const i=e.getVarFromNode(this,null,a),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`,this);const h=s.node,l=h.node.context({assign:!0}).build(e);for(let t=0;t<h.components.length;t++){const s=h.components[t];e.addLineFlowCode(`${l}.${s} = ${r}[ ${t} ]`,this)}"void"!==t&&(u=n)}else u=`${n} = ${o}`,"void"!==t&&"void"!==h||(e.addLineFlowCode(u,this),"void"!==t&&(u=n));return l.initialized=!0,e.format(u,a,t)}}ya("assign",Ya(dh).setParameterLength(2));class ph extends na{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}generateNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],s=this.functionNode,i=s.getInputs(e),r=this.parameters,n=(t,s)=>{const i=s.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r)){if(r.length>i.length)_t("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),r.length=i.length;else if(r.length<i.length)for(_t("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(ao(0));for(let e=0;e<r.length;e++)t.push(n(r[e],i[e]))}else for(const e of i){const s=r[e.name];void 0!==s?t.push(n(s,e)):(_t(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(n(ao(0),e)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}ya("call",(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?Xa(t):qa(t[0]),new ph(Wa(e),t)));const mh={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class gh extends na{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new gh(e,t,s);for(let t=0;t<i.length-1;t++)r=new gh(e,r,i[t]);t=r,s=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=s,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(mh[this.op],t)}generateNodeType(e,t=null){const s=this.op,i=this.aNode,r=this.bNode,n=i.getNodeType(e),a=r?r.getNodeType(e):null;if("void"===n||"void"===a)return t||"void";if("%"===s)return n;if("~"===s||"&"===s||"|"===s||"^"===s||">>"===s||"<<"===s)return e.getIntegerType(n);if("!"===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s){const t=Math.max(e.getTypeLength(n),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const s=this.op,{aNode:i,bNode:r}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=i.getNodeType(e),o=r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s||"!="===s?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===s||"<<"===s?(a=n,o=e.changeComponentType(o,"uint")):"%"===s?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const h=i.build(e,a),l=r?r.build(e,o):null,u=e.getFunctionOperator(s);if("void"!==t){const i=e.renderer.coordinateSystem===ht;if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s)return i&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} ${s} ${l} )`,n,t);if("%"===s)return e.isInteger(o)?e.format(`( ${h} % ${l} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${h}, ${l} )`,n,t);if("!"===s||"~"===s)return e.format(`(${s}${h})`,a,t);if(u)return e.format(`${u}( ${h}, ${l} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${l} ${s} ${h} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${h} ${s} ${l}`,n,t);{let r=`( ${h} ${s} ${l} )`;return!i&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(r=`all${r}`),e.format(r,n,t)}}if("void"!==a)return u?e.format(`${u}( ${h}, ${l} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${l} ${s} ${h}`,n,t):e.format(`${h} ${s} ${l}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const fh=Qa(gh,"+").setParameterLength(2,1/0).setName("add"),yh=Qa(gh,"-").setParameterLength(2,1/0).setName("sub"),bh=Qa(gh,"*").setParameterLength(2,1/0).setName("mul"),_h=Qa(gh,"/").setParameterLength(2,1/0).setName("div"),xh=Qa(gh,"%").setParameterLength(2).setName("mod"),vh=Qa(gh,"==").setParameterLength(2).setName("equal"),Th=Qa(gh,"!=").setParameterLength(2).setName("notEqual"),Sh=Qa(gh,"<").setParameterLength(2).setName("lessThan"),wh=Qa(gh,">").setParameterLength(2).setName("greaterThan"),Mh=Qa(gh,"<=").setParameterLength(2).setName("lessThanEqual"),Nh=Qa(gh,">=").setParameterLength(2).setName("greaterThanEqual"),Ah=Qa(gh,"&&").setParameterLength(2,1/0).setName("and"),Eh=Qa(gh,"||").setParameterLength(2,1/0).setName("or"),Rh=Qa(gh,"!").setParameterLength(1).setName("not"),Ch=Qa(gh,"^^").setParameterLength(2).setName("xor"),Ph=Qa(gh,"&").setParameterLength(2).setName("bitAnd"),Bh=Qa(gh,"~").setParameterLength(1).setName("bitNot"),Fh=Qa(gh,"|").setParameterLength(2).setName("bitOr"),Lh=Qa(gh,"^").setParameterLength(2).setName("bitXor"),Dh=Qa(gh,"<<").setParameterLength(2).setName("shiftLeft"),Ih=Qa(gh,">>").setParameterLength(2).setName("shiftRight"),Oh=eo(([e])=>(e.addAssign(1),e)),Uh=eo(([e])=>(e.subAssign(1),e)),kh=eo(([e])=>{const t=oo(e).toConst();return e.addAssign(1),t}),zh=eo(([e])=>{const t=oo(e).toConst();return e.subAssign(1),t});ya("add",fh),ya("sub",yh),ya("mul",bh),ya("div",_h),ya("mod",xh),ya("equal",vh),ya("notEqual",Th),ya("lessThan",Sh),ya("greaterThan",wh),ya("lessThanEqual",Mh),ya("greaterThanEqual",Nh),ya("and",Ah),ya("or",Eh),ya("not",Rh),ya("xor",Ch),ya("bitAnd",Ph),ya("bitNot",Bh),ya("bitOr",Fh),ya("bitXor",Lh),ya("shiftLeft",Dh),ya("shiftRight",Ih),ya("incrementBefore",Oh),ya("decrementBefore",Uh),ya("increment",kh),ya("decrement",zh);ya("modInt",(e,t)=>(bt('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new Bn),xh(oo(e),oo(t))));class Vh extends na{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===Vh.MAX||e===Vh.MIN)&&arguments.length>3){let r=new Vh(e,t,s);for(let t=2;t<arguments.length-1;t++)r=new Vh(e,r,arguments[t]);t=r,s=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=s,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s),a=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>a?t:n>a?s:a>r?i:t}generateNodeType(e){const t=this.method;return t===Vh.LENGTH||t===Vh.DISTANCE||t===Vh.DOT?"float":t===Vh.CROSS?"vec3":t===Vh.ALL||t===Vh.ANY?"bool":t===Vh.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:s,method:i}=this;let r=null;if(i===Vh.ONE_MINUS)r=yh(1,t);else if(i===Vh.RECIPROCAL)r=_h(1,t);else if(i===Vh.DIFFERENCE)r=fl(yh(t,s));else if(i===Vh.TRANSFORM_DIRECTION){let i=t,n=s;e.isMatrix(i.getNodeType(e))?n=_o(go(n),0):i=_o(go(i),0);const a=bh(i,n).xyz;r=sl(a)}return null!==r?r:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let s=this.method;const i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,a=this.bNode,o=this.cNode,h=e.renderer.coordinateSystem;if(s===Vh.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);{const l=[];return s===Vh.CROSS?l.push(n.build(e,i),a.build(e,i)):h===ht&&s===Vh.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),a.build(e,r)):h!==ht||s!==Vh.MIN&&s!==Vh.MAX?s===Vh.REFRACT?l.push(n.build(e,r),a.build(e,r),o.build(e,"float")):s===Vh.MIX?l.push(n.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(h===lt&&s===Vh.ATAN&&null!==a&&(s="atan2"),"fragment"===e.shaderStage||s!==Vh.DFDX&&s!==Vh.DFDY||(bt(`TSL: '${s}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),s="/*"+s+"*/"),l.push(n.build(e,r)),null!==a&&l.push(a.build(e,r)),null!==o&&l.push(o.build(e,r))):l.push(n.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)),e.format(`${e.getMethod(s,i)}( ${l.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Vh.ALL="all",Vh.ANY="any",Vh.RADIANS="radians",Vh.DEGREES="degrees",Vh.EXP="exp",Vh.EXP2="exp2",Vh.LOG="log",Vh.LOG2="log2",Vh.SQRT="sqrt",Vh.INVERSE_SQRT="inversesqrt",Vh.FLOOR="floor",Vh.CEIL="ceil",Vh.NORMALIZE="normalize",Vh.FRACT="fract",Vh.SIN="sin",Vh.SINH="sinh",Vh.COS="cos",Vh.COSH="cosh",Vh.TAN="tan",Vh.TANH="tanh",Vh.ASIN="asin",Vh.ASINH="asinh",Vh.ACOS="acos",Vh.ACOSH="acosh",Vh.ATAN="atan",Vh.ATANH="atanh",Vh.ABS="abs",Vh.SIGN="sign",Vh.LENGTH="length",Vh.NEGATE="negate",Vh.ONE_MINUS="oneMinus",Vh.DFDX="dFdx",Vh.DFDY="dFdy",Vh.ROUND="round",Vh.RECIPROCAL="reciprocal",Vh.TRUNC="trunc",Vh.FWIDTH="fwidth",Vh.TRANSPOSE="transpose",Vh.DETERMINANT="determinant",Vh.INVERSE="inverse",Vh.EQUALS="equals",Vh.MIN="min",Vh.MAX="max",Vh.STEP="step",Vh.REFLECT="reflect",Vh.DISTANCE="distance",Vh.DIFFERENCE="difference",Vh.DOT="dot",Vh.CROSS="cross",Vh.POW="pow",Vh.TRANSFORM_DIRECTION="transformDirection",Vh.MIX="mix",Vh.CLAMP="clamp",Vh.REFRACT="refract",Vh.SMOOTHSTEP="smoothstep",Vh.FACEFORWARD="faceforward";const Gh=ao(1e-6),jh=ao(Math.PI),$h=Qa(Vh,Vh.ALL).setParameterLength(1),Wh=Qa(Vh,Vh.ANY).setParameterLength(1),Hh=Qa(Vh,Vh.RADIANS).setParameterLength(1),qh=Qa(Vh,Vh.DEGREES).setParameterLength(1),Xh=Qa(Vh,Vh.EXP).setParameterLength(1),Yh=Qa(Vh,Vh.EXP2).setParameterLength(1),Kh=Qa(Vh,Vh.LOG).setParameterLength(1),Qh=Qa(Vh,Vh.LOG2).setParameterLength(1),Zh=Qa(Vh,Vh.SQRT).setParameterLength(1),Jh=Qa(Vh,Vh.INVERSE_SQRT).setParameterLength(1),el=Qa(Vh,Vh.FLOOR).setParameterLength(1),tl=Qa(Vh,Vh.CEIL).setParameterLength(1),sl=Qa(Vh,Vh.NORMALIZE).setParameterLength(1),il=Qa(Vh,Vh.FRACT).setParameterLength(1),rl=Qa(Vh,Vh.SIN).setParameterLength(1),nl=Qa(Vh,Vh.SINH).setParameterLength(1),al=Qa(Vh,Vh.COS).setParameterLength(1),ol=Qa(Vh,Vh.COSH).setParameterLength(1),hl=Qa(Vh,Vh.TAN).setParameterLength(1),ll=Qa(Vh,Vh.TANH).setParameterLength(1),ul=Qa(Vh,Vh.ASIN).setParameterLength(1),cl=Qa(Vh,Vh.ASINH).setParameterLength(1),dl=Qa(Vh,Vh.ACOS).setParameterLength(1),pl=Qa(Vh,Vh.ACOSH).setParameterLength(1),ml=Qa(Vh,Vh.ATAN).setParameterLength(1,2),gl=Qa(Vh,Vh.ATANH).setParameterLength(1),fl=Qa(Vh,Vh.ABS).setParameterLength(1),yl=Qa(Vh,Vh.SIGN).setParameterLength(1),bl=Qa(Vh,Vh.LENGTH).setParameterLength(1),_l=Qa(Vh,Vh.NEGATE).setParameterLength(1),xl=Qa(Vh,Vh.ONE_MINUS).setParameterLength(1),vl=Qa(Vh,Vh.DFDX).setParameterLength(1),Tl=Qa(Vh,Vh.DFDY).setParameterLength(1),Sl=Qa(Vh,Vh.ROUND).setParameterLength(1),wl=Qa(Vh,Vh.RECIPROCAL).setParameterLength(1),Ml=Qa(Vh,Vh.TRUNC).setParameterLength(1),Nl=Qa(Vh,Vh.FWIDTH).setParameterLength(1),Al=Qa(Vh,Vh.TRANSPOSE).setParameterLength(1),El=Qa(Vh,Vh.DETERMINANT).setParameterLength(1),Rl=Qa(Vh,Vh.INVERSE).setParameterLength(1),Cl=Qa(Vh,Vh.MIN).setParameterLength(2,1/0),Pl=Qa(Vh,Vh.MAX).setParameterLength(2,1/0),Bl=Qa(Vh,Vh.STEP).setParameterLength(2),Fl=Qa(Vh,Vh.REFLECT).setParameterLength(2),Ll=Qa(Vh,Vh.DISTANCE).setParameterLength(2),Dl=Qa(Vh,Vh.DIFFERENCE).setParameterLength(2),Il=Qa(Vh,Vh.DOT).setParameterLength(2),Ol=Qa(Vh,Vh.CROSS).setParameterLength(2),Ul=Qa(Vh,Vh.POW).setParameterLength(2),kl=e=>bh(e,e),zl=e=>bh(e,e,e,e),Vl=Qa(Vh,Vh.TRANSFORM_DIRECTION).setParameterLength(2),Gl=e=>Il(e,e),jl=Qa(Vh,Vh.MIX).setParameterLength(3),$l=(e,t=0,s=1)=>new Vh(Vh.CLAMP,Wa(e),Wa(t),Wa(s)),Wl=e=>$l(e),Hl=Qa(Vh,Vh.REFRACT).setParameterLength(3),ql=Qa(Vh,Vh.SMOOTHSTEP).setParameterLength(3),Xl=Qa(Vh,Vh.FACEFORWARD).setParameterLength(3),Yl=eo(([e])=>{const t=Il(e.xy,uo(12.9898,78.233)),s=xh(t,jh);return il(rl(s).mul(43758.5453))});ya("all",$h),ya("any",Wh),ya("radians",Hh),ya("degrees",qh),ya("exp",Xh),ya("exp2",Yh),ya("log",Kh),ya("log2",Qh),ya("sqrt",Zh),ya("inverseSqrt",Jh),ya("floor",el),ya("ceil",tl),ya("normalize",sl),ya("fract",il),ya("sin",rl),ya("sinh",nl),ya("cos",al),ya("cosh",ol),ya("tan",hl),ya("tanh",ll),ya("asin",ul),ya("asinh",cl),ya("acos",dl),ya("acosh",pl),ya("atan",ml),ya("atanh",gl),ya("abs",fl),ya("sign",yl),ya("length",bl),ya("lengthSq",Gl),ya("negate",_l),ya("oneMinus",xl),ya("dFdx",vl),ya("dFdy",Tl),ya("round",Sl),ya("reciprocal",wl),ya("trunc",Ml),ya("fwidth",Nl),ya("min",Cl),ya("max",Pl),ya("step",(e,t)=>Bl(t,e)),ya("reflect",Fl),ya("distance",Ll),ya("dot",Il),ya("cross",Ol),ya("pow",Ul),ya("pow2",kl),ya("pow3",e=>bh(e,e,e)),ya("pow4",zl),ya("transformDirection",Vl),ya("mix",(e,t,s)=>jl(t,s,e)),ya("clamp",$l),ya("refract",Hl),ya("smoothstep",(e,t,s)=>ql(t,s,e)),ya("faceForward",Xl),ya("difference",Dl),ya("saturate",Wl),ya("cbrt",e=>bh(yl(e),Ul(fl(e),1/3))),ya("transpose",Al),ya("determinant",El),ya("inverse",Rl),ya("rand",Yl);class Kl extends sa{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}generateNodeType(e){const{ifNode:t,elseNode:s}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const i=t.getNodeType(e);if(null!==s){const t=s.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(i))return t}return i}setup(e){const t=this.condNode,s=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,r=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const n=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?s:s.context({nodeBlock:s}),a.elseNode=i?n?i:i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:n,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,h="void"!==t,l=h?Ao(s).build(e):"";i.nodeProperty=l;const u=r.build(e,"bool");if(e.context.uniformFlow&&null!==a){const i=n.build(e,s),r=a.build(e,s),o=e.getTernary(u,i,r);return e.format(o,s,t)}e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let c=n.build(e,s);if(c&&(h?c=l+" = "+c+";":(c="return "+c+";",null===o&&(bt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,s);t&&(h?t=l+" = "+t+";":(t="return "+t+";",null===o&&(bt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,s,t)}}const Ql=Ya(Kl).setParameterLength(2,3);ya("select",Ql);class Zl extends sa{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const s=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(s),i}}const Jl=(e=null,t={})=>{let s=e;return null!==s&&!0===s.isNode||(t=s||t,s=null),new Zl(s,t)},eu=(e,t)=>Jl(e,{nodeName:t});ya("context",Jl),ya("label",function(e,t){return bt('TSL: "label()" has been deprecated. Use "setName()" instead.'),eu(e,t)}),ya("uniformFlow",e=>Jl(e,{uniformFlow:!0})),ya("setName",eu),ya("builtinShadowContext",(e,t,s)=>function(e,t,s=null){return Jl(s,{getShadow:({light:s,shadowColorNode:i})=>t===s?i.mul(e):i})}(t,s,e)),ya("builtinAOContext",(e,t)=>function(e,t=null){return Jl(t,{getAO:(t,{material:s})=>!0===s.transparent?t:null!==t?t.mul(e):e})}(t,e));class tu extends sa{static get type(){return"VarNode"}constructor(e,t=null,s=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=s,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const s=t.getBaseStack();e?s.addToStackBefore(this):s.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:s,readOnly:i}=this,{renderer:r}=e,n=!0===r.backend.isWebGPUBackend;let a=!1,o=!1;i&&(a=e.isDeterministic(t),o=n?i:a);const h=this.getNodeType(e);if("void"==h){!0!==this.isIntent(e)&&_t('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const l=e.getVectorType(h),u=t.build(e,l),c=e.getVarFromNode(this,s,l,void 0,o),d=e.getPropertyName(c);let p=d;if(o)if(n)p=a?`const ${d}`:`let ${d}`;else{const s=t.getArrayCount(e);p=`const ${e.getVar(c.type,d,s)}`}return e.addLineFlowCode(`${p} = ${u}`,this),d}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const su=Ya(tu);ya("toVar",(e,t=null)=>su(e,t).toStack()),ya("toConst",(e,t=null)=>su(e,t,!0).toStack()),ya("toVarIntent",e=>su(e).setIntent(!0).toStack());class iu extends sa{static get type(){return"SubBuild"}constructor(e,t,s=null){super(s),this.node=e,this.name=t,this.isSubBuildNode=!0}generateNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const s=this.node.build(e,...t);return e.removeSubBuild(),s}}const ru=(e,t,s=null)=>new iu(Wa(e),t,s);class nu extends sa{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=ru(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}generateNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(void 0===s){const i=this.name,r=this.getNodeType(e),n=this.interpolationType,a=this.interpolationSampling;t.varying=s=e.getVaryingFromNode(this,i,r,n,a),t.node=ru(this.node,"VERTEX")}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(jn,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(jn,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),s=e.getNodeProperties(this),i=this.setupVarying(e);if(void 0===s[t]){const r=this.getNodeType(e),n=e.getPropertyName(i,jn);e.flowNodeFromShaderStage(jn,s.node,r,n),s[t]=n}return e.getPropertyName(i)}}const au=Ya(nu).setParameterLength(1,2);ya("toVarying",au),ya("toVertexStage",e=>au(e));const ou=eo(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return jl(t,s,i)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),hu=eo(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return jl(t,s,i)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),lu="WorkingColorSpace";class uu extends na{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}resolveColorSpace(e,t){return t===lu?Wt.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,s=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let r=t;return!1!==Wt.enabled&&s!==i&&s&&i?(Wt.getTransfer(s)===Ke&&(r=_o(ou(r.rgb),r.a)),Wt.getPrimaries(s)!==Wt.getPrimaries(i)&&(r=_o(wo(Wt._getMatrix(new zt,s,i)).mul(r.rgb),r.a)),Wt.getTransfer(i)===Ke&&(r=_o(hu(r.rgb),r.a)),r):r}}const cu=(e,t)=>new uu(Wa(e),t,lu);ya("workingToColorSpace",(e,t)=>new uu(Wa(e),lu,t)),ya("colorSpaceToWorking",cu);let du=class extends ia{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class pu extends sa{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=qn}setGroup(e){return this.group=e,this}element(e){return new du(this,Wa(e))}setNodeType(e){const t=uh(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}generateNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;e<t.length;e++)s=s[t[e]];return s}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}class mu extends pu{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(oh)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const gu=(e,t,s=null)=>new mu(e,t,s);class fu extends na{static get type(){return"ToneMappingNode"}constructor(e,t=yu,s=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return In(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,s=this._toneMapping;if(0===s)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(s);return null!==r?i=_o(r(t.rgb,this.exposureNode),t.a):(_t("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const yu=gu("toneMappingExposure","float");ya("toneMapping",(e,t,s)=>((e,t,s)=>new fu(e,Wa(t),Wa(s)))(t,s,e));const bu=new WeakMap;function _u(e,t){let s=bu.get(e);return void 0===s&&(s=new Gi(e,t),bu.set(e,s)),s}class xu extends ca{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=at,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){let t;if(0===this.bufferStride&&0===this.bufferOffset){let s=e.globalCache.getData(this.value);void 0===s&&(s={node:this},e.globalCache.setData(this.value,s)),t=s.node.id}else t=this.id;return String(t)}generateNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),s=e.getTypeLength(t),i=this.value,r=this.bufferStride||s,n=this.bufferOffset;let a;a=!0===i.isInterleavedBuffer?i:!0===i.isBufferAttribute?_u(i.array,r):_u(i,r);const o=new $i(a,s,n);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=au(this).build(e,t)}return r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function vu(e,t=null,s=0,i=0,r=35044,n=!1){return"mat3"===t||null===t&&9===e.itemSize?wo(new xu(e,"vec3",9,0).setUsage(r).setInstanced(n),new xu(e,"vec3",9,3).setUsage(r).setInstanced(n),new xu(e,"vec3",9,6).setUsage(r).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?Mo(new xu(e,"vec4",16,0).setUsage(r).setInstanced(n),new xu(e,"vec4",16,4).setUsage(r).setInstanced(n),new xu(e,"vec4",16,8).setUsage(r).setInstanced(n),new xu(e,"vec4",16,12).setUsage(r).setInstanced(n)):new xu(e,t,s,i).setUsage(r)}const Tu=(e,t=null,s=0,i=0)=>vu(e,t,s,i),Su=(e,t=null,s=0,i=0)=>vu(e,t,s,i,at,!0),wu=(e,t=null,s=0,i=0)=>vu(e,t,s,i,ot,!0);ya("toAttribute",e=>Tu(e.value));class Mu extends sa{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i,r;if(s===Mu.VERTEX)i=e.getVertexIndex();else if(s===Mu.INSTANCE)i=e.getInstanceIndex();else if(s===Mu.DRAW)i=e.getDrawIndex();else if(s===Mu.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===Mu.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==Mu.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=au(this).build(e,t)}return r}}Mu.VERTEX="vertex",Mu.INSTANCE="instance",Mu.SUBGROUP="subgroup",Mu.INVOCATION_LOCAL="invocationLocal",Mu.INVOCATION_SUBGROUP="invocationSubgroup",Mu.DRAW="draw";const Nu=Ka(Mu,Mu.VERTEX),Au=Ka(Mu,Mu.INSTANCE);Mu.SUBGROUP,Mu.INVOCATION_SUBGROUP,Mu.INVOCATION_LOCAL;const Eu=Ka(Mu,Mu.DRAW);class Ru extends sa{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.updateBeforeType=qn,this.onInitFunction=null,this.countNode=null}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return bt('TSL: "label()" has been deprecated. Use "setName()" instead.',new Bn),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=uh(this.count,"uint").onObjectUpdate(()=>this.count));const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:s}=e;if("compute"===s){const t=this.computeNode.build(e,"void");if(""!==t&&e.addLineFlowCode(t,this),null!==this.count&&!0===e.allowEarlyReturns){const t=this.countNode.build(e,"uint"),s=Au.build(e,"uint");e.flow.code=`${e.tab}if ( ${s} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{const s=e.getNodeProperties(this).outputComputeNode;if(s)return s.build(e,t)}}}const Cu=(e,t=[64])=>{(0===t.length||t.length>3)&&_t("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Bn);for(let e=0;e<t.length;e++){const s=t[e];("number"!=typeof s||s<=0||!Number.isInteger(s))&&_t(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`,new Bn)}for(;t.length<3;)t.push(1);return new Ru(Wa(e),t)};ya("compute",(e,t,s)=>{const i=Cu(e,s);return"number"==typeof t?i.count=t:i.dispatchSize=t,i}),ya("computeKernel",Cu);class Pu extends sa{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(e){const t=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(s),r}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const Bu=e=>new Pu(Wa(e));ya("cache",function(e,t=!0){return bt('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),Bu(e).setParent(t)}),ya("isolate",Bu);class Fu extends sa{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}generateNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}ya("bypass",Ya(Fu).setParameterLength(2));const Lu=eo(([e,t,s,i=ao(0),r=ao(1),n=lo(!1)])=>{let a=e.sub(t).div(s.sub(t));return ja(n)&&(a=a.clamp()),a.mul(r.sub(i)).add(i)});ya("remap",Lu),ya("remapClamp",function(e,t,s,i=ao(0),r=ao(1)){return Lu(e,t,s,i,r,!0)});class Du extends sa{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if("void"!==s)return e.format(i,s,t);e.addLineFlowCode(i,this)}}const Iu=Ya(Du).setParameterLength(1,2);ya("discard",e=>(e?Ql(e,Iu("discard")):Iu("discard")).toStack());class Ou extends na{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=s,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const s=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||He;return 0!==s&&(t=t.toneMapping(s)),i!==He&&i!==Wt.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const Uu=(e,t=null,s=null)=>new Ou(Wa(e),t,s);ya("renderOutput",Uu);class ku extends na{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,s=this.node.build(e);if(null!==t)t(e,s);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(t.length);let r="";r+="// #"+t+"#\n",r+=e.flow.code.replace(/^\t/gm,"")+"\n",r+="/* ... */ "+s+" /* ... */\n",r+="// #"+i+"#\n",ft(r)}return s}}ya("debug",(e,t=null)=>new ku(Wa(e),t).toStack());class zu extends St{constructor(){super(),this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class Vu extends sa{static get type(){return"InspectorNode"}constructor(e,t="",s=null){super(),this.node=e,this.name=t,this.callback=s,this.updateType=Wn,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}generateNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return!0===e.context.inspector&&null!==this.callback&&(t=this.callback(t)),!0!==e.renderer.backend.isWebGPUBackend&&e.renderer.inspector.constructor!==zu&&xt('TSL: ".toInspector()" is only available with WebGPU.'),t}}ya("toInspector",function(e,t="",s=null){return(e=Wa(e)).before(new Vu(e,t,s))});class Gu extends sa{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}generateNodeType(e){let t=this.nodeType;if(null===t){const s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const i=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),n=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(n.name,r,s);return au(this).build(e,s)}return bt(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(s)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const ju=(e,t=null)=>new Gu(e,t),$u=(e=0)=>ju("uv"+(e>0?e:""),"vec2");class Wu extends sa{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const Hu=Ya(Wu).setParameterLength(1,2);class qu extends lh{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Wn}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&void 0!==s.width){const{width:e,height:t}=s;this.value=Math.log2(Math.max(e,t))}}}const Xu=Ya(qu).setParameterLength(1);class Yu extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const Ku=new ts;class Qu extends lh{static get type(){return"TextureNode"}constructor(e=Ku,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=$n,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===X?"uvec4":this.value.type===q?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return $u(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=uh(this.value.matrix)),this._matrixUniform.mul(go(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=uh(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(oo(Hu(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const s=this.value;if(!s||!0!==s.isTexture)throw new Yu("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const i=eo(()=>{let t=this.uvNode;return null!==t&&!0!==e.context.forceUVContext||!e.context.getUV||(t=e.context.getUV(this,e)),t||(t=this.getDefaultUV()),!0===this.updateMatrix&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=null!==this._matrixUniform||null!==this._flipYUniform?qn:$n,t})();let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this));let n=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(dt))n=this.compareNode;else{const e=s.compareFunction;null===e||513===e||e===tt||e===st||e===rt?a=this.compareNode:(n=this.compareNode,xt('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=n,t.compareStepNode=a,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,s,i,r,n,a,o,h){const l=this.value;let u;return u=r?e.generateTextureBias(l,t,s,r,n,h):o?e.generateTextureGrad(l,t,s,o,n,h):a?e.generateTextureCompare(l,t,s,a,n,h):!1===this.sampler?e.generateTextureLoad(l,t,s,i,n,h):i?e.generateTextureLevel(l,t,s,i,n,h):e.generateTexture(l,t,s,n,h),u}generate(e,t){const s=this.value,i=e.getNodeProperties(this),r=super.generate(e,"property");if(/^sampler/.test(t))return r+"_sampler";if(e.isReference(t))return r;{const n=e.getDataFromNode(this),a=this.getNodeType(e);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:h,biasNode:l,compareNode:u,compareStepNode:c,depthNode:d,gradNode:p,offsetNode:m}=i,g=this.generateUV(e,t),f=h?h.build(e,"float"):null,y=l?l.build(e,"float"):null,b=d?d.build(e,"int"):null,_=u?u.build(e,"float"):null,x=c?c.build(e,"float"):null,v=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,T=m?this.generateOffset(e,m):null;let S=b;null===S&&s.isArrayTexture&&!0!==this.isTexture3DNode&&(S="0");const w=e.getVarFromNode(this);o=e.getPropertyName(w);let M=this.generateSnippet(e,r,g,f,y,S,_,v,T);if(null!==x){const t=s.compareFunction;M=t===st||t===rt?Bl(Iu(M,a),Iu(x,"float")).build(e,a):Bl(Iu(x,"float"),Iu(M,a)).build(e,a)}e.addLineFlowCode(`${o} = ${M}`,this),n.snippet=M,n.propertyName=o}let h=o;return e.needsToWorkingColorSpace(s)&&(h=cu(Iu(h,a),s.colorSpace).setup(e).build(e,a)),e.format(h,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=Wa(e).mul(Xu(t)),t.referenceNode=this.getBase();const s=t.value;return!1===t.generateMipmaps&&(s&&!1===s.generateMipmaps||s.minFilter===O||s.magFilter===O)&&(bt("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Wa(t)}level(e){const t=this.clone();return t.levelNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}size(e){return Hu(this,e)}bias(e){const t=this.clone();return t.biasNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}grad(e,t){const s=this.clone();return s.gradNode=[Wa(e),Wa(t)],s.referenceNode=this.getBase(),Wa(s)}depth(e){const t=this.clone();return t.depthNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}offset(e){const t=this.clone();return t.offsetNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix();const s=this._flipYUniform;null!==s&&(s.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const Zu=Ya(Qu).setParameterLength(1,4).setName("texture"),Ju=(e=Ku,t=null,s=null,i=null)=>{let r;return e&&!0===e.isTextureNode?(r=Wa(e.clone()),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=Wa(t)),null!==s&&(r.levelNode=Wa(s)),null!==i&&(r.biasNode=Wa(i))):r=Zu(e,t,s,i),r},ec=(...e)=>Ju(...e).setSampler(!1);class tc extends lh{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const sc=(e,t,s)=>new tc(e,t,s);class ic extends ia{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType(e),i=this.node.getPaddedType();return e.format(t,i,s)}}class rc extends tc{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?zn(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Hn,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,s=this.elementType;if("float"===s||"int"===s||"uint"===s)for(let s=0;s<e.length;s++){t[4*s]=e[s]}else if("color"===s)for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.r,t[i+1]=r.g,t[i+2]=r.b||0}else if("mat2"===s)for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+3]=r.elements[3]}else if("mat3"===s)for(let s=0;s<e.length;s++){const i=16*s,r=e[s];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+4]=r.elements[3],t[i+5]=r.elements[4],t[i+6]=r.elements[5],t[i+8]=r.elements[6],t[i+9]=r.elements[7],t[i+10]=r.elements[8],t[i+15]=1}else if("mat4"===s)for(let s=0;s<e.length;s++){const i=16*s,r=e[s];for(let e=0;e<r.elements.length;e++)t[i+e]=r.elements[e]}else for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.x,t[i+1]=r.y,t[i+2]=r.z||0,t[i+3]=r.w||0}}setup(e){const t=this.array.length,s=this.elementType;let i=Float32Array;const r=this.paddedType,n=e.getTypeLength(r);return"i"===s.charAt(0)&&(i=Int32Array),"u"===s.charAt(0)&&(i=Uint32Array),this.value=new i(t*n),this.bufferCount=t,this.bufferType=r,this.update(),super.setup(e)}element(e){return new ic(this,Wa(e))}}const nc=(e,t)=>new rc(e,t);const ac=Ya(class extends sa{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let oc,hc;class lc extends sa{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}generateNodeType(){return this.scope===lc.DPR?"float":this.scope===lc.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=$n;return this.scope!==lc.SIZE&&this.scope!==lc.VIEWPORT&&this.scope!==lc.DPR||(e=Hn),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===lc.VIEWPORT?null!==t?hc.copy(t.viewport):(e.getViewport(hc),hc.multiplyScalar(e.getPixelRatio())):this.scope===lc.DPR?this._output.value=e.getPixelRatio():null!==t?(oc.width=t.width,oc.height=t.height):e.getDrawingBufferSize(oc)}setup(){const e=this.scope;let t=null;return t=e===lc.SIZE?uh(oc||(oc=new Dt)):e===lc.VIEWPORT?uh(hc||(hc=new ss)):e===lc.DPR?uh(1):uo(pc.div(dc)),this._output=t,t}generate(e){if(this.scope===lc.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(dc).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}lc.COORDINATE="coordinate",lc.VIEWPORT="viewport",lc.SIZE="size",lc.UV="uv",lc.DPR="dpr";const uc=Ka(lc,lc.DPR),cc=Ka(lc,lc.UV),dc=Ka(lc,lc.SIZE),pc=Ka(lc,lc.COORDINATE),mc=Ka(lc,lc.VIEWPORT),gc=mc.zw;mc.xy;let fc=null,yc=null,bc=null,_c=null,xc=null,vc=null,Tc=null,Sc=null;const wc=uh(0,"uint").setName("u_cameraIndex").setGroup(ah("cameraIndex")).toVarying("v_cameraIndex"),Mc=uh("float").setName("cameraNear").setGroup(oh).onRenderUpdate(({camera:e})=>e.near),Nc=uh("float").setName("cameraFar").setGroup(oh).onRenderUpdate(({camera:e})=>e.far),Ac=eo(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrix);null===yc?yc=nc(s).setGroup(oh).setName("cameraProjectionMatrices"):yc.array=s,t=yc.element(e.isMultiViewCamera?ac("gl_ViewID_OVR"):wc).toConst("cameraProjectionMatrix")}else null===fc&&(fc=uh(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(oh).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=fc;return t}).once()(),Ec=eo(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrixInverse);null===_c?_c=nc(s).setGroup(oh).setName("cameraProjectionMatricesInverse"):_c.array=s,t=_c.element(e.isMultiViewCamera?ac("gl_ViewID_OVR"):wc).toConst("cameraProjectionMatrixInverse")}else null===bc&&(bc=uh(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(oh).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=bc;return t}).once()(),Rc=eo(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorldInverse);null===vc?vc=nc(s).setGroup(oh).setName("cameraViewMatrices"):vc.array=s,t=vc.element(e.isMultiViewCamera?ac("gl_ViewID_OVR"):wc).toConst("cameraViewMatrix")}else null===xc&&(xc=uh(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(oh).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=xc;return t}).once()(),Cc=eo(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(let t=0,i=e.cameras.length;t<i;t++)s.push(new Ot);null===Sc?Sc=nc(s).setGroup(oh).setName("cameraPositions").onRenderUpdate(({camera:e},t)=>{const s=e.cameras,i=t.array;for(let e=0,t=s.length;e<t;e++)i[e].setFromMatrixPosition(s[e].matrixWorld)}):Sc.array=s,t=Sc.element(e.isMultiViewCamera?ac("gl_ViewID_OVR"):wc).toConst("cameraPosition")}else null===Tc&&(Tc=uh(new Ot).setName("cameraPosition").setGroup(oh).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),t=Tc;return t}).once()(),Pc=new Fi;class Bc extends sa{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=qn,this.uniformNode=new lh(null)}generateNodeType(){const e=this.scope;return e===Bc.WORLD_MATRIX?"mat4":e===Bc.POSITION||e===Bc.VIEW_POSITION||e===Bc.DIRECTION||e===Bc.SCALE?"vec3":e===Bc.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Bc.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Bc.POSITION)s.value=s.value||new Ot,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Bc.SCALE)s.value=s.value||new Ot,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Bc.DIRECTION)s.value=s.value||new Ot,t.getWorldDirection(s.value);else if(i===Bc.VIEW_POSITION){const i=e.camera;s.value=s.value||new Ot,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Bc.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),Pc.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),s.value=Pc.radius}}generate(e){const t=this.scope;return t===Bc.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Bc.POSITION||t===Bc.VIEW_POSITION||t===Bc.DIRECTION||t===Bc.SCALE?this.uniformNode.nodeType="vec3":t===Bc.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Bc.WORLD_MATRIX="worldMatrix",Bc.POSITION="position",Bc.SCALE="scale",Bc.VIEW_POSITION="viewPosition",Bc.DIRECTION="direction",Bc.RADIUS="radius";class Fc extends Bc{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Lc=Ka(Fc,Fc.WORLD_MATRIX),Dc=uh(new zt).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),Ic=eo(e=>e.context.modelViewMatrix||Oc).once()().toVar("modelViewMatrix"),Oc=Rc.mul(Lc),Uc=eo(e=>(e.context.isHighPrecisionModelViewMatrix=!0,uh("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),kc=eo(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return uh("mat3").onObjectUpdate(({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),zc=eo(e=>"fragment"!==e.shaderStage?(xt("TSL: `clipSpace` is only available in fragment stage."),_o()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),Vc=ju("position","vec3"),Gc=Vc.toVarying("positionLocal"),jc=Vc.toVarying("positionPrevious"),$c=eo(e=>Lc.mul(Gc).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Wc=eo(()=>Gc.transformDirection(Lc).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Hc=eo(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=Ec.mul(zc);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),qc=eo(e=>{let t;return t=e.camera.isOrthographicCamera?go(0,0,1):Hc.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class Xc extends sa{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return 1===t.side?"false":e.getFrontFacing()}}const Yc=ao(Ka(Xc)).mul(2).sub(1),Kc=eo(([e],{material:t})=>{const s=t.side;return 1===s?e=e.mul(-1):2===s&&(e=e.mul(Yc)),e}),Qc=ju("normal","vec3"),Zc=eo(e=>!1===e.geometry.hasAttribute("normal")?(bt('TSL: Vertex attribute "normal" not found on geometry.'),go(0,1,0)):Qc,"vec3").once()().toVar("normalLocal"),Jc=Hc.dFdx().cross(Hc.dFdy()).normalize().toVar("normalFlat"),ed=eo(e=>{let t;return t=e.isFlatShading()?Jc:ad(Zc).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),td=eo(e=>{let t=ed.transformDirection(Rc);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),sd=eo(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=ed,!0!==e.isFlatShading()&&(t=Kc(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),id=sd.transformDirection(Rc).toVar("normalWorld"),rd=eo(({subBuildFn:e,context:t})=>{let s;return s="NORMAL"===e||"VERTEX"===e?sd:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),s},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),nd=eo(([e,t=Lc])=>{const s=wo(t),i=e.div(go(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz}),ad=eo(([e],t)=>{const s=t.context.modelNormalViewMatrix;if(s)return s.transformDirection(e);const i=Dc.mul(e);return Rc.transformDirection(i)});eo(()=>(bt('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),sd)).once(["NORMAL","VERTEX"])(),eo(()=>(bt('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),id)).once(["NORMAL","VERTEX"])(),eo(()=>(bt('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),rd)).once(["NORMAL","VERTEX"])();const od=new ns,hd=uh(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),ld=uh(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),ud=uh(new ns).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const s=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return s?od.makeRotationFromEuler(s).transpose():od.identity(),od}),cd=qc.negate().reflect(sd),dd=qc.negate().refract(sd,hd),pd=cd.transformDirection(Rc).toVar("reflectVector"),md=dd.transformDirection(Rc).toVar("reflectVector"),gd=new Br;class fd extends Qu{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===B?pd:e.mapping===F?md:(_t('CubeTextureNode: Mapping "%s" not supported.',e.mapping),go(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return!0===s.isDepthTexture?e.renderer.coordinateSystem===lt?go(t.x,t.y.negate(),t.z):t:(t=ud.mul(t),e.renderer.coordinateSystem!==lt&&s.isRenderTargetTexture||(t=go(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const yd=Ya(fd).setParameterLength(1,4).setName("cubeTexture"),bd=(e=gd,t=null,s=null,i=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=Wa(e.clone()),r.referenceNode=e,null!==t&&(r.uvNode=Wa(t)),null!==s&&(r.levelNode=Wa(s)),null!==i&&(r.biasNode=Wa(i))):r=yd(e,t,s,i),r};class _d extends ia{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(e),i=this.getNodeType(e);return e.format(t,s,i)}}class xd extends sa{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=qn}element(e){return new _d(this,Wa(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return bt('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?sc(null,e,this.count):Array.isArray(this.getValueFromReference())?nc(null,e):"texture"===e?Ju(null):"cubeTexture"===e?bd(null):uh(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}generateNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;e<t.length;e++)s=s[t[e]];return s}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const vd=(e,t,s)=>new xd(e,t,s),Td=(e,t,s,i)=>new xd(e,t,i,s);class Sd extends xd{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const wd=(e,t,s=null)=>new Sd(e,t,s),Md=$u(),Nd=Hc.dFdx(),Ad=Hc.dFdy(),Ed=Md.dFdx(),Rd=Md.dFdy(),Cd=sd,Pd=Ad.cross(Cd),Bd=Cd.cross(Nd),Fd=Pd.mul(Ed.x).add(Bd.mul(Rd.x)),Ld=Pd.mul(Ed.y).add(Bd.mul(Rd.y)),Dd=Fd.dot(Fd).max(Ld.dot(Ld)),Id=Dd.equal(0).select(0,Dd.inverseSqrt()),Od=Fd.mul(Id).toVar("tangentViewFrame"),Ud=Ld.mul(Id).toVar("bitangentViewFrame"),kd=ju("tangent","vec4"),zd=kd.xyz.toVar("tangentLocal"),Vd=eo(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Ic.mul(_o(zd,0)).xyz.toVarying("v_tangentView").normalize():Od,!0!==e.isFlatShading()&&(t=Kc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),Gd=eo(([e,t],s)=>{let i=e.mul(kd.w).xyz;return"NORMAL"===s.subBuildFn&&!0!==s.isFlatShading()&&(i=i.toVarying(t)),i}).once(["NORMAL"]),jd=wo(Vd,eo(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Gd(sd.cross(Vd),"v_bitangentView").normalize():Ud,!0!==e.isFlatShading()&&(t=Kc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),sd).toVar("TBNViewMatrix"),$d=eo(()=>{let e=$o.cross(qc);return e=e.cross($o).normalize(),e=jl(e,sd,Go.mul(Bo.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),Wd=e=>go(e,Zh(Wl(ao(1).sub(Il(e,e)))));class Hd extends na{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=""}setup(e){const{normalMapType:t,scaleNode:s,unpackNormalMode:i}=this;let r=this.node.mul(2).sub(1);if(0===t?"rg"===i?r=Wd(r.xy):"ga"===i?r=Wd(r.yw):""!==i&&_t(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):""!==i&&_t(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),null!==s){let t=s;!0===e.isFlatShading()&&(t=Kc(t)),r=go(r.xy.mul(t),r.z)}let n=null;return 1===t?n=ad(r):0===t?n=jd.mul(r).normalize():(_t(`NodeMaterial: Unsupported normal map type: ${t}`),n=sd),n}}const qd=Ya(Hd).setParameterLength(1,2),Xd=eo(({textureNode:e,bumpScale:t})=>{const s=t=>e.isolate().context({getUV:e=>t(e.uvNode||$u()),forceUVContext:!0}),i=ao(s(e=>e));return uo(ao(s(e=>e.add(e.dFdx()))).sub(i),ao(s(e=>e.add(e.dFdy()))).sub(i)).mul(t)}),Yd=eo(e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,a=t.dFdy().normalize().cross(n),o=n.cross(r),h=r.dot(a).mul(Yc),l=h.sign().mul(i.x.mul(a).add(i.y.mul(o)));return h.abs().mul(s).sub(l).normalize()});class Kd extends na{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Xd({textureNode:this.textureNode,bumpScale:e});return Yd({surf_pos:Hc,surf_norm:sd,dHdxy:t})}}const Qd=Ya(Kd).setParameterLength(1,2),Zd=new Map;class Jd extends sa{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=Zd.get(e);return void 0===s&&(s=wd(e,t),Zd.set(e,s)),s}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,s=this.scope;let i=null;if(s===Jd.COLOR){const e=void 0!==t.color?this.getColor(s):go();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===Jd.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===Jd.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:ao(1);else if(s===Jd.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(s).a):e}else if(s===Jd.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===Jd.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===Jd.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===Jd.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(s)):r}else if(s===Jd.NORMAL)t.normalMap?(i=qd(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,t.normalMap.format!=le&&t.normalMap.format!=$e&&t.normalMap.format!=Me||(i.unpackNormalMode="rg")):i=t.bumpMap?Qd(this.getTexture("bump").r,this.getFloat("bumpScale")):sd;else if(s===Jd.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Jd.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Jd.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?qd(this.getTexture(s),this.getCache(s+"Scale","vec2")):sd;else if(s===Jd.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(s===Jd.SHEEN_ROUGHNESS){const e=this.getFloat(s);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,i=i.clamp(1e-4,1)}else if(s===Jd.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=So(Ip.x,Ip.y,Ip.y.negate(),Ip.x).mul(e.rg.mul(2).sub(uo(1)).normalize().mul(e.b))}else i=Ip;else if(s===Jd.IRIDESCENCE_THICKNESS){const e=vd("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=vd("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===Jd.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===Jd.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===Jd.IOR)i=this.getFloat(s);else if(s===Jd.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===Jd.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(s===Jd.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):ao(0);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}Jd.ALPHA_TEST="alphaTest",Jd.COLOR="color",Jd.OPACITY="opacity",Jd.SHININESS="shininess",Jd.SPECULAR="specular",Jd.SPECULAR_STRENGTH="specularStrength",Jd.SPECULAR_INTENSITY="specularIntensity",Jd.SPECULAR_COLOR="specularColor",Jd.REFLECTIVITY="reflectivity",Jd.ROUGHNESS="roughness",Jd.METALNESS="metalness",Jd.NORMAL="normal",Jd.CLEARCOAT="clearcoat",Jd.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Jd.CLEARCOAT_NORMAL="clearcoatNormal",Jd.EMISSIVE="emissive",Jd.ROTATION="rotation",Jd.SHEEN="sheen",Jd.SHEEN_ROUGHNESS="sheenRoughness",Jd.ANISOTROPY="anisotropy",Jd.IRIDESCENCE="iridescence",Jd.IRIDESCENCE_IOR="iridescenceIOR",Jd.IRIDESCENCE_THICKNESS="iridescenceThickness",Jd.IOR="ior",Jd.TRANSMISSION="transmission",Jd.THICKNESS="thickness",Jd.ATTENUATION_DISTANCE="attenuationDistance",Jd.ATTENUATION_COLOR="attenuationColor",Jd.LINE_SCALE="scale",Jd.LINE_DASH_SIZE="dashSize",Jd.LINE_GAP_SIZE="gapSize",Jd.LINE_WIDTH="linewidth",Jd.LINE_DASH_OFFSET="dashOffset",Jd.POINT_SIZE="size",Jd.DISPERSION="dispersion",Jd.LIGHT_MAP="light",Jd.AO="ao";const ep=Ka(Jd,Jd.ALPHA_TEST),tp=Ka(Jd,Jd.COLOR),sp=Ka(Jd,Jd.SHININESS),ip=Ka(Jd,Jd.EMISSIVE),rp=Ka(Jd,Jd.OPACITY),np=Ka(Jd,Jd.SPECULAR),ap=Ka(Jd,Jd.SPECULAR_INTENSITY),op=Ka(Jd,Jd.SPECULAR_COLOR),hp=Ka(Jd,Jd.SPECULAR_STRENGTH),lp=Ka(Jd,Jd.REFLECTIVITY),up=Ka(Jd,Jd.ROUGHNESS),cp=Ka(Jd,Jd.METALNESS),dp=Ka(Jd,Jd.NORMAL),pp=Ka(Jd,Jd.CLEARCOAT),mp=Ka(Jd,Jd.CLEARCOAT_ROUGHNESS),gp=Ka(Jd,Jd.CLEARCOAT_NORMAL),fp=Ka(Jd,Jd.ROTATION),yp=Ka(Jd,Jd.SHEEN),bp=Ka(Jd,Jd.SHEEN_ROUGHNESS),_p=Ka(Jd,Jd.ANISOTROPY),xp=Ka(Jd,Jd.IRIDESCENCE),vp=Ka(Jd,Jd.IRIDESCENCE_IOR),Tp=Ka(Jd,Jd.IRIDESCENCE_THICKNESS),Sp=Ka(Jd,Jd.TRANSMISSION),wp=Ka(Jd,Jd.THICKNESS),Mp=Ka(Jd,Jd.IOR),Np=Ka(Jd,Jd.ATTENUATION_DISTANCE),Ap=Ka(Jd,Jd.ATTENUATION_COLOR),Ep=Ka(Jd,Jd.LINE_SCALE),Rp=Ka(Jd,Jd.LINE_DASH_SIZE),Cp=Ka(Jd,Jd.LINE_GAP_SIZE);Jd.LINE_WIDTH;const Pp=Ka(Jd,Jd.LINE_DASH_OFFSET),Bp=Ka(Jd,Jd.POINT_SIZE),Fp=Ka(Jd,Jd.DISPERSION),Lp=Ka(Jd,Jd.LIGHT_MAP),Dp=Ka(Jd,Jd.AO),Ip=uh(new Dt).onReference(function(e){return e.material}).onRenderUpdate(function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))}),Op=eo(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class Up extends ia{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const s=this.storageBufferNode.structTypeNode;return s?s.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let s;const i=e.context.assign;if(s=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===i||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}const kp=Ya(Up).setParameterLength(2);class zp extends tc{static get type(){return"StorageBufferNode"}constructor(e,t=null,s=0){let i,r=null;t&&t.isStruct?(i="struct",r=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(s=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=kn(e.itemSize),s=e.count):i=t,super(e,i,s),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=Kn,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){let t;if(0===this.bufferCount){let s=e.globalCache.getData(this.value);void 0===s&&(s={node:this},e.globalCache.setData(this.value,s)),t=s.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return kp(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Xn)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=Tu(this.value),this._varying=au(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generateNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:s}=this.getAttributeData(),i=s.build(e);return e.registerTransform(i,t),i}}const Vp=(e,t=null,s=0)=>new zp(e,t,s);class Gp extends sa{static get type(){return"InstanceNode"}constructor(e,t,s=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=s,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=Wn,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){let{instanceMatrixNode:t,instanceColorNode:s}=this;null===t&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:i,isStorageColor:r}=this;if(i&&null===s){if(r)s=Vp(i,"vec3",Math.max(i.count,1)).element(Au);else{const e=new yr(i.array,3),t=i.usage===ot?wu:Su;this.bufferColor=e,s=go(t(e,"vec3",3,0))}this.instanceColorNode=s}const n=t.mul(Gc).xyz;if(Gc.assign(n),e.needsPreviousData()&&jc.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const e=nd(Zc,t);Zc.assign(e)}null!==this.instanceColorNode&&Eo("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),null!==this.previousInstanceMatrixNode&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return null===this.previousInstanceMatrixNode&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(jc).xyz}_createInstanceMatrixNode(e,t){let s;const{instanceMatrix:i}=this,{count:r}=i;if(this.isStorageMatrix)s=Vp(i,"mat4",Math.max(r,1)).element(Au);else{if(16*r*4<=t.getUniformBufferLimit())s=sc(i.array,"mat4",Math.max(r,1)).element(Au);else{const t=new Sn(i.array,16,1);!0===e&&(this.buffer=t);const r=i.usage===ot?wu:Su,n=[r(t,"vec4",16,0),r(t,"vec4",16,4),r(t,"vec4",16,8),r(t,"vec4",16,12)];s=Mo(...n)}}return s}}class jp extends Gp{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const $p=Ya(jp).setParameterLength(1);class Wp extends sa{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=Au:this.batchingIdNode=Eu);const t=eo(([e])=>{const t=oo(Hu(ec(this.batchMesh._indirectTexture),0).x).toConst(),s=oo(e).mod(t).toConst(),i=oo(e).div(t).toConst();return ec(this.batchMesh._indirectTexture,co(s,i)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(oo(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=oo(Hu(ec(i),0).x).toConst(),n=ao(s).mul(4).toInt().toConst(),a=n.mod(r).toConst(),o=n.div(r).toConst(),h=Mo(ec(i,co(a,o)),ec(i,co(a.add(1),o)),ec(i,co(a.add(2),o)),ec(i,co(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=eo(([e])=>{const t=oo(Hu(ec(l),0).x).toConst(),s=e,i=s.mod(t).toConst(),r=s.div(t).toConst();return ec(l,co(i,r)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);Eo("vec3","vBatchColor").assign(t)}const u=wo(h);Gc.assign(h.mul(Gc));const c=Zc.div(go(u[0].dot(u[0]),u[1].dot(u[1]),u[2].dot(u[2]))),d=u.mul(c).xyz;Zc.assign(d),e.hasGeometryAttribute("tangent")&&zd.mulAssign(u)}}const Hp=Ya(Wp).setParameterLength(1),qp=new WeakMap;class Xp extends sa{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=qn,this.skinIndexNode=ju("skinIndex","uvec4"),this.skinWeightNode=ju("skinWeight","vec4"),this.bindMatrixNode=vd("bindMatrix","mat4"),this.bindMatrixInverseNode=vd("bindMatrixInverse","mat4"),this.boneMatricesNode=Td("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Gc,this.toPositionNode=Gc,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,a=e.element(s.x),o=e.element(s.y),h=e.element(s.z),l=e.element(s.w),u=r.mul(t),c=fh(a.mul(i.x).mul(u),o.mul(i.y).mul(u),h.mul(i.z).mul(u),l.mul(i.w).mul(u));return n.mul(c).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=Zc,s=zd){const{skinIndexNode:i,skinWeightNode:r,bindMatrixNode:n,bindMatrixInverseNode:a}=this,o=e.element(i.x),h=e.element(i.y),l=e.element(i.z),u=e.element(i.w);let c=fh(r.x.mul(o),r.y.mul(h),r.z.mul(l),r.w.mul(u));c=a.mul(c).mul(n);return{skinNormal:c.transformDirection(t).xyz,skinTangent:c.transformDirection(s).xyz}}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=Td("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,jc)}setup(e){e.needsPreviousData()&&jc.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:t,skinTangent:s}=this.getSkinnedNormalAndTangent();Zc.assign(t),e.hasGeometryAttribute("tangent")&&zd.assign(s)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;qp.get(t)!==e.frameId&&(qp.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}class Yp extends sa{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const s={};for(let e=0,t=this.params.length-1;e<t;e++){const t=this.params[e],i=!0!==t.isNode&&t.name||this.getVarName(e),r=!0!==t.isNode&&t.type||"int";s[i]=Iu(i,r)}const i=e.addStack(),r=this.params[this.params.length-1](s);t.returnsNode=r.context({nodeLoop:r}),t.stackNode=i;const n=this.params[0];if(!0!==n.isNode&&"function"==typeof n.update){const e=eo(this.params[0].update)(s);t.updateNode=e.context({nodeLoop:e})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){e.getDataFromNode(e.fnCall.shaderNode).hasLoop=!0}}generate(e){const t=this.getProperties(e),s=this.params,i=t.stackNode;for(let i=0,r=s.length-1;i<r;i++){const r=s[i];let n,a=!1,o=null,h=null,l=null,u=null,c=null,d=null;if(r.isNode?"bool"===r.getNodeType(e)?(a=!0,u="bool",h=r.build(e,u)):(u="int",l=this.getVarName(i),o="0",h=r.build(e,u),c="<"):(u=r.type||"int",l=r.name||this.getVarName(i),o=r.start,h=r.end,c=r.condition,d=r.update,"number"==typeof o?o=e.generateConst(u,o):o&&o.isNode&&(o=o.build(e,u)),"number"==typeof h?h=e.generateConst(u,h):h&&h.isNode&&(h=h.build(e,u)),void 0!==o&&void 0===h?(o+=" - 1",h="0",c=">="):void 0!==h&&void 0===o&&(o="0",c="<"),void 0===c&&(c=Number(o)>Number(h)?">=":"<")),a)n=`while ( ${h} )`;else{const s={start:o,end:h},i=s.start,r=s.end;let a;const p=()=>c.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=l+" "+p()+" "+e.generateConst(u,d);break;case"string":a=l+" "+d;break;default:d.isNode?a=l+" "+p()+" "+d.build(e):(_t("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else d="int"===u||"uint"===u?c.includes("<")?"++":"--":p()+" 1.",a=l+" "+d;n=`for ( ${e.getVar(u,l)+" = "+i}; ${l+" "+c+" "+r}; ${a} )`}e.addFlowCode((0===i?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const r=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,s=this.params.length-1;t<s;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();e.addFlowTab()}}const Kp=(...e)=>new Yp(Xa(e,"int")).toStack(),Qp=new WeakMap,Zp=new ss,Jp=eo(({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const a=oo(Nu).mul(s).add(n),o=a.div(i),h=a.sub(o.mul(i));return ec(e,co(h,o)).depth(r).xyz.mul(t)});class em extends sa{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=uh(1),this.updateType=qn}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,n=void 0!==r?r.length:0,{texture:a,stride:o,size:h}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,n=void 0!==r?r.length:0;let a=Qp.get(e);if(void 0===a||a.count!==n){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],h=e.morphAttributes.normal||[],l=e.morphAttributes.color||[];let u=0;!0===t&&(u=1),!0===s&&(u=2),!0===i&&(u=3);let c=e.attributes.position.count*u,d=1;const p=4096;c>p&&(d=Math.ceil(c/p),c=p);const m=new Float32Array(c*d*4*n),g=new rs(m,c,d,n);g.type=Y,g.needsUpdate=!0;const f=4*u;for(let b=0;b<n;b++){const _=o[b],x=h[b],v=l[b],T=c*d*4*b;for(let S=0;S<_.count;S++){const w=S*f;!0===t&&(Zp.fromBufferAttribute(_,S),m[T+w+0]=Zp.x,m[T+w+1]=Zp.y,m[T+w+2]=Zp.z,m[T+w+3]=0),!0===s&&(Zp.fromBufferAttribute(x,S),m[T+w+4]=Zp.x,m[T+w+5]=Zp.y,m[T+w+6]=Zp.z,m[T+w+7]=0),!0===i&&(Zp.fromBufferAttribute(v,S),m[T+w+8]=Zp.x,m[T+w+9]=Zp.y,m[T+w+10]=Zp.z,m[T+w+11]=4===v.itemSize?Zp.w:1)}}function y(){g.dispose(),Qp.delete(e),e.removeEventListener("dispose",y)}a={count:n,texture:g,stride:u,size:new Dt(c,d)},Qp.set(e,a),e.addEventListener("dispose",y)}return a}(t);!0===s&&Gc.mulAssign(this.morphBaseInfluence),!0===i&&Zc.mulAssign(this.morphBaseInfluence);const l=oo(h.width);Kp(n,({i:e})=>{const t=ao(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(ec(this.mesh.morphTexture,co(oo(e).add(1),oo(Au))).r):t.assign(vd("morphTargetInfluences","float").element(e).toVar()),io(t.notEqual(0),()=>{!0===s&&Gc.addAssign(Jp({bufferMap:a,influence:t,stride:o,width:l,depth:e,offset:oo(0)})),!0===i&&Zc.addAssign(Jp({bufferMap:a,influence:t,stride:o,width:l,depth:e,offset:oo(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const tm=Ya(em).setParameterLength(1);class sm extends sa{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class im extends sm{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class rm extends Zl{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s={directDiffuse:go().toVar("directDiffuse"),directSpecular:go().toVar("directSpecular"),indirectDiffuse:go().toVar("indirectDiffuse"),indirectSpecular:go().toVar("indirectSpecular")};return{radiance:go().toVar("radiance"),irradiance:go().toVar("irradiance"),iblIrradiance:go().toVar("iblIrradiance"),ambientOcclusion:ao(1).toVar("ambientOcclusion"),reflectedLight:s,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const nm=Ya(rm);class am extends sm{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const om=new Dt;class hm extends Qu{static get type(){return"ViewportTextureNode"}constructor(e=cc,t=null,s=null){let i=null;null===s?(i=new Pr,i.minFilter=G,s=i):i=s,super(s,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=Hn,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,s;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,s=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,s=this._cacheTextures),null===e)return t;if(!1===s.has(e)){const i=t.clone();s.set(e,i)}return s.get(e)}updateReference(e){const t=e.renderer,s=t.getRenderTarget(),i=t.getCanvasTarget(),r=s||i;return this.value=this.getTextureForReference(r),this.value}updateBefore(e){const t=e.renderer,s=t.getRenderTarget(),i=t.getCanvasTarget(),r=s||i;null===r?t.getDrawingBufferSize(om):r.getDrawingBufferSize?r.getDrawingBufferSize(om):om.set(r.width,r.height);const n=this.getTextureForReference(r);n.image.width===om.width&&n.image.height===om.height||(n.image.width=om.width,n.image.height=om.height,n.needsUpdate=!0);const a=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const lm=Ya(hm,null,null,{generateMipmaps:!0}).setParameterLength(0,3),um=lm(),cm=(e=cc,t=null)=>um.sample(e,t);let dm=null;class pm extends hm{static get type(){return"ViewportDepthTextureNode"}constructor(e=cc,t=null,s=null){null===s&&(null===dm&&(dm=new Fr),s=dm),super(e,t,s)}}const mm=Ya(pm).setParameterLength(0,3);class gm extends sa{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===gm.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===gm.DEPTH_BASE)null!==s&&(i=xm().assign(s));else if(t===gm.DEPTH)i=e.isPerspectiveCamera?ym(Hc.z,Mc,Nc):fm(Hc.z,Mc,Nc);else if(t===gm.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=bm(s,Mc,Nc);i=fm(e,Mc,Nc)}else i=s;else i=fm(Hc.z,Mc,Nc);return i}}gm.DEPTH_BASE="depthBase",gm.DEPTH="depth",gm.LINEAR_DEPTH="linearDepth";const fm=(e,t,s)=>e.add(t).div(t.sub(s)),ym=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),bm=eo(([e,t,s],i)=>!0===i.renderer.reversedDepthBuffer?t.mul(s).div(t.sub(s).mul(e).sub(t)):t.mul(s).div(s.sub(t).mul(e).sub(s))),_m=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Qh(e.negate().div(t)),r=Qh(s.div(t));return i.div(r)},xm=Ya(gm,gm.DEPTH_BASE),vm=Ka(gm,gm.DEPTH);mm(),vm.assign=e=>xm(e);class Tm extends sa{static get type(){return"ClippingNode"}constructor(e=Tm.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:s,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===Tm.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===Tm.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return eo(()=>{const s=ao().toVar("distanceToPlane"),i=ao().toVar("distanceToGradient"),r=ao(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=nc(t).setGroup(oh);Kp(n,({i:t})=>{const n=e.element(t);s.assign(Hc.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(ql(i.negate(),i,s))})}const a=e.length;if(a>0){const t=nc(e).setGroup(oh),n=ao(1).toVar("intersectionClipOpacity");Kp(a,({i:e})=>{const r=t.element(e);s.assign(Hc.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(ql(i.negate(),i,s).oneMinus())}),r.mulAssign(n.oneMinus())}Ro.a.mulAssign(r),Ro.a.equal(0).discard()})()}setupDefault(e,t){return eo(()=>{const s=t.length;if(!1===this.hardwareClipping&&s>0){const e=nc(t).setGroup(oh);Kp(s,({i:t})=>{const s=e.element(t);Hc.dot(s.xyz).greaterThan(s.w).discard()})}const i=e.length;if(i>0){const t=nc(e).setGroup(oh),s=lo(!0).toVar("clipped");Kp(i,({i:e})=>{const i=t.element(e);s.assign(Hc.dot(i.xyz).greaterThan(i.w).and(s))}),s.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),eo(()=>{const i=nc(e).setGroup(oh),r=ac(t.getClipDistance());Kp(s,({i:e})=>{const t=i.element(e),s=Hc.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)})})()}}Tm.ALPHA_TO_COVERAGE="alphaToCoverage",Tm.DEFAULT="default",Tm.HARDWARE="hardware";const Sm=eo(([e])=>il(bh(1e4,rl(bh(17,e.x).add(bh(.1,e.y)))).mul(fh(.1,fl(rl(bh(13,e.y).add(e.x))))))),wm=eo(([e])=>Sm(uo(Sm(e.xy),e.z))),Mm=eo(([e])=>{const t=Pl(bl(vl(e.xyz)),bl(Tl(e.xyz))),s=ao(1).div(ao(.05).mul(t)).toVar("pixScale"),i=uo(Yh(el(Qh(s))),Yh(tl(Qh(s)))),r=uo(wm(el(i.x.mul(e.xyz))),wm(el(i.y.mul(e.xyz)))),n=il(Qh(s)),a=fh(bh(n.oneMinus(),r.x),bh(n,r.y)),o=Cl(n,n.oneMinus()),h=go(a.mul(a).div(bh(2,o).mul(yh(1,o))),a.sub(bh(.5,o)).div(yh(1,o)),yh(1,yh(1,a).mul(yh(1,a)).div(bh(2,o).mul(yh(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(h.x,h.y),h.z);return $l(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Nm extends Gu{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let s;return s=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new ss(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const Am=eo(([e])=>_o(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"});class Em extends Hi{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const s=this[t];s&&!0===s.isNode&&e.push({property:t,childNode:s})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:s}of this._getNodeChildren())e.push(Ln(t.slice(0,-4)),s.getCacheKey());return this.type+Dn(e)}build(e){this.setup(e)}setupObserver(e){return new Cn(e)}setup(e){e.context.setupNormal=()=>ru(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();e.addStack();const i=this.setupVertex(e),r=ru(this.vertexNode||i,"VERTEX");let n;e.context.clipSpace=r,e.stack.outputNode=r,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==s?!0===s.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const r=_o(i,Ro.a).max(0);n=this.setupOutput(e,r),Yo.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==s){const e=t.getMRT(),s=this.mrtNode;null!==e?(o&&Yo.assign(n),n=e,null!==s&&(n=e.merge(s))):null!==s&&(n=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=_o(t)),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:s}=e.clippingContext;let i=null;if(t.length>0||s.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?i=new Tm(Tm.ALPHA_TO_COVERAGE):e.stack.addToStack(new Tm)}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new Tm(Tm.HARDWARE)),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=s.isPerspectiveCamera?_m(Hc.z,Mc,Nc):fm(Hc.z,Mc,Nc))}null!==i&&vm.assign(i).toStack()}setupPositionView(){return Ic.mul(Gc).xyz}setupModelViewProjection(){return Ac.mul(Hc)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),Op}setupPosition(e){const{object:t,geometry:s}=e;var i;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&tm(t).toStack(),!0===t.isSkinnedMesh&&(i=t,new Xp(i)).toStack(),this.displacementMap){const e=wd("displacementMap","texture"),t=wd("displacementScale","float"),s=wd("displacementBias","float");Gc.addAssign(Zc.normalize().mul(e.x.mul(t).add(s)))}return t.isBatchedMesh&&Hp(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&$p(t).toStack(),null!==this.positionNode&&Gc.assign(ru(this.positionNode,"POSITION","vec3")),Gc}setupDiffuseColor(e){const{object:t,geometry:s}=e;null!==this.maskNode&&lo(this.maskNode).not().discard();let i=this.colorNode?_o(this.colorNode):tp;if(!0===this.vertexColors&&s.hasAttribute("color")&&(i=i.mul(((e=0)=>new Nm(e))())),t.instanceColor){i=Eo("vec3","vInstanceColor").mul(i)}if(t.isBatchedMesh&&t._colorsTexture){i=Eo("vec3","vBatchColor").mul(i)}Ro.assign(i);const r=this.opacityNode?ao(this.opacityNode):rp;Ro.a.assign(Ro.a.mul(r));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?ao(this.alphaTestNode):ep,!0===this.alphaToCoverage?(Ro.a=ql(n,n.add(Nl(Ro.a)),Ro.a),Ro.a.lessThanEqual(0).discard()):Ro.a.lessThanEqual(n).discard()),!0===this.alphaHash&&Ro.a.lessThan(Mm(Gc)).discard(),e.isOpaque()&&Ro.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?go(0):Ro.rgb}setupNormal(){return this.normalNode?go(this.normalNode):dp}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?wd("envMap","cubeTexture"):wd("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new am(Lp)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);i&&i.isLightingNode&&t.push(i);let r=this.aoNode;null===r&&e.material.aoMap&&(r=Dp),e.context.getAO&&(r=e.context.getAO(r,e)),r&&t.push(new im(r));let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:r}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=nm(n,t,s,i)}else null!==s&&(a=go(null!==i?jl(a,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Po.assign(go(r||ip)),a=a.add(Po)),a}setupFog(e,t){const s=e.fogNode;return s&&(Yo.assign(t),t=_o(s.toVar())),t}setupPremultipliedAlpha(e,t){return Am(t)}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),!0===this.premultipliedAlpha&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const t in e){const s=e[t];void 0===this[t]&&(this[t]=s,s&&s.clone&&(this[t]=s.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const s=Hi.prototype.toJSON.call(this,e);s.inputNodes={};for(const{property:t,childNode:i}of this._getNodeChildren())s.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(t){const t=i(e.textures),r=i(e.images),n=i(e.nodes);t.length>0&&(s.textures=t),r.length>0&&(s.images=r),n.length>0&&(s.nodes=n)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const Rm=new Rr;class Cm extends Em{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Rm),this.setValues(e)}}const Pm=new qr;class Bm extends Em{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Pm),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?ao(this.offsetNode):Pp,t=this.dashScaleNode?ao(this.dashScaleNode):Ep,s=this.dashSizeNode?ao(this.dashSizeNode):Rp,i=this.gapSizeNode?ao(this.gapSizeNode):Cp;Ko.assign(s),Qo.assign(i);const r=au(ju("lineDistance").mul(t));(e?r.add(e):r).mod(Ko.add(Qo)).greaterThan(Ko).discard()}}const Fm=new $r;class Lm extends Em{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Fm),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?ao(this.opacityNode):rp;Ro.assign(cu(_o(Wa(sd).mul(.5).add(.5),e),qe))}}const Dm=eo(([e=Wc])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return uo(t,s)});class Im extends is{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Br(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r=new Dr(5,5,5),n=Dm(Wc),a=new Em;a.colorNode=Ju(t,n,0),a.side=1,a.blending=0;const o=new mr(r,a),h=new Gs;h.add(o),t.minFilter===G&&(t.minFilter=z);const l=new vn(1,10,this),u=e.getMRT();return e.setMRT(null),l.update(e,h),e.setMRT(u),t.minFilter=s,t.generateMipmaps=i,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,s=!0,i=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(r)}}const Om=new WeakMap;class Um extends na{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=bd(null);const t=new Br;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Hn}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:s[i.property];if(e&&e.isTexture){const s=e.mapping;if(303===s||304===s){if(Om.has(e)){const t=Om.get(e);zm(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new Im(s.height);i.fromEquirectangularTexture(t,e),zm(i.texture,e.mapping),this._cubeTexture=i.texture,Om.set(e,i.texture),e.addEventListener("dispose",km)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function km(e){const t=e.target;t.removeEventListener("dispose",km);const s=Om.get(t);void 0!==s&&(Om.delete(t),s.dispose())}function zm(e,t){303===t?e.mapping=B:304===t&&(e.mapping=F)}const Vm=Ya(Um).setParameterLength(1);class Gm extends sm{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Vm(this.envNode)}}class jm extends sm{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=ao(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class $m{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Wm extends $m{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(_o(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(_o(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Ro.rgb)}finish(e){const{material:t,context:s}=e,i=s.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case 0:i.rgb.assign(jl(i.rgb,i.rgb.mul(r.rgb),hp.mul(lp)));break;case 1:i.rgb.assign(jl(i.rgb,r.rgb,hp.mul(lp)));break;case 2:i.rgb.addAssign(r.rgb.mul(hp.mul(lp)));break;default:bt("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Hm=new sr;class qm extends Em{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Hm),this.setValues(e)}setupNormal(){return Kc(ed)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Gm(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new jm(Lp)),t}setupOutgoingLight(){return Ro.rgb}setupLightingModel(){return new Wm}}const Xm=eo(({f0:e,f90:t,dotVH:s})=>{const i=s.mul(-5.55473).sub(6.98316).mul(s).exp2();return e.mul(i.oneMinus()).add(t.mul(i))}),Ym=eo(e=>e.diffuseColor.mul(1/Math.PI)),Km=eo(({dotNH:e})=>Xo.mul(ao(.5)).add(1).mul(ao(1/Math.PI)).mul(e.pow(Xo))),Qm=eo(({lightDirection:e})=>{const t=e.add(qc).normalize(),s=sd.dot(t).clamp(),i=qc.dot(t).clamp(),r=Xm({f0:Wo,f90:1,dotVH:i}),n=ao(.25),a=Km({dotNH:s});return r.mul(n).mul(a)});class Zm extends Wm{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=sd.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(Ym({diffuseColor:Ro.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(Qm({lightDirection:e})).mul(hp))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(Ym({diffuseColor:Ro}))),i.indirectDiffuse.mulAssign(t)}}const Jm=new Wr;class eg extends Em{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Jm),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Gm(t):null}setupLightingModel(){return new Zm(!1)}}const tg=new Gr;class sg extends Em{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(tg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Gm(t):null}setupLightingModel(){return new Zm}setupVariants(){const e=(this.shininessNode?ao(this.shininessNode):sp).max(1e-4);Xo.assign(e);const t=this.specularNode||np;Wo.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const ig=eo(e=>{if(!1===e.geometry.hasAttribute("normal"))return ao(0);const t=ed.dFdx().abs().max(ed.dFdy().abs());return t.x.max(t.y).max(t.z)}),rg=eo(e=>{const{roughness:t}=e,s=ig();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i}),ng=eo(({alpha:e,dotNL:t,dotNV:s})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(s.pow2())).sqrt()),n=s.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return _h(.5,r.add(n).max(Gh))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),ag=eo(({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:a,dotNL:o})=>{const h=o.mul(go(e.mul(s),t.mul(i),a).length()),l=a.mul(go(e.mul(r),t.mul(n),o).length());return _h(.5,h.add(l).max(Gh))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),og=eo(({alpha:e,dotNH:t})=>{const s=e.pow2(),i=t.pow2().mul(s.oneMinus()).oneMinus();return s.div(i.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),hg=ao(1/Math.PI),lg=eo(({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),a=go(t.mul(i),e.mul(r),n.mul(s)),o=a.dot(a),h=n.div(o);return hg.mul(n.mul(h.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),ug=eo(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,normalView:n=sd,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const h=i.pow2(),l=e.add(qc).normalize(),u=n.dot(e).clamp(),c=n.dot(qc).clamp(),d=n.dot(l).clamp(),p=qc.dot(l).clamp();let m,g,f=Xm({f0:t,f90:s,dotVH:p});if(ja(a)&&(f=Uo.mix(f,r)),ja(o)){const t=jo.dot(e),s=jo.dot(qc),i=jo.dot(l),r=$o.dot(e),n=$o.dot(qc),a=$o.dot(l);m=ag({alphaT:Vo,alphaB:h,dotTV:s,dotBV:n,dotTL:t,dotBL:r,dotNV:c,dotNL:u}),g=lg({alphaT:Vo,alphaB:h,dotNH:d,dotTH:i,dotBH:a})}else m=ng({alpha:h,dotNL:u,dotNV:c}),g=og({alpha:h,dotNH:d});return f.mul(m).mul(g)}),cg=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let dg=null;const pg=eo(({roughness:e,dotNV:t})=>{null===dg&&(dg=new fr(cg,16,16,le,K),dg.name="DFG_LUT",dg.minFilter=z,dg.magFilter=z,dg.wrapS=D,dg.wrapT=D,dg.generateMipmaps=!1,dg.needsUpdate=!0);const s=uo(e,t);return Ju(dg,s).rg}),mg=eo(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:a})=>{const o=ug({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:a}),h=sd.dot(e).clamp(),l=sd.dot(qc).clamp(),u=pg({roughness:i,dotNV:l}),c=pg({roughness:i,dotNV:h}),d=t.mul(u.x).add(s.mul(u.y)),p=t.mul(c.x).add(s.mul(c.y)),m=u.x.add(u.y),g=c.x.add(c.y),f=ao(1).sub(m),y=ao(1).sub(g),b=t.add(t.oneMinus().mul(.047619)),_=d.mul(p).mul(b).div(ao(1).sub(f.mul(y).mul(b).mul(b)).add(Gh)),x=f.mul(y),v=_.mul(x);return o.add(v)}),gg=eo(e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=pg({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))}),fg=eo(({f:e,f90:t,dotVH:s})=>{const i=s.oneMinus().saturate(),r=i.mul(i),n=i.mul(r,r).clamp(0,.9999);return e.sub(go(t).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),yg=eo(({roughness:e,dotNH:t})=>{const s=e.pow2(),i=ao(1).div(s),r=t.pow2().oneMinus().max(.0078125);return ao(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),bg=eo(({dotNV:e,dotNL:t})=>ao(1).div(ao(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),_g=eo(({lightDirection:e})=>{const t=e.add(qc).normalize(),s=sd.dot(e).clamp(),i=sd.dot(qc).clamp(),r=sd.dot(t).clamp(),n=yg({roughness:Oo,dotNH:r}),a=bg({dotNV:i,dotNL:s});return Io.mul(n).mul(a)}),xg=eo(({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=uo(s,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),vg=eo(({f:e})=>{const t=e.length();return Pl(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Tg=eo(({v1:e,v2:t})=>{const s=e.dot(t),i=s.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),n=i.add(4.1616724).mul(i).add(3.417594).toVar(),a=r.div(n),o=s.greaterThan(0).select(a,Pl(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),Sg=eo(({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:a,p3:o})=>{const h=n.sub(r).toVar(),l=o.sub(r).toVar(),u=h.cross(l),c=go().toVar();return io(u.dot(s.sub(r)).greaterThanEqual(0),()=>{const h=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(h).negate(),u=i.mul(wo(h,l,e).transpose()).toVar(),d=u.mul(r.sub(s)).normalize().toVar(),p=u.mul(n.sub(s)).normalize().toVar(),m=u.mul(a.sub(s)).normalize().toVar(),g=u.mul(o.sub(s)).normalize().toVar(),f=go(0).toVar();f.addAssign(Tg({v1:d,v2:p})),f.addAssign(Tg({v1:p,v2:m})),f.addAssign(Tg({v1:m,v2:g})),f.addAssign(Tg({v1:g,v2:d})),c.assign(go(vg({f:f})))}),c}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),wg=1/6,Mg=e=>bh(wg,bh(e,bh(e,e.negate().add(3)).sub(3)).add(1)),Ng=e=>bh(wg,bh(e,bh(e,bh(3,e).sub(6))).add(4)),Ag=e=>bh(wg,bh(e,bh(e,bh(-3,e).add(3)).add(3)).add(1)),Eg=e=>bh(wg,Ul(e,3)),Rg=e=>Mg(e).add(Ng(e)),Cg=e=>Ag(e).add(Eg(e)),Pg=e=>fh(-1,Ng(e).div(Mg(e).add(Ng(e)))),Bg=e=>fh(1,Eg(e).div(Ag(e).add(Eg(e)))),Fg=(e,t,s)=>{const i=e.uvNode,r=bh(i,t.zw).add(.5),n=el(r),a=il(r),o=Rg(a.x),h=Cg(a.x),l=Pg(a.x),u=Bg(a.x),c=Pg(a.y),d=Bg(a.y),p=uo(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),m=uo(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),g=uo(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),f=uo(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),y=Rg(a.y).mul(fh(o.mul(e.sample(p).level(s)),h.mul(e.sample(m).level(s)))),b=Cg(a.y).mul(fh(o.mul(e.sample(g).level(s)),h.mul(e.sample(f).level(s))));return y.add(b)},Lg=eo(([e,t])=>{const s=uo(e.size(oo(t))),i=uo(e.size(oo(t.add(1)))),r=_h(1,s),n=_h(1,i),a=Fg(e,_o(r,s),el(t)),o=Fg(e,_o(n,i),tl(t));return il(t).mix(a,o)}),Dg=eo(([e,t,s,i,r])=>{const n=go(Hl(t.negate(),sl(e),_h(1,i))),a=go(bl(r[0].xyz),bl(r[1].xyz),bl(r[2].xyz));return sl(n).mul(s.mul(a))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),Ig=eo(([e,t])=>e.mul($l(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Og=lm(),Ug=cm(),kg=eo(([e,t,s],{material:i})=>{const r=(1===i.side?Og:Ug).sample(e),n=Qh(dc.x).mul(Ig(t,s));return Lg(r,n)}),zg=eo(([e,t,s])=>(io(s.notEqual(0),()=>{const i=Kh(t).negate().div(s);return Xh(i.negate().mul(e))}),go(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Vg=eo(([e,t,s,i,r,n,a,o,h,l,u,c,d,p,m])=>{let g,f;if(m){g=_o().toVar(),f=go().toVar();const r=u.sub(1).mul(m.mul(.025)),n=go(u.sub(r),u,u.add(r));Kp({start:0,end:3},({i:r})=>{const u=n.element(r),m=Dg(e,t,c,u,o),y=a.add(m),b=l.mul(h.mul(_o(y,1))),_=uo(b.xy.div(b.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(uo(_.x,_.y.oneMinus()));const x=kg(_,s,u);g.element(r).assign(x.element(r)),g.a.addAssign(x.a),f.element(r).assign(i.element(r).mul(zg(bl(m),d,p).element(r)))}),g.a.divAssign(3)}else{const r=Dg(e,t,c,u,o),n=a.add(r),m=l.mul(h.mul(_o(n,1))),y=uo(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(uo(y.x,y.y.oneMinus())),g=kg(y,s,u),f=i.mul(zg(bl(r),d,p))}const y=f.rgb.mul(g.rgb),b=e.dot(t).clamp(),_=go(gg({dotNV:b,specularColor:r,specularF90:n,roughness:s})),x=f.r.add(f.g,f.b).div(3);return _o(_.oneMinus().mul(y),g.a.oneMinus().mul(x).oneMinus())}),Gg=wo(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),jg=(e,t)=>e.sub(t).div(e.add(t)).pow2(),$g=eo(({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=jl(e,t,ql(0,.03,i)),a=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();io(a.lessThan(0),()=>go(1));const o=a.sqrt(),h=jg(n,e),l=Xm({f0:h,f90:1,dotVH:s}),u=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=ao(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return go(1).add(t).div(go(1).sub(t))})(r.clamp(0,.9999)),m=jg(p,n.toVec3()),g=Xm({f0:m,f90:1,dotVH:o}),f=go(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(i,o,2),b=go(d).add(f),_=l.mul(g).clamp(1e-5,.9999),x=_.sqrt(),v=u.pow2().mul(g).div(go(1).sub(_)),T=l.add(v).toVar(),S=v.sub(u).toVar();return Kp({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{S.mulAssign(x);const t=((e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=go(54856e-17,44201e-17,52481e-17),r=go(1681e3,1795300,2208400),n=go(43278e5,93046e5,66121e5),a=ao(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let o=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());return o=go(o.x.add(a),o.y,o.z).div(1.0685e-7),Gg.mul(o)})(ao(e).mul(y),ao(e).mul(b)).mul(2);T.addAssign(S.mul(t))}),T.max(go(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),Wg=eo(({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.mul(s),n=s.add(.1).reciprocal(),a=ao(-1.9362).add(s.mul(1.0678)).add(r.mul(.4573)).sub(n.mul(.8469)),o=ao(-.6014).add(s.mul(.5538)).sub(r.mul(.467)).sub(n.mul(.1255));return a.mul(i).add(o).exp().saturate()}),Hg=go(.04),qg=ao(1);class Xg extends $m{constructor(e=!1,t=!1,s=!1,i=!1,r=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=r,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=go().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=go().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=go().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=go().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=go().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=sd.dot(qc).clamp(),t=$g({outsideIOR:ao(1),eta2:ko,cosTheta1:e,thinFilmThickness:zo,baseF0:Wo}),s=$g({outsideIOR:ao(1),eta2:ko,cosTheta1:e,thinFilmThickness:zo,baseF0:Ro.rgb});this.iridescenceFresnel=jl(t,s,Fo),this.iridescenceF0Dielectric=fg({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=fg({f:s,f90:1,dotVH:e}),this.iridescenceF0=jl(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Fo)}if(!0===this.transmission){const t=$c,s=Cc.sub($c).normalize(),i=id,r=e.context;r.backdrop=Vg(i,s,Bo,Co,Ho,qo,t,Lc,Rc,Ac,Zo,eh,sh,th,this.dispersion?ih:null),r.backdropAlpha=Jo,Ro.a.mulAssign(jl(1,r.backdrop.a,Jo))}super.start(e)}computeMultiscattering(e,t,s,i,r=null){const n=sd.dot(qc).clamp(),a=pg({roughness:Bo,dotNV:n}),o=r?Uo.mix(i,r):i,h=o.mul(a.x).add(s.mul(a.y)),l=a.x.add(a.y).oneMinus(),u=o.add(o.oneMinus().mul(.047619)),c=h.mul(u).div(l.mul(u).oneMinus());e.addAssign(h),t.addAssign(c.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=sd.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(i.mul(_g({lightDirection:e})));const t=Wg({normal:sd,viewDir:qc,roughness:Oo}),s=Wg({normal:sd,viewDir:e,roughness:Oo}),r=Io.r.max(Io.g).max(Io.b).mul(t.max(s)).oneMinus();i.mulAssign(r)}if(!0===this.clearcoat){const s=rd.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(ug({lightDirection:e,f0:Hg,f90:qg,roughness:Do,normalView:rd})))}s.directDiffuse.addAssign(i.mul(Ym({diffuseColor:Co}))),s.directSpecular.addAssign(i.mul(mg({lightDirection:e,f0:Ho,f90:1,roughness:Bo,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:r,ltc_1:n,ltc_2:a}){const o=t.add(s).sub(i),h=t.sub(s).sub(i),l=t.sub(s).add(i),u=t.add(s).add(i),c=sd,d=qc,p=Hc.toVar(),m=xg({N:c,V:d,roughness:Bo}),g=n.sample(m).toVar(),f=a.sample(m).toVar(),y=wo(go(g.x,0,g.y),go(0,1,0),go(g.z,0,g.w)).toVar(),b=Ho.mul(f.x).add(qo.sub(Ho).mul(f.y)).toVar();if(r.directSpecular.addAssign(e.mul(b).mul(Sg({N:c,V:d,P:p,mInv:y,p0:o,p1:h,p2:l,p3:u}))),r.directDiffuse.addAssign(e.mul(Co).mul(Sg({N:c,V:d,P:p,mInv:wo(1,0,0,0,1,0,0,0,1),p0:o,p1:h,p2:l,p3:u}))),!0===this.clearcoat){const t=rd,s=xg({N:t,V:d,roughness:Do}),i=n.sample(s),r=a.sample(s),c=wo(go(i.x,0,i.y),go(0,1,0),go(i.z,0,i.w)),m=Hg.mul(r.x).add(qg.sub(Hg).mul(r.y));this.clearcoatSpecularDirect.addAssign(e.mul(m).mul(Sg({N:t,V:d,P:p,mInv:c,p0:o,p1:h,p2:l,p3:u})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:s}=e.context,i=t.mul(Ym({diffuseColor:Co})).toVar();if(!0===this.sheen){const e=Wg({normal:sd,viewDir:qc,roughness:Oo}),t=Io.r.max(Io.g).max(Io.b).mul(e).oneMinus();i.mulAssign(t)}s.indirectDiffuse.addAssign(i)}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(s.mul(Io,Wg({normal:sd,viewDir:qc,roughness:Oo}))),!0===this.clearcoat){const e=rd.dot(qc).clamp(),t=gg({dotNV:e,specularColor:Hg,specularF90:qg,roughness:Do});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=go().toVar("singleScatteringDielectric"),n=go().toVar("multiScatteringDielectric"),a=go().toVar("singleScatteringMetallic"),o=go().toVar("multiScatteringMetallic");this.computeMultiscattering(r,n,qo,Wo,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,qo,Ro.rgb,this.iridescenceF0Metallic);const h=jl(r,a,Fo),l=jl(n,o,Fo),u=r.add(n),c=Co.mul(u.oneMinus()),d=s.mul(1/Math.PI),p=t.mul(h).add(l.mul(d)).toVar(),m=c.mul(d).toVar();if(!0===this.sheen){const e=Wg({normal:sd,viewDir:qc,roughness:Oo}),t=Io.r.max(Io.g).max(Io.b).mul(e).oneMinus();p.mulAssign(t),m.mulAssign(t)}i.indirectSpecular.addAssign(p),i.indirectDiffuse.addAssign(m)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:s}=e.context,i=sd.dot(qc).clamp().add(t),r=Bo.mul(-16).oneMinus().negate().exp2(),n=t.sub(i.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),s.indirectDiffuse.mulAssign(t),s.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=rd.dot(qc).clamp(),s=Xm({dotVH:e,f0:Hg,f90:qg}),i=t.mul(Lo.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Lo));t.assign(i)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const Yg=ao(1),Kg=ao(-2),Qg=ao(.8),Zg=ao(-1),Jg=ao(.4),ef=ao(2),tf=ao(.305),sf=ao(3),rf=ao(.21),nf=ao(4),af=ao(4),of=ao(16),hf=eo(([e])=>{const t=go(fl(e)).toVar(),s=ao(-1).toVar();return io(t.x.greaterThan(t.z),()=>{io(t.x.greaterThan(t.y),()=>{s.assign(Ql(e.x.greaterThan(0),0,3))}).Else(()=>{s.assign(Ql(e.y.greaterThan(0),1,4))})}).Else(()=>{io(t.z.greaterThan(t.y),()=>{s.assign(Ql(e.z.greaterThan(0),2,5))}).Else(()=>{s.assign(Ql(e.y.greaterThan(0),1,4))})}),s}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),lf=eo(([e,t])=>{const s=uo().toVar();return io(t.equal(0),()=>{s.assign(uo(e.z,e.y).div(fl(e.x)))}).ElseIf(t.equal(1),()=>{s.assign(uo(e.x.negate(),e.z.negate()).div(fl(e.y)))}).ElseIf(t.equal(2),()=>{s.assign(uo(e.x.negate(),e.y).div(fl(e.z)))}).ElseIf(t.equal(3),()=>{s.assign(uo(e.z.negate(),e.y).div(fl(e.x)))}).ElseIf(t.equal(4),()=>{s.assign(uo(e.x.negate(),e.z).div(fl(e.y)))}).Else(()=>{s.assign(uo(e.x,e.y).div(fl(e.z)))}),bh(.5,s.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),uf=eo(([e])=>{const t=ao(0).toVar();return io(e.greaterThanEqual(Qg),()=>{t.assign(Yg.sub(e).mul(Zg.sub(Kg)).div(Yg.sub(Qg)).add(Kg))}).ElseIf(e.greaterThanEqual(Jg),()=>{t.assign(Qg.sub(e).mul(ef.sub(Zg)).div(Qg.sub(Jg)).add(Zg))}).ElseIf(e.greaterThanEqual(tf),()=>{t.assign(Jg.sub(e).mul(sf.sub(ef)).div(Jg.sub(tf)).add(ef))}).ElseIf(e.greaterThanEqual(rf),()=>{t.assign(tf.sub(e).mul(nf.sub(sf)).div(tf.sub(rf)).add(sf))}).Else(()=>{t.assign(ao(-2).mul(Qh(bh(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),cf=eo(([e,t])=>{const s=e.toVar();s.assign(bh(2,s).sub(1));const i=go(s,1).toVar();return io(t.equal(0),()=>{i.assign(i.zyx)}).ElseIf(t.equal(1),()=>{i.assign(i.xzy),i.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{i.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{i.assign(i.zyx),i.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{i.assign(i.xzy),i.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{i.z.mulAssign(-1)}),i}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),df=eo(([e,t,s,i,r,n])=>{const a=ao(s),o=go(t),h=$l(uf(a),Kg,n),l=il(h),u=el(h),c=go(pf(e,o,u,i,r,n)).toVar();return io(l.notEqual(0),()=>{const t=go(pf(e,o,u.add(1),i,r,n)).toVar();c.assign(jl(c,t,l))}),c}),pf=eo(([e,t,s,i,r,n])=>{const a=ao(s).toVar(),o=go(t),h=ao(hf(o)).toVar(),l=ao(Pl(af.sub(a),0)).toVar();a.assign(Pl(a,af));const u=ao(Yh(a)).toVar(),c=uo(lf(o,h).mul(u.sub(2)).add(1)).toVar();return io(h.greaterThan(2),()=>{c.y.addAssign(u),h.subAssign(3)}),c.x.addAssign(h.mul(u)),c.x.addAssign(l.mul(bh(3,of))),c.y.addAssign(bh(4,Yh(n).sub(u))),c.x.mulAssign(i),c.y.mulAssign(r),e.sample(c).grad(uo(),uo())}),mf=eo(({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const h=al(i),l=s.mul(h).add(r.cross(s).mul(rl(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return pf(e,l,t,n,a,o)}),gf=eo(({n:e,latitudinal:t,poleAxis:s,outputDirection:i,weights:r,samples:n,dTheta:a,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})=>{const d=go(Ql(t,s,Ol(s,i))).toVar();io(d.equal(go(0)),()=>{d.assign(go(i.z,0,i.x.negate()))}),d.assign(sl(d));const p=go().toVar();return p.addAssign(r.element(0).mul(mf({theta:0,axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),Kp({start:oo(1),end:e},({i:e})=>{io(e.greaterThanEqual(n),()=>{Iu("break").toStack()});const t=ao(a.mul(ao(e))).toVar();p.addAssign(r.element(e).mul(mf({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),p.addAssign(r.element(e).mul(mf({theta:t,axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})))}),_o(p,1)}),ff=eo(([e])=>{const t=ho(e).toVar();return t.assign(t.shiftLeft(ho(16)).bitOr(t.shiftRight(ho(16)))),t.assign(t.bitAnd(ho(1431655765)).shiftLeft(ho(1)).bitOr(t.bitAnd(ho(2863311530)).shiftRight(ho(1)))),t.assign(t.bitAnd(ho(858993459)).shiftLeft(ho(2)).bitOr(t.bitAnd(ho(3435973836)).shiftRight(ho(2)))),t.assign(t.bitAnd(ho(252645135)).shiftLeft(ho(4)).bitOr(t.bitAnd(ho(4042322160)).shiftRight(ho(4)))),t.assign(t.bitAnd(ho(16711935)).shiftLeft(ho(8)).bitOr(t.bitAnd(ho(4278255360)).shiftRight(ho(8)))),ao(t).mul(2.3283064365386963e-10)}),yf=eo(([e,t])=>uo(ao(e).div(ao(t)),ff(e))),bf=eo(([e,t,s])=>{const i=s.mul(s).toConst(),r=go(1,0,0).toConst(),n=Ol(t,r).toConst(),a=Zh(e.x).toConst(),o=bh(2,3.14159265359).mul(e.y).toConst(),h=a.mul(al(o)).toConst(),l=a.mul(rl(o)).toVar(),u=bh(.5,t.z.add(1)).toConst();l.assign(u.oneMinus().mul(Zh(h.mul(h).oneMinus())).add(u.mul(l)));const c=r.mul(h).add(n.mul(l)).add(t.mul(Zh(Pl(0,h.mul(h).add(l.mul(l)).oneMinus()))));return sl(go(i.mul(c.x),i.mul(c.y),Pl(0,c.z)))}),_f=eo(({roughness:e,mipInt:t,envMap:s,N_immutable:i,GGX_SAMPLES:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const h=go(i).toVar(),l=go(0).toVar(),u=ao(0).toVar();return io(e.lessThan(.001),()=>{l.assign(pf(s,h,t,n,a,o))}).Else(()=>{const i=Ql(fl(h.z).lessThan(.999),go(0,0,1),go(1,0,0)),c=sl(Ol(i,h)).toVar(),d=Ol(h,c).toVar();Kp({start:ho(0),end:r},({i:i})=>{const p=yf(i,r),m=bf(p,go(0,0,1),e),g=sl(c.mul(m.x).add(d.mul(m.y)).add(h.mul(m.z))),f=sl(g.mul(Il(h,g).mul(2)).sub(h)),y=Pl(Il(h,f),0);io(y.greaterThan(0),()=>{const e=pf(s,f,t,n,a,o);l.addAssign(e.mul(y)),u.addAssign(y)})}),io(u.greaterThan(0),()=>{l.assign(l.div(u))})}),_o(l,1)}),xf=[.125,.215,.35,.446,.526,.582],vf=20,Tf=new pn(-1,1,1,-1,0,1),Sf=new hn(90,1),wf=new zs;let Mf=null,Nf=0,Af=0;const Ef=new Ot,Rf=new WeakMap,Cf=[3,1,5,0,4,2],Pf=cf($u(),ju("faceIndex")).normalize(),Bf=go(Pf.x,Pf.y,Pf.z);class Ff{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,s=.1,i=100,r={}){const{size:n=256,position:a=Ef,renderTarget:o=null}=r;if(this._setSize(n),!1===this._hasInitialized){bt('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const n=o||this._allocateTarget();return r.renderTarget=n,this.fromSceneAsync(e,t,s,i,r),n}Mf=this._renderer.getRenderTarget(),Nf=this._renderer.getActiveCubeFace(),Af=this._renderer.getActiveMipmapLevel();const h=o||this._allocateTarget();return h.depthBuffer=!0,this._init(h),this._sceneToCubeUV(e,s,i,h,a),t>0&&this._blur(h,0,0,t),this._applyPMREM(h),this._cleanup(h),h}async fromSceneAsync(e,t=0,s=.1,i=100,r={}){return xt('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,s,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){bt('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromEquirectangularAsync(e,s),s}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return xt('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){bt("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromCubemapAsync(e,t),s}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return xt('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=If(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Of(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===B||e.mapping===F?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(Mf,Nf,Af),e.scissorTest=!1,this._setViewport(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Mf=this._renderer.getRenderTarget(),Nf=this._renderer.getActiveCubeFace(),Af=this._renderer.getActiveMipmapLevel();const s=t||this._allocateTarget();return this._init(s),this._textureToCubeUV(e,s),this._applyPMREM(s),this._cleanup(s),s}_allocateTarget(){return Lf(3*Math.max(this._cubeSize,112),4*this._cubeSize)}_init(e){if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=Lf(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=function(e){const t=[],s=[],i=[];let r=e;const n=e-4+1+xf.length;for(let a=0;a<n;a++){const n=Math.pow(2,r);t.push(n);let o=1/n;a>e-4?o=xf[a-e+4-1]:0===a&&(o=0),s.push(o);const h=1/(n-2),l=-h,u=1+h,c=[l,l,u,l,u,u,l,l,u,u,l,u],d=6,p=6,m=3,g=2,f=1,y=new Float32Array(m*p*d),b=new Float32Array(g*p*d),_=new Float32Array(f*p*d);for(let e=0;e<d;e++){const t=e%3*2/3-1,s=e>2?0:-1,i=[t,s,0,t+2/3,s,0,t+2/3,s+1,0,t,s,0,t+2/3,s+1,0,t,s+1,0],r=Cf[e];y.set(i,m*p*r),b.set(c,g*p*r);const n=[r,r,r,r,r,r];_.set(n,f*p*r)}const x=new Vi;x.setAttribute("position",new Mi(y,m)),x.setAttribute("uv",new Mi(b,g)),x.setAttribute("faceIndex",new Mi(_,f)),i.push(new mr(x,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:s}}(t)),this._blurMaterial=function(e,t,s){const i=nc(new Array(vf).fill(0)),r=uh(new Ot(0,1,0)),n=uh(0),a=ao(vf),o=uh(0),h=uh(1),l=Ju(),u=uh(0),c=ao(1/t),d=ao(1/s),p=ao(e),m={n:a,latitudinal:o,weights:i,poleAxis:r,outputDirection:Bf,dTheta:n,samples:h,envMap:l,mipInt:u,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=Df("blur");return g.fragmentNode=gf({...m,latitudinal:o.equal(1)}),Rf.set(g,m),g}(t,e.width,e.height),this._ggxMaterial=function(e,t,s){const i=Ju(),r=uh(0),n=uh(0),a=ao(1/t),o=ao(1/s),h=ao(e),l={envMap:i,roughness:r,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:h},u=Df("ggx");return u.fragmentNode=_f({...l,N_immutable:Bf,GGX_SAMPLES:ho(512)}),Rf.set(u,l),u}(t,e.width,e.height)}}async _compileMaterial(e){const t=new mr(new Vi,e);await this._renderer.compile(t,Tf)}_sceneToCubeUV(e,t,s,i,r){const n=Sf;n.near=t,n.far=s;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],h=this._renderer,l=h.autoClear;h.getClearColor(wf),h.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new mr(new Dr,new sr({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const u=this._backgroundBox,c=u.material;let d=!1;const p=e.background;p?p.isColor&&(c.color.copy(p),e.background=null,d=!0):(c.color.copy(wf),d=!0),h.setRenderTarget(i),h.clear(),d&&h.render(u,n);for(let t=0;t<6;t++){const s=t%3;0===s?(n.up.set(0,a[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x+o[t],r.y,r.z)):1===s?(n.up.set(0,0,a[t]),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y+o[t],r.z)):(n.up.set(0,a[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y,r.z+o[t]));const l=this._cubeSize;this._setViewport(i,s*l,t>2?l:0,l,l),h.render(e,n)}h.autoClear=l,e.background=p}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===B||e.mapping===F;i?null===this._cubemapMaterial&&(this._cubemapMaterial=If(e)):null===this._equirectMaterial&&(this._equirectMaterial=Of(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),s.setRenderTarget(t),s.render(n,Tf)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let t=1;t<i;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=s}_applyGGXFilter(e,t,s){const i=this._renderer,r=this._pingPongRenderTarget,n=this._ggxMaterial,a=this._lodMeshes[s];a.material=n;const o=Rf.get(n),h=s/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(h*h-l*l)*(0+1.25*h),{_lodMax:c}=this,d=this._sizeLods[s],p=3*d*(s>c-4?s-c+4:0),m=4*(this._cubeSize-d);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=u,o.mipInt.value=c-t,this._setViewport(r,p,m,3*d,2*d),i.setRenderTarget(r),i.render(a,Tf),r.texture.frame=(r.texture.frame||0)+1,o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=c-s,this._setViewport(e,p,m,3*d,2*d),i.setRenderTarget(e),i.render(a,Tf)}_blur(e,t,s,i,r){const n=this._pingPongRenderTarget;this._halfBlur(e,n,t,s,i,"latitudinal",r),this._halfBlur(n,e,s,s,i,"longitudinal",r)}_halfBlur(e,t,s,i,r,n,a){const o=this._renderer,h=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&_t("blur direction must be either latitudinal or longitudinal!");const l=this._lodMeshes[i];l.material=h;const u=Rf.get(h),c=this._sizeLods[s]-1,d=isFinite(r)?Math.PI/(2*c):2*Math.PI/39,p=r/d,m=isFinite(r)?1+Math.floor(3*p):vf;m>vf&&bt(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const g=[];let f=0;for(let e=0;e<vf;++e){const t=e/p,s=Math.exp(-t*t/2);g.push(s),0===e?f+=s:e<m&&(f+=2*s)}for(let e=0;e<g.length;e++)g[e]=g[e]/f;e.texture.frame=(e.texture.frame||0)+1,u.envMap.value=e.texture,u.samples.value=m,u.weights.array=g,u.latitudinal.value="latitudinal"===n?1:0,a&&(u.poleAxis.value=a);const{_lodMax:y}=this;u.dTheta.value=d,u.mipInt.value=y-s;const b=this._sizeLods[i],_=3*b*(i>y-4?i-y+4:0),x=4*(this._cubeSize-b);this._setViewport(t,_,x,3*b,2*b),o.setRenderTarget(t),o.render(l,Tf)}_setViewport(e,t,s,i,r){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-r-s,i,r),e.scissor.set(t,e.height-r-s,i,r)):(e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r))}}function Lf(e,t){const s=new is(e,t,{magFilter:z,minFilter:z,generateMipmaps:!1,type:K,format:re,colorSpace:Xe});return s.texture.mapping=306,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function Df(e){const t=new Em;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function If(e){const t=Df("cubemap");return t.fragmentNode=bd(e,Bf),t}function Of(e){const t=Df("equirect");return t.fragmentNode=Ju(e,Dm(Bf),0),t}const Uf=new WeakMap;function kf(e,t,s){const i=function(e){let t=Uf.get(e);void 0===t&&(t=new WeakMap,Uf.set(e,t));return t}(t);let r=i.get(e);if((void 0!==r?r.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const s=6;for(let i=0;i<s;i++)void 0!==e[i]&&t++;return t===s}(t))return null;r=s.fromCubemap(e,r)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;r=s.fromEquirectangular(e,r)}r.pmremVersion=e.pmremVersion,i.set(e,r)}return r.texture}class zf extends na{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new ts;i.isRenderTargetTexture=!0,this._texture=Ju(i),this._width=uh(0),this._height=uh(0),this._maxMip=uh(0),this.updateBeforeType=Hn}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,s=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:s,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const s=t?t.pmremVersion:-1,i=this._value;s!==i.pmremVersion&&(t=!0===i.isPMREMTexture?i:kf(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Ff(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=ud.mul(go(t.x,t.y.negate(),t.z));let s=this.levelNode;return null===s&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),df(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const Vf=Ya(zf).setParameterLength(1,3),Gf=new WeakMap;class jf extends sm{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const i=s.isTextureNode?s.value:t[s.property],r=this._getPMREMNodeCache(e.renderer);let n=r.get(i);void 0===n&&(n=Vf(i),r.set(i,n)),s=n}const i=!0===t.useAnisotropy||t.anisotropy>0?$d:sd,r=s.context($f(Bo,i)).mul(ld),n=s.context(Wf(id)).mul(Math.PI).mul(ld),a=Bu(r),o=Bu(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const h=e.context.lightingModel.clearcoatRadiance;if(h){const e=s.context($f(Do,rd)).mul(ld),t=Bu(e);h.addAssign(t)}}_getPMREMNodeCache(e){let t=Gf.get(e);return void 0===t&&(t=new WeakMap,Gf.set(e,t)),t}}const $f=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=qc.negate().reflect(t),s=zl(e).mix(s,t).normalize(),s=s.transformDirection(Rc)),s),getTextureLevel:()=>e}},Wf=e=>({getUV:()=>e,getTextureLevel:()=>ao(1)}),Hf=new zr;class qf extends Em{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(Hf),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new jf(t):null}setupLightingModel(){return new Xg}setupSpecular(){const e=jl(go(.04),Ro.rgb,Fo);Wo.assign(go(.04)),Ho.assign(e),qo.assign(1)}setupVariants(){const e=this.metalnessNode?ao(this.metalnessNode):cp;Fo.assign(e);let t=this.roughnessNode?ao(this.roughnessNode):up;t=rg({roughness:t}),Bo.assign(t),this.setupSpecular(),Co.assign(Ro.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Xf=new Vr;class Yf extends qf{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(Xf),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?ao(this.iorNode):Mp;Zo.assign(e),Wo.assign(Cl(kl(Zo.sub(1).div(Zo.add(1))).mul(op),go(1)).mul(ap)),Ho.assign(jl(Wo,Ro.rgb,Fo)),qo.assign(jl(ap,1,Fo))}setupLightingModel(){return new Xg(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?ao(this.clearcoatNode):pp,t=this.clearcoatRoughnessNode?ao(this.clearcoatRoughnessNode):mp;Lo.assign(e),Do.assign(rg({roughness:t}))}if(this.useSheen){const e=this.sheenNode?go(this.sheenNode):yp,t=this.sheenRoughnessNode?ao(this.sheenRoughnessNode):bp;Io.assign(e),Oo.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?ao(this.iridescenceNode):xp,t=this.iridescenceIORNode?ao(this.iridescenceIORNode):vp,s=this.iridescenceThicknessNode?ao(this.iridescenceThicknessNode):Tp;Uo.assign(e),ko.assign(t),zo.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?uo(this.anisotropyNode):_p).toVar();Go.assign(e.length()),io(Go.equal(0),()=>{e.assign(uo(1,0))}).Else(()=>{e.divAssign(uo(Go)),Go.assign(Go.saturate())}),Vo.assign(Go.pow2().mix(Bo.pow2(),1)),jo.assign(jd[0].mul(e.x).add(jd[1].mul(e.y))),$o.assign(jd[1].mul(e.x).sub(jd[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?ao(this.transmissionNode):Sp,t=this.thicknessNode?ao(this.thicknessNode):wp,s=this.attenuationDistanceNode?ao(this.attenuationDistanceNode):Np,i=this.attenuationColorNode?go(this.attenuationColorNode):Ap;if(Jo.assign(e),eh.assign(t),th.assign(s),sh.assign(i),this.useDispersion){const e=this.dispersionNode?ao(this.dispersionNode):Fp;ih.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?go(this.clearcoatNormalNode):gp}setup(e){e.context.setupClearcoatNormal=()=>ru(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const Kf=eo(({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=uo(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=wd("gradientMap","texture").context({getUV:()=>r});return go(e.r)}{const e=r.fwidth().mul(.5);return jl(go(.7),go(1),ql(ao(.7).sub(e.x),ao(.7).add(e.x),r.x))}});class Qf extends $m{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const r=Kf({normal:Qc,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(r.mul(Ym({diffuseColor:Ro.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(Ym({diffuseColor:Ro}))),i.indirectDiffuse.mulAssign(t)}}const Zf=new jr;class Jf extends Em{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Zf),this.setValues(e)}setupLightingModel(){return new Qf}}const ey=eo(()=>{const e=go(qc.z,0,qc.x.negate()).normalize(),t=qc.cross(e);return uo(e.dot(sd),t.dot(sd)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),ty=new Hr;class sy extends Em{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(ty),this.setValues(e)}setupVariants(e){const t=ey;let s;s=e.material.matcap?wd("matcap","texture").context({getUV:()=>t}):go(jl(.2,.8,t.y)),Ro.rgb.mulAssign(s.rgb)}}class iy extends na{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:s}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return So(e,i,i.negate(),e).mul(s)}{const e=t,i=Mo(_o(1,0,0,0),_o(0,al(e.x),rl(e.x).negate(),0),_o(0,rl(e.x),al(e.x),0),_o(0,0,0,1)),r=Mo(_o(al(e.y),0,rl(e.y),0),_o(0,1,0,0),_o(rl(e.y).negate(),0,al(e.y),0),_o(0,0,0,1)),n=Mo(_o(al(e.z),rl(e.z).negate(),0,0),_o(rl(e.z),al(e.z),0,0),_o(0,0,1,0),_o(0,0,0,1));return i.mul(r).mul(n).mul(_o(s,1)).xyz}}}const ry=Ya(iy).setParameterLength(2),ny=new qi;class ay extends Em{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(ny),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,{positionNode:i,rotationNode:r,scaleNode:n,sizeAttenuation:a}=this,o=Ic.mul(go(i||0));let h=uo(Lc[0].xyz.length(),Lc[1].xyz.length());null!==n&&(h=h.mul(uo(n))),s.isPerspectiveCamera&&!1===a&&(h=h.mul(o.z.negate()));let l=Vc.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,s)=>new pu(e,t,s))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(h);const u=ao(r||fp),c=ry(l,u);return _o(o.xy.add(c),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const oy=new Cr,hy=new Dt;class ly extends ay{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(oy),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Ic.mul(go(e||Gc)).xyz}setupVertexSprite(e){const{material:t,camera:s}=e,{rotationNode:i,scaleNode:r,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let h=null!==n?uo(n):Bp;h=h.mul(uc),s.isPerspectiveCamera&&!0===a&&(h=h.mul(uy.div(Hc.z.negate()))),r&&r.isNode&&(h=h.mul(uo(r)));let l=Vc.xy;if(i&&i.isNode){const e=ao(i);l=ry(l,e)}return l=l.mul(h),l=l.div(gc.div(2)),l=l.mul(o.w),o=o.add(_o(l,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const uy=uh(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(hy);this.value=.5*t.y});class cy extends $m{constructor(){super(),this.shadowNode=ao(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Ro.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Ro.rgb)}}const dy=new kr;class py extends Em{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(dy),this.setValues(e)}setupLightingModel(){return new cy}}Ao("vec3"),Ao("vec3"),Ao("vec3");class my{constructor(e,t,s){this.renderer=e,this.nodes=t,this.info=s,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,s)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,s),this.renderer._inspector.finish()};e()}stop(){null!==this._context&&this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class gy{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let s=this.weakMaps[t];return void 0===s&&(s=new WeakMap,this.weakMaps[t]=s),s}get(e){let t=this._getWeakMap(e);for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let s=this._getWeakMap(e);for(let t=0;t<e.length-1;t++){const i=e[t];!1===s.has(i)&&s.set(i,new WeakMap),s=s.get(i)}return s.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),void 0===t)return!1;return t.delete(e[e.length-1])}}let fy=0;class yy{constructor(e,t,s,i,r,n,a,o,h,l){this.id=fy++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=r,this.scene=n,this.camera=a,this.lightsNode=o,this.context=h,this.geometry=i.geometry,this.version=r.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=l,this.clippingContextCacheKey=null!==l?l.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set,r={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),r[n.name]=e.id),void 0===e)continue;s.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;i.add(a)}return this.attributes=s,this.attributesId=r,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:r}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let h=1;if(!0===s.isInstancedBufferGeometry?h=s.instanceCount:void 0!==e.count&&(h=Math.max(0,e.count)),0===h)return null;if(n.instanceCount=h,!0===e.isBatchedMesh)return n;let l=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(l=2);let u=r.start*l,c=(r.start+r.count)*l;null!==i&&(u=Math.max(u,i.start*l),c=Math.min(c,(i.start+i.count)*l));const d=s.attributes.position;let p=1/0;o?p=a.count:null!=d&&(p=d.count),u=Math.max(u,0),c=Math.min(c,p);const m=c-u;return m<0||m===1/0?null:(n.vertexCount=m,n.firstVertex=u,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const s of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[s];t+="morph-"+s+",";for(let e=0,s=i.length;e<s;e++){t+=i[e].id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:s}=this;let i=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let s=Object.getPrototypeOf(e);for(;s;){const e=Object.getOwnPropertyDescriptors(s);for(const s in e)if(void 0!==e[s]){const i=e[s];i&&"function"==typeof i.get&&t.push(s)}s=Object.getPrototypeOf(s)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const r=t[e];let n;if(null!==r){const e=typeof r;"number"===e?n=0!==r?"1":"0":"object"===e?(n="{",r.isTexture&&(n+=r.mapping,!0===s.backend.isWebGPUBackend&&(n+=r.magFilter,n+=r.minFilter,n+=r.wrapS,n+=r.wrapT,n+=r.wrapR)),n+="}"):n=String(r)}else n=String(r);i+=n+","}return i+=this.clippingContextCacheKey+",",e.geometry&&(i+=this.getGeometryCacheKey()),e.skeleton&&(i+=e.skeleton.bones.length+","),e.isBatchedMesh&&(i+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(i+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1||Array.isArray(e.morphTargetInfluences))&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",Ln(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(null!==this.attributes){const e=this.attributesId;for(const t in e){const s=this.geometry.getAttribute(t);if(void 0===s||e[t]!==s.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=In(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=In(e,1)),e=In(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const by=[];class _y{constructor(e,t,s,i,r,n){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=r,this.info=n,this.chainMaps={}}get(e,t,s,i,r,n,a,o){const h=this.getChainMap(o);by[0]=e,by[1]=t,by[2]=n,by[3]=r;let l=h.get(by);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,a,o),h.set(by,l)):(l.camera=i,l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,s,i,r,n,a,o)):l.version=t.version)),by[0]=null,by[1]=null,by[2]=null,by[3]=null,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new gy)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,a,o,h,l,u){const c=this.getChainMap(u),d=new yy(e,t,s,i,r,n,a,o,h,l);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),c.delete(d.getChainArray())},d}}class xy{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const vy=1,Ty=2,Sy=3,wy=4,My=16;class Ny extends xy{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){const t=super.delete(e);return null!==t&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===vy?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===Ty?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===Sy?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===wy&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version<t.version||t.usage===ot)&&(this.backend.updateAttribute(e),s.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function Ay(e){return null!==e.index?e.index.version:e.attributes.position.version}function Ey(e){return null!==e.index?e.index.id:e.attributes.position.id}function Ry(e){const t=[],s=e.index,i=e.attributes.position;if(null!==s){const e=s.array;for(let s=0,i=e.length;s<i;s+=3){const i=e[s+0],r=e[s+1],n=e[s+2];t.push(i,r,r,n,n,i)}}else{for(let e=0,s=i.array.length/3-1;e<s;e+=3){const s=e+0,i=e+1,r=e+2;t.push(s,i,i,r,r,s)}}const r=new(i.count>=65535?Ai:Ni)(t,1);return r.version=Ay(e),r.__id=Ey(e),r}class Cy extends xy{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",s),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",s),this._geometryDisposeListeners.set(t,s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,Sy):this.updateAttribute(e,vy);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,Ty);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,wy)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(!0===s.wireframe){const e=this.wireframes;let s=e.get(t);void 0===s?(s=Ry(t),e.set(t,s)):s.version===Ay(t)&&s.__id===Ey(t)||(this.attributes.delete(s),s=Ry(t),e.set(t,s)),i=s}return i}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class Py{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0,attributes:0,indexAttributes:0,storageAttributes:0,indirectStorageAttributes:0,readbackBuffers:0,programs:0,renderTargets:0,total:0,texturesSize:0,attributesSize:0,indexAttributesSize:0,storageAttributesSize:0,indirectStorageAttributesSize:0,readbackBuffersSize:0,programsSize:0},this.memoryMap=new Map}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):_t("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap.clear()}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const s=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:s,type:t}),this.memory[t]++,this.memory.total+=s,this.memory[t+"Size"]+=s}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===$||e.type===j?t=1:e.type===W||e.type===H||e.type===K?t=2:e.type!==q&&e.type!==X&&e.type!==Y||(t=4);let s=4;e.format===se||e.format===oe||e.format===he||e.format===ne||e.format===ae?s=1:e.format===le||e.format===ue?s=2:e.format!==ie&&1032!==e.format||(s=3);let i=t*s;e.type===Q||e.type===Z?i=2:e.type!==J&&e.type!==ee&&e.type!==te||(i=4);const r=e.width||1,n=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=r*n*a*i;const h=e.mipmaps;if(h&&h.length>0){let e=0;for(let t=0;t<h.length;t++){const s=h[t];if(s.data)e+=s.data.byteLength;else{e+=(s.width||Math.max(1,r>>t))*(s.height||Math.max(1,n>>t))*a*i}}o+=e}else e.generateMipmaps&&(o*=1.333);return Math.round(o)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}}class By{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Fy extends By{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class Ly extends By{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Dy=0;class Iy{constructor(e,t,s,i=null,r=null){this.id=Dy++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=r,this.usedTimes=0}}class Oy extends xy{constructor(e,t,s){super(),this.backend=e,this.nodes=t,this.info=s,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let a=this.programs.compute.get(n.computeShader);void 0===a&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),a=new Iy(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),s.createProgram(a),this.info.createProgram(a));const o=this._getComputeCacheKey(e,a);let h=this.caches.get(o);void 0===h&&(r&&0===r.usedTimes&&this._releasePipeline(r),h=this._getComputePipeline(e,a,o,t)),h.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=h}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new Iy(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),s.createProgram(o),this.info.createProgram(o));let h=this.programs.fragment.get(n.fragmentShader);void 0===h&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),h=new Iy(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,h),s.createProgram(h),this.info.createProgram(h));const l=this._getRenderCacheKey(e,o,h);let u=this.caches.get(l);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,o,h,l,t)):e.pipeline=u,u.usedTimes++,o.usedTimes++,h.usedTimes++,i.pipeline=u}return i.pipeline}isReady(e){const t=this.get(e).pipeline;if(void 0===t)return!1;const s=this.backend.get(t);return void 0!==s.pipeline&&null!==s.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,s,i){s=s||this._getComputeCacheKey(e,t);let r=this.caches.get(s);return void 0===r&&(r=new Ly(s,t),this.caches.set(s,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,s,i,r){i=i||this._getRenderCacheKey(e,t,s);let n=this.caches.get(i);return void 0===n&&(n=new Fy(i,t,s),this.caches.set(i,n),e.pipeline=n,this.backend.createRenderPipeline(e,r)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].delete(t),this.info.destroyProgram(e)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class Uy extends xy{constructor(e,t,s,i,r,n){super(),this.backend=e,this.textures=s,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),s.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),s.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,s=e.isIndirectStorageBufferAttribute?wy:Sy;this.attributes.update(e,s)}}_update(e,t){const{backend:s}=this;let i=!1,r=!0,n=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?wy:Sy,n=s.get(t);this.attributes.update(e,r),n.attribute!==e&&(n.attribute=e,i=!0)}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),h=t.texture,l=this.textures.get(h);o&&(this.textures.updateTexture(h),t.generation!==l.generation&&(t.generation=l.generation,i=!0),l.bindGroups.add(e));if(void 0!==s.get(h).externalTexture||l.isDefaultTexture?r=!1:(n=10*n+h.id,a+=h.version),!0===h.isStorageTexture&&!0===h.mipmapsAutoUpdate){const e=this.get(h);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(h)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(h),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,i=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===i&&this.backend.updateBindings(e,t,r?n:0,a)}}function ky(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?e.z-t.z:e.id-t.id}function zy(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function Vy(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class Gy{constructor(e,t,s){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,s),this.lightsArray=[],this.scene=t,this.camera=s,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,i,r,n,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:r,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=s,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,s,i,r,n,a){const o=this.getNextRenderItem(e,t,s,i,r,n,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(Vy(s)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,s,i,r,n,a){const o=this.getNextRenderItem(e,t,s,i,r,n,a);!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(Vy(s)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||ky),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||zy),this.transparent.length>1&&this.transparent.sort(t||zy)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.groupOrder=null,t.renderOrder=null,t.z=null,t.group=null,t.clippingContext=null}}}const jy=[];class $y{constructor(e){this.lighting=e,this.lists=new gy}get(e,t){const s=this.lists;jy[0]=e,jy[1]=t;let i=s.get(jy);return void 0===i&&(i=new Gy(this.lighting,e,t),s.set(jy,i)),jy[0]=null,jy[1]=null,i}dispose(){this.lists=new gy}}let Wy=0;class Hy{constructor(){this.id=Wy++,this.mrt=null,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new ss,this.scissor=!1,this.scissorValue=new ss,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.isRenderContext=!0}getCacheKey(){return qy(this)}}function qy(e){const{textures:t,activeCubeFace:s,activeMipmapLevel:i}=e,r=[s,i];for(const e of t)r.push(e.id);return Dn(r)}class Xy{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,s=0){let i;if(null===e)i="default";else{const t=e.texture.format,s=e.texture.type;i=`${e.textures.length}:${t}:${s}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const r=i+"-"+(null!==t?t.id:"default")+"-"+s;let n=this._renderContexts[r];return void 0===n&&(n=new Hy,n.mrt=t,this._renderContexts[r]=n),null!==e&&(n.sampleCount=0===e.samples?1:e.samples),n.clearDepthValue=this.renderer.getClearDepth(),n.clearStencilValue=this.renderer.getClearStencil(),n}dispose(){this._renderContexts={}}}const Yy=new Ot;class Ky extends xy{constructor(e,t,s){super(),this.renderer=e,this.backend=t,this.info=s,this._htmlTextures=new Set}updateRenderTarget(e,t=0){const s=this.get(e),i=0===e.samples?1:e.samples,r=s.depthTextureMips||(s.depthTextureMips={}),n=e.textures,a=this.getSize(n[0]),o=a.width>>t,h=a.height>>t;let l=e.depthTexture||r[t];const u=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===l&&u&&(l=new Fr,l.format=e.stencilBuffer?ae:ne,l.type=e.stencilBuffer?J:X,l.image.width=o,l.image.height=h,l.image.depth=a.depth,l.renderTarget=e,l.isArrayTexture=!0===e.multiview&&a.depth>1,r[t]=l),s.width===a.width&&a.height===s.height||(c=!0,l&&(l.needsUpdate=!0,l.image.width=o,l.image.height=h,l.image.depth=l.isArrayTexture?l.image.depth:1)),s.width=a.width,s.height=a.height,s.textures=n,s.depthTexture=l||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(c=!0,l&&(l.needsUpdate=!0),s.sampleCount=i);const d={sampleCount:i};if(!0!==e.isXRRenderTarget){for(let e=0;e<n.length;e++){const t=n[e];c&&(t.needsUpdate=!0),this.updateTexture(t,d)}l&&this.updateTexture(l,d)}!0!==s.initialized&&(s.initialized=!0,this.info.memory.renderTargets++,s.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",s.onDispose))}updateTexture(e,t={}){const s=this.get(e);if(!0===s.initialized&&s.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,r=this.backend;if(i&&!0===s.initialized&&r.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:j}if(e.isHTMLTexture&&e.image){const t=this.renderer.domElement;if("requestPaint"in t){if(t.hasAttribute("layoutsubtree")||t.setAttribute("layoutsubtree","true"),e.image.parentNode!==t&&t.appendChild(e.image),0===this._htmlTextures.size){const e=this._htmlTextures;t.onpaint=t=>{const s=t&&t.changedElements;for(const t of e)s&&!s.includes(t.image)||(t.needsUpdate=!0)}}this._htmlTextures.add(e)}}const{width:n,height:a,depth:o}=this.getSize(e);if(t.width=n,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,i||!0===e.isStorageTexture||!0===e.isExternalTexture)r.createTexture(e,t),s.generation=e.version;else if(e.version>0){const i=e.image;if(void 0===i)bt("Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)bt("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const s=[];for(const t of e.images)s.push(t);t.images=s}else t.image=i;void 0!==s.isDefaultTexture&&!0!==s.isDefaultTexture||(r.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t);const n=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!n&&r.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else r.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version;!0!==s.initialized&&(s.initialized=!0,s.generation=e.version,s.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&!0===Wt.enabled&&Wt.getTransfer(e.colorSpace)!==Ke&&bt("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),s.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",s.onDispose)),s.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=Yy){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),e.isHTMLTexture?(t.width=s.offsetWidth||1,t.height=s.offsetHeight||1,t.depth=1):"undefined"!=typeof HTMLVideoElement&&s instanceof HTMLVideoElement?(t.width=s.videoWidth||1,t.height=s.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&s instanceof VideoFrame?(t.width=s.displayWidth||1,t.height=s.displayHeight||1,t.depth=1):(t.width=s.width||1,t.height=s.height||1,t.depth=e.isCubeTexture?6:s.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return i=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),s=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e<s.length;e++)this._destroyTexture(s[e]);i&&this._destroyTexture(i),this.delete(e),this.backend.delete(e),this.info.memory.renderTargets--}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const s=t.isDefaultTexture;if(this.backend.destroyTexture(e,s),t.bindGroups)for(const e of t.bindGroups){const t=this.backend.get(e);t.groups=void 0,t.versions=void 0}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}}class Qy extends zs{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class Zy extends No{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const s=this.getNodeType(e),i=e.getStructTypeNode(s);let r;return null!==i?r=i.getMemberType(e,t):(_t(`TSL: Member "${t}" not found in struct "${s}".`,new Bn),r="float"),r}getHash(){return String(this.id)}generate(){return this.name}}class Jy extends sa{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this.isStackNode=!0}getElementType(e){return this.hasOutput(e)?this.outputNode.getElementType(e):"void"}generateNodeType(e){return this.hasOutput(e)?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput(e)?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=this.nodes.length){return!0!==e.isNode?(_t("TSL: Invalid node added to stack.",new Bn),this):(this.nodes.splice(t,0,e),this)}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const s=new $a(t);return this._currentCond=Ql(e,s),this.addToStack(this._currentCond)}ElseIf(e,t){const s=new $a(t),i=Ql(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new $a(e),this}Switch(e){return this._expressionNode=Wa(e),this}Case(...e){const t=[];if(e.length>=2)for(let s=0;s<e.length-1;s++)t.push(this._expressionNode.equal(Wa(e[s])));else _t("TSL: Invalid parameter length. Case() requires at least two parameters.",new Bn);const s=new $a(e[e.length-1]);let i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);const r=Ql(i,s);return null===this._currentCond?(this._currentCond=r,this.addToStack(this._currentCond)):(this._currentCond.elseNode=r,this._currentCond=r,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let s=0;for(const i of this.getChildren())i.isVarNode&&i.isIntent(e)&&!0!==i.isAssign(e)||(t["node"+s++]=i);return t.outputNode||null}hasOutput(e){return this.outputNode&&this.outputNode.isNode&&"void"!==this.outputNode.getNodeType(e)}build(e,...t){const s=so(),i=e.buildStage;to(this),e.setActiveStack(this);const r=t=>{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===i)t.build(e);else if("analyze"===i)t.build(e,this);else if("generate"===i){const s=e.getDataFromNode(t,"any").stages,i=s&&s[e.shaderStage];if(t.isVarNode&&i&&1===i.length&&i[0]&&i[0].isStackNode)return;t.build(e,"void")}},n=[...this.nodes];for(const e of n)r(e);this._currentNode=null;const a=this.nodes.filter(e=>-1===n.indexOf(e));for(const e of a)r(e);let o;return o=this.hasOutput(e)?this.outputNode.build(e,...t):super.build(e,...t),to(s),e.removeActiveStack(this),o}}const eb=Ya(Jy).setParameterLength(0,1);class tb extends na{static get type(){return"BitcastNode"}constructor(e,t,s=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=s,this.isBitcastNode=!0}generateNodeType(e){if(null!==this.inputType){const t=this.valueNode.getNodeType(e),s=e.getTypeLength(t);return e.getTypeFromLength(s,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let s="";if(null!==this.inputType){const t=this.valueNode.getNodeType(e);s=1===e.getTypeLength(t)?this.inputType:e.changeComponentType(t,this.inputType)}else s=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,s)}( ${this.valueNode.build(e,s)} )`}}const sb=Qa(tb).setParameterLength(2),ib={};class rb extends Vh{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,s){"int"===s?t.assign(sb(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return ho;case"int":return oo;case"uvec2":return po;case"uvec3":return yo;case"uvec4":return vo;case"ivec2":return co;case"ivec3":return fo;case"ivec4":return xo}}_createTrailingZerosBaseLayout(e,t){const s=this._returnDataNode(t),i=eo(([e])=>{const i=ho(0);this._resolveElementType(e,i,t);const r=(e=>new tb(e,"uint","float"))(ao(i.bitAnd(_l(i)))),n=r.shiftRight(23).sub(127);return s(n)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createLeadingZerosBaseLayout(e,t){const s=this._returnDataNode(t),i=eo(([e])=>{io(e.equal(ho(0)),()=>ho(32));const i=ho(0),r=ho(0);return this._resolveElementType(e,i,t),io(i.shiftRight(16).equal(0),()=>{r.addAssign(16),i.shiftLeftAssign(16)}),io(i.shiftRight(24).equal(0),()=>{r.addAssign(8),i.shiftLeftAssign(8)}),io(i.shiftRight(28).equal(0),()=>{r.addAssign(4),i.shiftLeftAssign(4)}),io(i.shiftRight(30).equal(0),()=>{r.addAssign(2),i.shiftLeftAssign(2)}),io(i.shiftRight(31).equal(0),()=>{r.addAssign(1)}),s(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createOneBitsBaseLayout(e,t){const s=this._returnDataNode(t),i=eo(([e])=>{const i=ho(0);this._resolveElementType(e,i,t),i.assign(i.sub(i.shiftRight(ho(1)).bitAnd(ho(1431655765)))),i.assign(i.bitAnd(ho(858993459)).add(i.shiftRight(ho(2)).bitAnd(ho(858993459))));const r=i.add(i.shiftRight(ho(4))).bitAnd(ho(252645135)).mul(ho(16843009)).shiftRight(ho(24));return s(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createMainLayout(e,t,s,i){const r=this._returnDataNode(t),n=eo(([e])=>{if(1===s)return r(i(e));{const t=r(0),n=["x","y","z","w"];for(let r=0;r<s;r++){const s=n[r];t[s].assign(i(e[s]))}return t}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return n}setup(e){const{method:t,aNode:s}=this,{renderer:i}=e;if(i.backend.isWebGPUBackend)return super.setup(e);const r=this.getInputType(e),n=e.getElementType(r),a=e.getTypeLength(r),o=`${t}_base_${n}`,h=`${t}_${r}`;let l=ib[o];if(void 0===l){switch(t){case rb.COUNT_LEADING_ZEROS:l=this._createLeadingZerosBaseLayout(o,n);break;case rb.COUNT_TRAILING_ZEROS:l=this._createTrailingZerosBaseLayout(o,n);break;case rb.COUNT_ONE_BITS:l=this._createOneBitsBaseLayout(o,n)}ib[o]=l}let u=ib[h];void 0===u&&(u=this._createMainLayout(h,r,a,l),ib[h]=u);return eo(()=>u(s))()}}rb.COUNT_TRAILING_ZEROS="countTrailingZeros",rb.COUNT_LEADING_ZEROS="countLeadingZeros",rb.COUNT_ONE_BITS="countOneBits",new ns;const nb=new is;cc.flipX(),nb.depthTexture=new Fr(1,1);const ab=new pn(-1,1,1,-1,0,1);class ob extends Vi{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Ri([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Ri(t,2))}}const hb=new ob;class lb extends mr{constructor(e=null){super(hb,e),this.camera=ab,this.isQuadMesh=!0}async renderAsync(e){xt('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,ab)}render(e){e.render(this,ab)}}const ub=eo(([e])=>il(ao(52.9829189).mul(il(Il(e,uo(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),cb=eo(([e,t,s])=>{const i=ao(2.399963229728653),r=Zh(ao(e).add(.5).div(ao(t))),n=ao(e).mul(i).add(s);return uo(al(n),rl(n)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class db extends sa{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===db.OBJECT?this.updateType=qn:e===db.MATERIAL?this.updateType=Hn:e===db.FRAME?this.updateType=Wn:e===db.BEFORE_OBJECT?this.updateBeforeType=qn:e===db.BEFORE_MATERIAL?this.updateBeforeType=Hn:e===db.BEFORE_FRAME&&(this.updateBeforeType=Wn)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}db.OBJECT="object",db.MATERIAL="material",db.FRAME="frame",db.BEFORE_OBJECT="beforeObject",db.BEFORE_MATERIAL="beforeMaterial",db.BEFORE_FRAME="beforeFrame";const pb=new ns,mb=uh(0).setGroup(oh).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),gb=uh(1).setGroup(oh).onRenderUpdate(({scene:e})=>e.backgroundIntensity),fb=uh(new ns).setGroup(oh).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&300!==t.mapping?pb.makeRotationFromEuler(e.backgroundRotation).transpose():pb.identity(),pb});eo(({texture:e,uv:t})=>{const s=1e-4,i=go().toVar();return io(t.x.lessThan(s),()=>{i.assign(go(1,0,0))}).ElseIf(t.y.lessThan(s),()=>{i.assign(go(0,1,0))}).ElseIf(t.z.lessThan(s),()=>{i.assign(go(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{i.assign(go(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{i.assign(go(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{i.assign(go(0,0,-1))}).Else(()=>{const s=.01,r=e.sample(t.add(go(-.01,0,0))).r.sub(e.sample(t.add(go(s,0,0))).r),n=e.sample(t.add(go(0,-.01,0))).r.sub(e.sample(t.add(go(0,s,0))).r),a=e.sample(t.add(go(0,0,-.01))).r.sub(e.sample(t.add(go(0,0,s))).r);i.assign(go(r,n,a))}),i.normalize()}),eo(([e,t])=>e.mul(t).floor().div(t));const yb=new Dt;class bb extends Qu{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){return e.getNodeProperties(this).passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class _b extends bb{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class xb extends na{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new Fr;r.isRenderTargetTexture=!0,r.name="depth";const n=new is(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:K,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=uh(0),this._cameraFar=uh(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=Wn,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return bt("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return bt("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new _b(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new _b(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=bm(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=fm(r,s,i)}return t}async compileAsync(e){const t=e.getRenderTarget(),s=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(s)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),!0===e.reversedDepthBuffer&&(this.renderTarget.depthTexture.type=Y),this.scope===xb.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s}=this;let i,r;const n=t.getOutputRenderTarget();n&&!0===n.isXRRenderTarget?(r=1,i=t.xr.getCamera(),t.xr.updateCamera(i),yb.set(n.width,n.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(yb)),this._pixelRatio=r,this.setSize(yb.width,yb.height);const a=t.getRenderTarget(),o=t.getMRT(),h=t.autoClear,l=t.transparent,u=t.opaque,c=i.layers.mask,d=t.contextNode,p=s.overrideMaterial;this._cameraNear.value=i.near,this._cameraFar.value=i.far,null!==this._layers&&(i.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(s.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Jl({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const m=s.name;s.name=this.name?this.name:s.name,t.render(s,i),s.name=m,s.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(o),t.autoClear=h,t.transparent=l,t.opaque=u,t.contextNode=d,i.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const s=Math.floor(this._width*this._pixelRatio*this._resolutionScale),i=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(s,i),null!==this._scissor?(this.renderTarget.scissor.copy(this._scissor).multiplyScalar(this._pixelRatio*this._resolutionScale).floor(),this.renderTarget.scissorTest=!0):this.renderTarget.scissorTest=!1,null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._pixelRatio*this._resolutionScale).floor()}setScissor(e,t,s,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new ss),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,s,i))}setViewport(e,t,s,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new ss),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,s,i))}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}xb.COLOR="color",xb.DEPTH="depth";const vb=eo(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Tb=eo(([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp()).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Sb=eo(([e,t])=>{const s=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return s.div(i).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),wb=eo(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),s=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(s)}),Mb=eo(([e,t])=>{const s=wo(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=wo(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=wb(e),(e=i.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Nb=wo(go(1.6605,-.1246,-.0182),go(-.5876,1.1329,-.1006),go(-.0728,-.0083,1.1187)),Ab=wo(go(.6274,.0691,.0164),go(.3293,.9195,.088),go(.0433,.0113,.8956)),Eb=eo(([e])=>{const t=go(e).toVar(),s=go(t.mul(t)).toVar(),i=go(s.mul(s)).toVar();return ao(15.5).mul(i.mul(s)).sub(bh(40.14,i.mul(t))).add(bh(31.96,i).sub(bh(6.868,s.mul(t))).add(bh(.4298,s).add(bh(.1191,t).sub(.00232))))}),Rb=eo(([e,t])=>{const s=go(e).toVar(),i=wo(go(.856627153315983,.137318972929847,.11189821299995),go(.0951212405381588,.761241990602591,.0767994186031903),go(.0482516061458583,.101439036467562,.811302368396859)),r=wo(go(1.1271005818144368,-.1413297634984383,-.14132976349843826),go(-.11060664309660323,1.157823702216272,-.11060664309660294),go(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=ao(-12.47393),a=ao(4.026069);return s.mulAssign(t),s.assign(Ab.mul(s)),s.assign(i.mul(s)),s.assign(Pl(s,1e-10)),s.assign(Qh(s)),s.assign(s.sub(n).div(a.sub(n))),s.assign($l(s,0,1)),s.assign(Eb(s)),s.assign(r.mul(s)),s.assign(Ul(Pl(go(0),s),go(2.2))),s.assign(Nb.mul(s)),s.assign($l(s,0,1)),s}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Cb=eo(([e,t])=>{const s=ao(.76),i=ao(.15);e=e.mul(t);const r=Cl(e.r,Cl(e.g,e.b)),n=Ql(r.lessThan(.08),r.sub(bh(6.25,r.mul(r))),.04);e.subAssign(n);const a=Pl(e.r,Pl(e.g,e.b));io(a.lessThan(s),()=>e);const o=yh(1,s),h=yh(1,o.mul(o).div(a.add(o.sub(s))));e.mulAssign(h.div(a));const l=yh(1,_h(1,i.mul(a.sub(h)).add(1)));return jl(e,go(h),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Pb extends sa{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=s}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}class Bb extends Pb{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const s=this.getNodeType(e);return e.getStructTypeNode(s).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return void 0===s&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,r=s.type,n=e.getCodeFromNode(this,r);""!==i&&(n.name=i);const a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}function Fb(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||Hc.z).negate()}const Lb=eo(([e,t],s)=>{const i=Fb(s);return ql(e,t,i)}),Db=eo(([e],t)=>{const s=Fb(t);return e.mul(e,s,s).negate().exp().oneMinus()});eo(([e,t],s)=>{const i=Fb(s),r=t.sub($c.y).max(0).toConst().mul(i).toConst();return e.mul(e,r,r).negate().exp().oneMinus()});const Ib=eo(([e,t])=>_o(t.toFloat().mix(Yo.rgb,e.toVec3()),Yo.a));Ya(class extends sa{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}generate(e){const{scope:t}=this,{renderer:s}=e;!0===s.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class Ob extends sa{static get type(){return"AtomicFunctionNode"}constructor(e,t,s){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}generateNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),s=t.parents,i=this.method,r=this.getNodeType(e),n=this.getInputType(e),a=this.pointerNode,o=this.valueNode,h=[];h.push(`&${a.build(e,n)}`),null!==o&&h.push(o.build(e,n));const l=`${e.getMethod(i,r)}( ${h.join(", ")} )`;if(!(!!s&&(1===s.length&&!0===s[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Iu(l,r).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}Ob.ATOMIC_LOAD="atomicLoad",Ob.ATOMIC_STORE="atomicStore",Ob.ATOMIC_ADD="atomicAdd",Ob.ATOMIC_SUB="atomicSub",Ob.ATOMIC_MAX="atomicMax",Ob.ATOMIC_MIN="atomicMin",Ob.ATOMIC_AND="atomicAnd",Ob.ATOMIC_OR="atomicOr",Ob.ATOMIC_XOR="atomicXor",Ya(Ob);class Ub extends na{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,s=null){super(),this.method=e,this.aNode=t,this.bNode=s}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,s=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(s)?0:e.getTypeLength(s))?t:s}generateNodeType(e){const t=this.method;return t===Ub.SUBGROUP_ELECT?"bool":t===Ub.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,a=this.bNode,o=[];if(s===Ub.SUBGROUP_BROADCAST||s===Ub.SUBGROUP_SHUFFLE||s===Ub.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(n.build(e,i),a.build(e,"float"===t?"int":i))}else s===Ub.SUBGROUP_SHUFFLE_XOR||s===Ub.SUBGROUP_SHUFFLE_DOWN||s===Ub.SUBGROUP_SHUFFLE_UP?o.push(n.build(e,i),a.build(e,"uint")):(null!==n&&o.push(n.build(e,r)),null!==a&&o.push(a.build(e,r)));const h=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(s,i)}${h}`,i,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}let kb;function zb(e){kb=kb||new WeakMap;let t=kb.get(e);return void 0===t&&kb.set(e,t={}),t}function Vb(e){const t=zb(e);return t.shadowMatrix||(t.shadowMatrix=uh("mat4").setGroup(oh).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix)))}function Gb(e){const t=zb(e);return t.position||(t.position=uh(new Ot).setGroup(oh).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld)))}function jb(e){const t=zb(e);return t.viewPosition||(t.viewPosition=uh(new Ot).setGroup(oh).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new Ot,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}Ub.SUBGROUP_ELECT="subgroupElect",Ub.SUBGROUP_BALLOT="subgroupBallot",Ub.SUBGROUP_ADD="subgroupAdd",Ub.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",Ub.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",Ub.SUBGROUP_MUL="subgroupMul",Ub.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",Ub.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",Ub.SUBGROUP_AND="subgroupAnd",Ub.SUBGROUP_OR="subgroupOr",Ub.SUBGROUP_XOR="subgroupXor",Ub.SUBGROUP_MIN="subgroupMin",Ub.SUBGROUP_MAX="subgroupMax",Ub.SUBGROUP_ALL="subgroupAll",Ub.SUBGROUP_ANY="subgroupAny",Ub.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",Ub.QUAD_SWAP_X="quadSwapX",Ub.QUAD_SWAP_Y="quadSwapY",Ub.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",Ub.SUBGROUP_BROADCAST="subgroupBroadcast",Ub.SUBGROUP_SHUFFLE="subgroupShuffle",Ub.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",Ub.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",Ub.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",Ub.QUAD_BROADCAST="quadBroadcast";const $b=e=>Rc.transformDirection(Gb(e).sub(function(e){const t=zb(e);return t.targetPosition||(t.targetPosition=uh(new Ot).setGroup(oh).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),Wb=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},Hb=new WeakMap,qb=[];class Xb extends sa{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Ao("vec3","totalDiffuse"),this.totalSpecularNode=Ao("vec3","totalSpecular"),this.outgoingLightNode=Ao("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;t<e.length;t++){const s=e[t];if(qb.push(s.id),qb.push(s.castShadow?1:0),!0===s.isSpotLight){const e=null!==s.map?s.map.id:-1,t=s.colorNode?s.colorNode.getCacheKey():-1;qb.push(e,t)}}const t=Dn(qb);return qb.length=0,t}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const s of t.nodes)s.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=(e=>e.sort((e,t)=>e.id-t.id))(this._lights),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(Wa(e));else{let i=null;if(null!==s&&(i=Wb(e.id,s)),null===i){const t=r.getLightNodeClass(e.constructor);if(null===t){bt(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===Hb.has(e)&&Hb.set(e,new t(e)),i=Hb.get(e)}t.push(i)}this._lightNodes=t}setupDirectLight(e,t,s){const{lightingModel:i,reflectedLight:r}=e.context;i.direct({...s,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,s){const{lightingModel:i,reflectedLight:r}=e.context;i.directRectArea({...s,lightNode:t,reflectedLight:r},e)}setupLights(e,t){for(const s of t)s.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let s=this.outgoingLightNode;const i=e.context,r=i.lightingModel,n=e.getNodeProperties(this);if(r){const{totalDiffuseNode:t,totalSpecularNode:a}=this;i.outgoingLight=s;const o=e.addStack();n.nodes=o.nodes,r.start(e);const{backdrop:h,backdropAlpha:l}=i,{directDiffuse:u,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=i.reflectedLight;let m=u.add(d);null!==h&&(m=go(null!==l?l.mix(m,h):h)),t.assign(m),a.assign(c.add(p)),s.assign(t.add(a)),r.finish(e),s=s.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,s}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class Yb extends sa{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Hn,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){Kb.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||$c)}}const Kb=Ao("vec3","shadowPositionWorld");function Qb(e,t){return t=function(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new zs),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}const Zb=new WeakMap,Jb=eo(({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=Ju(e,t.xy).setName("t_basic");return e.isArrayTexture&&(i=i.depth(s)),i.compare(t.z)}),e_=eo(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=Ju(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=vd("mapSize","vec2",s).setGroup(oh),a=vd("radius","float",s).setGroup(oh),o=uo(1).div(n),h=a.mul(o.x),l=ub(pc.xy).mul(6.28318530718);return fh(r(t.xy.add(cb(0,5,l).mul(h)),t.z),r(t.xy.add(cb(1,5,l).mul(h)),t.z),r(t.xy.add(cb(2,5,l).mul(h)),t.z),r(t.xy.add(cb(3,5,l).mul(h)),t.z),r(t.xy.add(cb(4,5,l).mul(h)),t.z)).mul(.2)}),t_=eo(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=Ju(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=vd("mapSize","vec2",s).setGroup(oh),a=uo(1).div(n),o=a.x,h=a.y,l=t.xy,u=il(l.mul(n).add(.5));return l.subAssign(u.mul(a)),fh(r(l,t.z),r(l.add(uo(o,0)),t.z),r(l.add(uo(0,h)),t.z),r(l.add(a),t.z),jl(r(l.add(uo(o.negate(),0)),t.z),r(l.add(uo(o.mul(2),0)),t.z),u.x),jl(r(l.add(uo(o.negate(),h)),t.z),r(l.add(uo(o.mul(2),h)),t.z),u.x),jl(r(l.add(uo(0,h.negate())),t.z),r(l.add(uo(0,h.mul(2))),t.z),u.y),jl(r(l.add(uo(o,h.negate())),t.z),r(l.add(uo(o,h.mul(2))),t.z),u.y),jl(jl(r(l.add(uo(o.negate(),h.negate())),t.z),r(l.add(uo(o.mul(2),h.negate())),t.z),u.x),jl(r(l.add(uo(o.negate(),h.mul(2))),t.z),r(l.add(uo(o.mul(2),h.mul(2))),t.z),u.x),u.y)).mul(1/9)}),s_=eo(({depthTexture:e,shadowCoord:t,depthLayer:s},i)=>{let r=Ju(e).sample(t.xy);e.isArrayTexture&&(r=r.depth(s)),r=r.rg;const n=r.x,a=Pl(1e-7,r.y.mul(r.y)),o=i.renderer.reversedDepthBuffer?Bl(n,t.z):Bl(t.z,n),h=ao(1).toVar();return io(o.notEqual(1),()=>{const e=t.z.sub(n);let s=a.div(a.add(e.mul(e)));s=$l(yh(s,.3).div(.65)),h.assign(Pl(o,s))}),h}),i_=new gy,r_=[],n_=eo(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=ao(0).toVar("meanVertical"),a=ao(0).toVar("squareMeanVertical"),o=e.lessThanEqual(ao(1)).select(ao(0),ao(2).div(e.sub(1))),h=e.lessThanEqual(ao(1)).select(ao(0),ao(-1));Kp({start:oo(0),end:oo(e),type:"int",condition:"<"},({i:e})=>{const l=h.add(ao(e).mul(o));let u=i.sample(fh(pc.xy,uo(0,l).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),u=u.x,n.addAssign(u),a.addAssign(u.mul(u))}),n.divAssign(e),a.divAssign(e);const l=Zh(a.sub(n.mul(n)).max(0));return uo(n,l)}),a_=eo(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=ao(0).toVar("meanHorizontal"),a=ao(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(ao(1)).select(ao(0),ao(2).div(e.sub(1))),h=e.lessThanEqual(ao(1)).select(ao(0),ao(-1));Kp({start:oo(0),end:oo(e),type:"int",condition:"<"},({i:e})=>{const l=h.add(ao(e).mul(o));let u=i.sample(fh(pc.xy,uo(l,0).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),n.addAssign(u.x),a.addAssign(fh(u.y.mul(u.y),u.x.mul(u.x)))}),n.divAssign(e),a.divAssign(e);const l=Zh(a.sub(n.mul(n)).max(0));return uo(n,l)}),o_=[Jb,e_,t_,s_];let h_;const l_=new lb;class u_ extends Yb{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r,depthLayer:n}){const a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),o=t({depthTexture:s,shadowCoord:i,shadow:r,depthLayer:n});return a.select(o,ao(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=s.biasNode||vd("bias","float",s).setGroup(oh);let n,a=t;if(s.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z;else{const e=a.w;a=a.xy.div(e);const t=vd("near","float",s.camera).setGroup(oh),i=vd("far","float",s.camera).setGroup(oh);n=_m(e.negate(),t,i)}return a=go(a.x,a.y.oneMinus(),i.reversedDepthBuffer?n.sub(r):n.add(r)),a}getShadowFilterFn(e){return o_[e]}setupRenderTarget(e,t){const s=new Fr(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=t.renderer.reversedDepthBuffer?rt:tt;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=s,{shadowMap:i,depthTexture:s}}setupShadow(e){const{renderer:t,camera:s}=e,{light:i,shadow:r}=this,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(r,e),o=t.shadowMap.type,h=t.hasCompatibility(dt);if(1!==o&&2!==o||!h?(n.minFilter=O,n.magFilter=O):(n.minFilter=z,n.magFilter=z),r.camera.coordinateSystem=s.coordinateSystem,r.camera.updateProjectionMatrix(),3===o&&!0!==r.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:le,type:K,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:le,type:K,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:le,type:K,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:le,type:K,depthBuffer:!1}));let t=Ju(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let s=Ju(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(s=s.depth(this.depthLayer));const i=vd("blurSamples","float",r).setGroup(oh),o=vd("radius","float",r).setGroup(oh),h=vd("mapSize","vec2",r).setGroup(oh);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Em);l.fragmentNode=n_({samples:i,radius:o,size:h,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Em),l.fragmentNode=a_({samples:i,radius:o,size:h,shadowPass:s,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const l=vd("intensity","float",r).setGroup(oh),u=vd("normalBias","float",r).setGroup(oh),c=Vb(i),d=id.mul(u);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=c.mul(Kb.add(d));else{p=uh("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(c.value,e.matrixWorld)).mul(Gc).add(c.mul(_o(d,0)))}const m=this.setupShadowCoord(e,p),g=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===g)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=3===o&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,y=this.setupShadowFilter(e,{filterFn:g,shadowTexture:a.texture,depthTexture:f,shadowCoord:m,shadow:r,depthLayer:this.depthLayer});let b,_;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?b=bd(a.texture,m.xyz):(b=Ju(a.texture,m),n.isArrayTexture&&(b=b.depth(this.depthLayer)))),_=b?jl(1,y.rgb.mix(b,1),l.mul(b.a)).toVar():jl(1,y,l).toVar(),this.shadowMap=a,this.shadow.map=a;const x=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return b&&_.toInspector(`${x} / Color`,()=>this.shadowMap.texture.isCubeTexture?bd(this.shadowMap.texture):Ju(this.shadowMap.texture)),_.toInspector(`${x} / Depth`,()=>this.shadowMap.texture.isCubeTexture?bd(this.shadowMap.texture).r.oneMinus():ec(this.shadowMap.depthTexture,$u().mul(Hu(Ju(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return eo(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let s=this._node;return this.setupShadowPosition(e),null===s&&(this._node=s=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(s=e.material.receivedShadowNode(s)),s})()}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:r,scene:n}=e;t.updateMatrices(i),s.setSize(t.mapSize.width,t.mapSize.height,s.depth);const a=n.name;n.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,r.render(n,t.camera),n.name=a}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:r,scene:n,camera:a}=e,o=r.shadowMap.type,h=t.depthTexture.version;this._depthVersionCached=h;const l=i.camera.layers.mask;4294967294&i.camera.layers.mask||(i.camera.layers.mask=a.layers.mask);const u=r.getRenderObjectFunction(),c=r.getMRT(),d=!!c&&c.has("velocity");h_=function(e,t,s){return s=function(e,t){return t=function(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}(t,s=Qb(e,s)),s}(r,n,h_),n.overrideMaterial=(e=>{let t=Zb.get(e);return void 0===t&&(t=new Em,t.colorNode=_o(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=0,t.fog=!1,Zb.set(e,t)),t})(s),r.setRenderObjectFunction(((e,t,s,i)=>{r_[0]=e,r_[1]=t;let r=i_.get(r_);return void 0!==r&&r.shadowType===s&&r.useVelocity===i||(r=(r,n,a,o,h,l,...u)=>{(!0===r.castShadow||r.receiveShadow&&3===s)&&(i&&(Gn(r).useVelocity=!0),r.onBeforeShadow(e,r,a,t.camera,o,n.overrideMaterial,l),e.renderObject(r,n,a,o,h,l,...u),r.onAfterShadow(e,r,a,t.camera,o,n.overrideMaterial,l))},r.shadowType=s,r.useVelocity=i,i_.set(r_,r)),r_[0]=null,r_[1]=null,r})(r,i,o,d)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(u),3===o&&!0!==i.isPointLightShadow&&this.vsmPass(r),i.camera.layers.mask=l,function(e,t,s){!function(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}(e,s),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,s)}(r,n,h_)}vsmPass(e){const{shadow:t}=this,s=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,s),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,s),e.setRenderTarget(this.vsmShadowMapVertical),l_.material=this.vsmMaterialVertical,l_.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),l_.material=this.vsmMaterialHorizontal,l_.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,(e=>{const t=Zb.get(e);void 0!==t&&(t.dispose(),Zb.delete(e))})(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let s=t.needsUpdate||t.autoUpdate;s&&(this._cameraFrameId[e.camera]===e.frameId&&(s=!1),this._cameraFrameId[e.camera]=e.frameId),s&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const c_=new zs,d_=new ns,p_=new Ot,m_=new Ot,g_=[new Ot(1,0,0),new Ot(-1,0,0),new Ot(0,-1,0),new Ot(0,1,0),new Ot(0,0,1),new Ot(0,0,-1)],f_=[new Ot(0,-1,0),new Ot(0,-1,0),new Ot(0,0,-1),new Ot(0,0,1),new Ot(0,-1,0),new Ot(0,-1,0)],y_=[new Ot(1,0,0),new Ot(-1,0,0),new Ot(0,1,0),new Ot(0,-1,0),new Ot(0,0,1),new Ot(0,0,-1)],b_=[new Ot(0,-1,0),new Ot(0,-1,0),new Ot(0,0,1),new Ot(0,0,-1),new Ot(0,-1,0),new Ot(0,-1,0)],__=eo(({depthTexture:e,bd3D:t,dp:s})=>bd(e,t).compare(s)),x_=eo(({depthTexture:e,bd3D:t,dp:s,shadow:i})=>{const r=vd("radius","float",i).setGroup(oh),n=vd("mapSize","vec2",i).setGroup(oh),a=r.div(n.x),o=fl(t),h=sl(Ol(t,o.x.greaterThan(o.z).select(go(0,1,0),go(1,0,0)))),l=Ol(t,h),u=ub(pc.xy).mul(6.28318530718),c=cb(0,5,u),d=cb(1,5,u),p=cb(2,5,u),m=cb(3,5,u),g=cb(4,5,u);return bd(e,t.add(h.mul(c.x).add(l.mul(c.y)).mul(a))).compare(s).add(bd(e,t.add(h.mul(d.x).add(l.mul(d.y)).mul(a))).compare(s)).add(bd(e,t.add(h.mul(p.x).add(l.mul(p.y)).mul(a))).compare(s)).add(bd(e,t.add(h.mul(m.x).add(l.mul(m.y)).mul(a))).compare(s)).add(bd(e,t.add(h.mul(g.x).add(l.mul(g.y)).mul(a))).compare(s)).mul(.2)}),v_=eo(({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i},r)=>{const n=s.xyz.toConst(),a=n.abs().toConst(),o=a.x.max(a.y).max(a.z),h=uh("float").setGroup(oh).onRenderUpdate(()=>i.camera.near),l=uh("float").setGroup(oh).onRenderUpdate(()=>i.camera.far),u=vd("bias","float",i).setGroup(oh),c=ao(1).toVar();return io(o.sub(l).lessThanEqual(0).and(o.sub(h).greaterThanEqual(0)),()=>{let s;r.renderer.reversedDepthBuffer?(s=((e,t,s)=>t.mul(e.add(s)).div(e.mul(t.sub(s))))(o.negate(),h,l),s.subAssign(u)):(s=ym(o.negate(),h,l),s.addAssign(u));const a=n.normalize();c.assign(e({depthTexture:t,bd3D:a,dp:s,shadow:i}))}),c});class T_ extends u_{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?__:x_}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r}){return v_({filterFn:t,depthTexture:s,shadowCoord:i,shadow:r})}setupRenderTarget(e,t){const s=new Lr(e.mapSize.width);s.name="PointShadowDepthTexture",s.compareFunction=t.renderer.reversedDepthBuffer?rt:tt;const i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=s,{shadowMap:i,depthTexture:s}}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:r,scene:n}=e,a=t.camera,o=t.matrix,h=r.coordinateSystem===lt,l=h?g_:y_,u=h?f_:b_;s.setSize(t.mapSize.width,t.mapSize.width);const c=r.autoClear,d=r.getClearColor(c_),p=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){r.setRenderTarget(s,e),r.clear();const h=i.distance||a.far;h!==a.far&&(a.far=h,a.updateProjectionMatrix()),p_.setFromMatrixPosition(i.matrixWorld),a.position.copy(p_),m_.copy(a.position),m_.add(l[e]),a.up.copy(u[e]),a.lookAt(m_),a.updateMatrixWorld(),o.makeTranslation(-p_.x,-p_.y,-p_.z),d_.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(d_,a.coordinateSystem,a.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${e+1}`,r.render(n,a),n.name=c}r.autoClear=c,r.setClearColor(d,p)}}class S_ extends sm{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new zs,this.colorNode=e&&e.colorNode||uh(this.color).setGroup(oh),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Wn,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,null!==this.baseColorNode&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return jb(this.light).sub(e.context.positionView||Hc)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>new u_(e,t))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let s=this.shadowColorNode;if(null===s){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?Wa(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=s=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(s=e.context.getShadow(this,e)),this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),s=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),s&&e.lightsNode.setupDirectRectAreaLight(e,this,s)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const w_=eo(({lightDistance:e,cutoffDistance:t,decayExponent:s})=>{const i=e.pow(s).max(.01).reciprocal();return t.greaterThan(0).select(i.mul(e.div(t).pow4().oneMinus().clamp().pow2()),i)});class M_ extends S_{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=uh(0).setGroup(oh),this.decayExponentNode=uh(2).setGroup(oh)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>new T_(e,t))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:s,decayExponent:i})=>{const r=t.normalize(),n=t.length(),a=w_({lightDistance:n,cutoffDistance:s,decayExponent:i});return{lightDirection:r,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}eo(([e=$u()],{renderer:t,material:s})=>{const i=Gl(e.mul(2).sub(1));let r;if(s.alphaToCoverage&&t.currentSamples>0){const e=ao(i.fwidth()).toVar();r=ql(e.oneMinus(),e.add(1),i).oneMinus()}else r=Ql(i.greaterThan(1),0,1);return r});const N_=eo(([e,t])=>{const s=e.x,i=e.y,r=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(i)),n=n.add(t.element(2).mul(1.023328).mul(r)),n=n.add(t.element(3).mul(1.023328).mul(s)),n=n.add(t.element(4).mul(.858086).mul(s).mul(i)),n=n.add(t.element(5).mul(.858086).mul(i).mul(r)),n=n.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(s).mul(r)),n=n.add(t.element(8).mul(.429043).mul(bh(s,s).sub(bh(i,i)))),n}),A_=new Qy;class E_ extends xy{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===r)i._clearColor.getRGB(A_),A_.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(A_),A_.a=1,n=!0;else if(!0===r.isNode){const o=this.get(e),h=r;A_.copy(i._clearColor);let l=o.backgroundMesh;if(void 0===l){const c=_o(h).mul(gb).context({getUV:()=>fb.mul(td),getTextureLevel:()=>mb}),d=Ac.element(3).element(3).equal(1),p=_h(1,Ac.element(1).element(1)).mul(3),m=d.select(Gc.mul(p),Gc),g=Ic.mul(_o(m,0));let f=Ac.mul(_o(g.xyz,1));f=f.setZ(f.w);const y=new Em;function b(){r.removeEventListener("dispose",b),l.material.dispose(),l.geometry.dispose()}y.name="Background.material",y.side=1,y.depthTest=!1,y.depthWrite=!1,y.allowOverride=!1,y.fog=!1,y.lights=!1,y.vertexNode=f,y.colorNode=c,o.backgroundMeshNode=c,o.backgroundMesh=l=new mr(new Ur(1,32,32),y),l.frustumCulled=!1,l.name="Background.mesh",r.addEventListener("dispose",b)}const u=h.getCacheKey();o.backgroundCacheKey!==u&&(o.backgroundMeshNode.node=_o(h).mul(gb),o.backgroundMeshNode.needsUpdate=!0,l.material.needsUpdate=!0,o.backgroundCacheKey=u),t.unshift(l,l.geometry,l.material,0,0,null,null)}else _t("Renderer: Unsupported background configuration.",r);const a=i.xr.getEnvironmentBlendMode();if("additive"===a?A_.set(0,0,0,1):"alpha-blend"===a&&A_.set(0,0,0,0),!0===i.autoClear||!0===n){const _=s.clearColorValue;_.r=A_.r,_.g=A_.g,_.b=A_.b,_.a=A_.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(_.r*=_.a,_.g*=_.a,_.b*=_.a),s.depthClearValue=i.getClearDepth(),s.stencilClearValue=i.getClearStencil(),s.clearColor=!0===i.autoClearColor,s.clearDepth=!0===i.autoClearDepth,s.clearStencil=!0===i.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}let R_=0;class C_{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=R_++}}class P_{constructor(e,t,s,i,r,n,a,o,h,l=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=l,this.nodeAttributes=i,this.bindings=r,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=h,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new C_(t.name,[]);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}class B_{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class F_{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class L_{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class D_ extends L_{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class I_{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let O_=0;class U_{constructor(e=null){this.id=O_++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class k_{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class z_{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class V_ extends z_{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class G_ extends z_{constructor(e,t=new Dt){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class j_ extends z_{constructor(e,t=new Ot){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class $_ extends z_{constructor(e,t=new ss){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class W_ extends z_{constructor(e,t=new zs){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class H_ extends z_{constructor(e,t=new wn){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class q_ extends z_{constructor(e,t=new zt){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class X_ extends z_{constructor(e,t=new ns){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Y_ extends V_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class K_ extends G_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Q_ extends j_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Z_ extends $_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class J_ extends W_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ex extends H_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class tx extends q_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class sx extends X_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let ix=0;const rx=new WeakMap,nx=new WeakMap,ax=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),ox=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class hx{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=eb(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new U_,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:ix++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}createRenderTarget(e,t,s){return new is(e,t,s)}createCubeRenderTarget(e,t){return new Im(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=t[0].groupNode;let i,r=s.shared;if(r)for(let e=1;e<t.length;e++)s!==t[e].groupNode&&(r=!1);if(r){let s="";for(const e of t)if(e.isNodeUniformsGroup){e.uniforms.sort((e,t)=>e.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)s+=t.nodeUniform.node.id}else s+=e.nodeUniform.id;const r=this.renderer._currentRenderContext||this.renderer;let n=rx.get(r);void 0===n&&(n=new Map,rx.set(r,n));const a=Ln(s);i=n.get(a),void 0===i&&(i=new C_(e,t),n.set(a,i))}else i=new C_(e,t);return i}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},s=this.bindings;for(const e of Zn)for(const i in s[e]){const r=s[e][i],n=t[i]||(t[i]=[]);for(const e of r)!1===n.includes(e)&&n.push(e)}e=[];for(const s in t){const i=t[s],r=this._getBindGroup(s,i);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const s=e[t];this.bindingsIndexes[s.name].group=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t===$n&&s===$n||!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==$n&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==$n&&this.updateBeforeNodes.push(e),s!==$n&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===z||e.magFilter===V||e.magFilter===k||e.magFilter===G||e.minFilter===z||e.minFilter===V||e.minFilter===k||e.minFilter===G}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const s=this.getDataFromNode(e);return void 0===s.cache&&(s.cache=new U_(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){bt("Abstract function.")}getInstanceIndex(){bt("Abstract function.")}getDrawIndex(){bt("Abstract function.")}getFrontFacing(){bt("Abstract function.")}getFragCoord(){bt("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,t.usageCount}generateTexture(){bt("Abstract function.")}generateTextureLod(){bt("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,s=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let r=0;r<t;r++){const n=s?s[r]:null;i+=null!==n?n.build(this,e):this.generateConst(e),r<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,s=null){const i=[];for(const e of t){const{name:t,type:r}=e;s&&s[t]&&s[t].isNode?i.push(s[t].build(this,r)):i.push(this.generateConst(r))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new zs:"vec2"===e||"uvec2"===e||"ivec2"===e?t=new Dt:"vec3"===e||"uvec3"===e||"ivec3"===e?t=new Ot:"vec4"!==e&&"uvec4"!==e&&"ivec4"!==e||(t=new ss)),"float"===e)return ox(t);if("int"===e)return`${Math.round(t)}`;if("uint"===e)return t>=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${ox(t.r)}, ${ox(t.g)}, ${ox(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===s&&"mat2"!==e)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(s>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const s=this.attributes;for(const t of s)if(t.name===e)return t;const i=new B_(e,t);return this.registerDeclaration(i),s.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===q)return"int";if(t===X)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let s=kn(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return ax.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,r=e.normalized;let n;return e instanceof Ei||!0===r||(n=this.getTypeFromArray(s)),this.getTypeFromLength(i,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=eb(this.stack);const e=so();return this.stacks.push(e),to(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){this.getDataFromNode(t).stack=e}return this.stack=e.parent,to(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){let i=(s=null===s?e.isGlobal(this)?this.globalCache:this.cache:s).getData(e);void 0===i&&(i={},s.setData(e,i)),void 0===i[t]&&(i[t]={});let r=i[t];const n=i.any?i.any.subBuilds:null,a=this.getClosestSubBuild(n);return a&&(void 0===r.subBuildsCache&&(r.subBuildsCache={}),r=r.subBuildsCache[a]||(r.subBuildsCache[a]={}),r.subBuilds=n),r}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e,"vertex");let i=s.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new B_("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,s=null,i=this.shaderStage){const r=this.getDataFromNode(e,i,this.globalCache);let n=r.structType;if(void 0===n){const a=this.structs.index++;null===s&&(s="StructType"+a),n=new k_(s,t),this.structs[i].push(n),this.types[i][s]=e,r.structType=n}return n}getOutputStructTypeFromNode(e,t){const s=this.getStructTypeFromNode(e,t,"OutputType","fragment");return s.output=!0,s}getUniformFromNode(e,t,s=this.shaderStage,i=null){const r=this.getDataFromNode(e,s,this.globalCache);let n=r.uniform;if(void 0===n){const a=this.uniforms.index++;n=new F_(i||"nodeUniform"+a,t,e),this.uniforms[s].push(n),this.registerDeclaration(n),r.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage,r=!1){const n=this.getDataFromNode(e,i),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){const h=r?"_const":"_var",l=this.vars[i]||(this.vars[i]=[]),u=this.vars[h]||(this.vars[h]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+u,this.vars[h]++),"variable"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new L_(t,s,r,c),r||l.push(o),this.registerDeclaration(o),n[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,s=e.getNodeType(this),i=null,r=null){const n=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,h=e.length;null===t&&(t="nodeVarying"+h),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new D_(t,s,i,r),e.push(o),this.registerDeclaration(o),n[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,s=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let r=1,n=i;for(;void 0!==s[n];)n=i+"_"+r++;r>1&&(e.name=n,bt(`TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${n}'.`)),s[n]=e}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[s]||(this.codes[s]=[]),n=e.length;r=new I_("nodeCode"+n,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,n=t;for(;n;){if(!0===i.get(n)){r=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(r)for(const e of s)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),n=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),n.set(s,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new Bb,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout,s={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)s[e.name]=new Zy(e.type,e.name);e.layout=null;const i=e.call(s),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowBuildStage(e,t,s=null){const i=this.getBuildStage();this.setBuildStage(t);const r=e.build(this,s);return this.setBuildStage(i),r}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,r=this.declarations,n=this.cache,a=this.buildStage,o=this.stack,h={code:""};this.flow=h,this.vars={},this.declarations={},this.cache=new U_,this.stack=eb();for(const s of Qn)this.setBuildStage(s),h.result=e.build(this,t);return h.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.declarations=r,this.cache=n,this.stack=o,this.setBuildStage(a),h}getFunctionOperator(){return null}buildFunctionCode(){bt("Abstract function.")}flowChildNode(e,t=null){const s=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=s,i}flowNodeFromShaderStage(e,t,s=null,i=null){const r=this.tab,n=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const h={...this.context};delete h.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=h;let l=null;if("generate"===this.buildStage){const r=this.flowChildNode(t,s);null!==i&&(r.code+=`${this.tab+i} = ${r.result};\n`),this.flowCode[e]=this.flowCode[e]+r.code,l=r}else l=t.build(this);return this.setShaderStage(a),this.cache=n,this.tab=r,this.context=o,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){bt("Abstract function.")}getVaryings(){bt("Abstract function.")}getVar(e,t,s=null){return`${null!==s?this.generateArrayDeclaration(e,s):this.getType(e)} ${t}`}getVars(e,t=!1){const s=[],i=this.vars[e];if(void 0!==i)for(const e of i)s.push(`${this.getVar(e.type,e.name,e.count)};`);return s.join(t?"\n":"\n\t")}getUniforms(){bt("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(void 0!==t)for(const e of t)s+=e.code+"\n";return s}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){bt("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,"any").subBuilds:e instanceof Set?[...e]:e,!t)return null;const s=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const i=t[e];if(s.includes(i))return i}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let s,i;return s=null!==t?this.getClosestSubBuild(t):this.subBuildFn,i=s?e?s+"_"+e:s:e,i}prebuild(){const{object:e,renderer:t,material:s}=this;if(!0===t.contextNode.isContextNode?this.context={...this.context,...t.contextNode.getFlowContextData()}:_t('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),s&&s.contextNode&&(!0===s.contextNode.isContextNode?this.context={...this.context,...s.contextNode.getFlowContextData()}:_t('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),null!==s){let e=t.library.fromMaterial(s);null===e&&(_t(`NodeBuilder: Material "${s.type}" is not compatible.`),e=new Em),e.build(this)}else this.addFlow("compute",e)}build(){this.prebuild();for(const e of Qn){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Zn){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(){this.prebuild();for(const e of Qn){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Zn){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"generate"===e?this.flowNode(t):t.build(this);await vt()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=nx.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const s=this.getSharedDataFromNode(e);let i=s.cache;if(void 0===i){if("float"===t||"int"===t||"uint"===t)i=new Y_(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)i=new K_(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)i=new Q_(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)i=new Z_(e);else if("color"===t)i=new J_(e);else if("mat2"===t)i=new ex(e);else if("mat3"===t)i=new tx(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);i=new sx(e)}s.cache=i}return i}format(e,t,s){if((t=this.getVectorType(t))===(s=this.getVectorType(s))||null===s||this.isReference(s))return e;const i=this.getTypeLength(t),r=this.getTypeLength(s);return 16===i&&9===r?`${this.getType(s)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===i&&4===r?`${this.getType(s)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||r>4||0===r?e:i===r?`${this.getType(s)}( ${e} )`:i>r?(e="bool"===s?`all( ${e} )`:`${e}.${"xyz".slice(0,r)}`,this.format(e,this.getTypeFromLength(r,this.getComponentType(t)),s)):4===r&&i>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(s)&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${a} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||!0===Gn(this.object).useVelocity}}class lx{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let s=e.get(t);return void 0===s&&(s={renderId:0,frameId:0},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===Wn){const t=this._getMaps(this.updateBeforeMap,s);if(t.frameId!==this.frameId){const s=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=s)}}else if(t===Hn){const t=this._getMaps(this.updateBeforeMap,s);if(t.renderId!==this.renderId){const s=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=s)}}else t===qn&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===Wn){const t=this._getMaps(this.updateAfterMap,s);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===Hn){const t=this._getMaps(this.updateAfterMap,s);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===qn&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===Wn){const t=this._getMaps(this.updateMap,s);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===Hn){const t=this._getMaps(this.updateMap,s);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===qn&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class ux{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}ux.isNodeFunctionInput=!0;class cx extends S_{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class dx extends S_{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:$b(this.light),lightColor:e}}}class px extends S_{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Gb(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=uh(new zs).setGroup(oh)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:s,lightDirectionNode:i}=this,r=id.dot(i).mul(.5).add(.5),n=jl(s,t,r);e.context.irradiance.addAssign(n)}}class mx extends S_{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=uh(0).setGroup(oh),this.penumbraCosNode=uh(0).setGroup(oh),this.cutoffDistanceNode=uh(0).setGroup(oh),this.decayExponentNode=uh(0).setGroup(oh),this.colorNode=uh(this.color).setGroup(oh)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:s,penumbraCosNode:i}=this;return ql(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return void 0===s&&(s=function(e,t=$c){const s=Vb(e).mul(t);return s.xyz.div(s.w)}(this.light,e.context.positionWorld),t.projectionUV=s),s}setupDirect(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:r}=this,n=this.getLightVector(e),a=n.normalize(),o=a.dot($b(r)),h=this.getSpotAttenuation(e,o),l=n.length(),u=w_({lightDistance:l,cutoffDistance:s,decayExponent:i});let c,d,p=t.mul(h).mul(u);if(r.colorNode?(d=this.getLightCoord(e),c=r.colorNode(d)):r.map&&(d=this.getLightCoord(e),c=Ju(r.map,d.xy).onRenderUpdate(()=>r.map)),c){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:a}}}class gx extends mx{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const s=this.light.iesMap;let i=null;if(s&&!0===s.isTexture){const e=t.acos().mul(1/Math.PI);i=Ju(s,uo(e,0),0).r}else i=super.getSpotAttenuation(t);return i}}class fx extends S_{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new Ot);this.lightProbe=nc(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=N_(id,this.lightProbe);e.context.irradiance.addAssign(t)}}const yx=eo(([e,t])=>{const s=e.abs().sub(t);return bl(Pl(s,0)).add(Cl(Pl(s.x,s.y),0))});class bx extends mx{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),null===t.aspect){let e=1;null!==t.map&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=ao(0),s=this.penumbraCosNode,i=Vb(this.light).mul(e.context.positionWorld||$c);return io(i.w.greaterThan(0),()=>{const e=i.xyz.div(i.w),r=yx(e.xy.sub(uo(.5)),uo(.5)),n=_h(-1,yh(1,dl(s)).sub(1));t.assign(Wl(r.mul(-2).mul(n)))}),t}}const _x=new ns,xx=new ns;let vx=null;class Tx extends S_{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=uh(new Ot).setGroup(oh),this.halfWidth=uh(new Ot).setGroup(oh),this.updateType=Hn}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;xx.identity(),_x.copy(t.matrixWorld),_x.premultiply(s),xx.extractRotation(_x),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(xx),this.halfHeight.value.applyMatrix4(xx)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=Ju(vx.LTC_FLOAT_1),s=Ju(vx.LTC_FLOAT_2)):(t=Ju(vx.LTC_HALF_1),s=Ju(vx.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:jb(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){vx=e}}class Sx{parseFunction(){bt("Abstract function.")}}class wx{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){bt("Abstract function.")}}wx.isNodeFunction=!0;const Mx=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,Nx=/[a-z_0-9]+/gi,Ax="#pragma main";class Ex extends wx{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(Ax),s=-1!==t?e.slice(t+12):e,i=s.match(Mx);if(null!==i&&5===i.length){const r=i[4],n=[];let a=null;for(;null!==(a=Nx.exec(r));)n.push(a);const o=[];let h=0;for(;h<n.length;){const e="const"===n[h][0];!0===e&&h++;let t=n[h][0];"in"===t||"out"===t||"inout"===t?h++:t="";const s=n[h++][0];let i=Number.parseInt(n[h][0]);!1===Number.isNaN(i)?h++:i=null;const r=n[h++][0];o.push(new ux(s,r,i,t,e))}const l=s.substring(i[0].length),u=void 0!==i[3]?i[3]:"";return{type:i[2],inputs:o,name:u,precision:void 0!==i[1]?i[1]:"",inputsCode:r,blockCode:l,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("FunctionNode: Function is not a GLSL code.")})(e);super(t,s,i,r),this.inputsCode=n,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const s=this.blockCode;if(""!==s){const{type:i,inputsCode:r,headerCode:n,precision:a}=this;let o=`${i} ${e} ( ${r.trim()} )`;""!==a&&(o=`${a} ${o}`),t=n+o+s}else t="";return t}}class Rx extends Sx{parseFunction(e){return new Ex(e)}}const Cx=[],Px=[];class Bx extends xy{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new lx,this.nodeBuilderCache=new Map,this.callHashCache=new gy,this.groupsData=new gy,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){const t=e.groupNode;Cx[0]=t,Cx[1]=e;let s=this.groupsData.get(Cx);return void 0===s&&this.groupsData.set(Cx,s={}),Cx[0]=null,Cx[1]=null,s.version!==t.version&&(s.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,t){const s=this.backend.createNodeBuilder(e.object,this.renderer);return s.scene=e.scene,s.material=t,s.camera=e.camera,s.context.material=t,s.lightsNode=e.lightsNode,s.environmentNode=this.getEnvironmentNode(e.scene),s.fogNode=this.getFogNode(e.scene),s.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&s.enableMultiview(),s}getForRender(e,t=!1){const s=this.get(e);let i=s.nodeBuilderState;if(void 0===i){const{nodeBuilderCache:r}=this,n=this.getForRenderCacheKey(e);if(i=r.get(n),void 0===i){const a=async()=>{let s=this._createNodeBuilder(e,e.material);try{t?await s.buildAsync():s.build()}catch(i){s=this._createNodeBuilder(e,new Em),t?await s.buildAsync():s.build(),_t("TSL: "+i)}return s};if(t)return a().then(e=>(i=this._createNodeBuilderState(e),r.set(n,i),i.usedTimes++,s.nodeBuilderState=i,i));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(s){t=this._createNodeBuilder(e,new Em),t.build();let i=s.stackTrace;!i&&s.stack&&(i=new Bn(s.stack)),_t("TSL: "+s,i)}i=this._createNodeBuilderState(t),r.set(n,i)}}i.usedTimes++,s.nodeBuilderState=i}return i}getForRenderAsync(e){const t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){const t=this.get(e);if(void 0!==t.nodeBuilderState)return t.nodeBuilderState;const s=this.getForRenderCacheKey(e),i=this.nodeBuilderCache.get(s);return void 0!==i?(i.usedTimes++,t.nodeBuilderState=i,i):(!0!==t.pendingBuild&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||0===this._buildQueue.length)return;this._buildInProgress=!0;this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;void 0!==t&&(t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),s=this._createNodeBuilderState(i),t.nodeBuilderState=s}return s}_createNodeBuilderState(e){return new P_(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const s=this.get(e);s.environmentNode&&(t=s.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const s=this.get(e);s.backgroundNode&&(t=s.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){Cx[0]=e,Cx[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(Cx)||{};if(i.callId!==s){const r=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&Px.push(t.getCacheKey(!0)),r&&Px.push(r.getCacheKey()),n&&Px.push(n.getCacheKey()),Px.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),Px.push(this.renderer.shadowMap.enabled?1:0),Px.push(this.renderer.shadowMap.type),i.callId=s,i.cacheKey=Dn(Px),this.callHashCache.set(Cx,i),Px.length=0}return Cx[0]=null,Cx[1]=null,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),s=e.background;if(s){const i=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==s||i){const r=this.getCacheNode("background",s,()=>{if(!0===s.isCubeTexture||303===s.mapping||304===s.mapping||306===s.mapping){if(e.backgroundBlurriness>0||306===s.mapping)return Vf(s);{let e;return e=!0===s.isCubeTexture?bd(s):Ju(s),Vm(e)}}if(!0===s.isTexture)return Ju(s,cc.flipY()).setUpdateMatrix(!0);!0!==s.isColor&&_t("WebGPUNodes: Unsupported background configuration.",s)},i);t.backgroundNode=r,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,s,i=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=r.get(t);return(void 0===n||i)&&(n=s(),r.set(t,n)),n}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){const e=this.getCacheNode("fog",s,()=>{if(s.isFogExp2){const e=vd("color","color",s).setGroup(oh),t=vd("density","float",s).setGroup(oh);return Ib(e,Db(t))}if(s.isFog){const e=vd("color","color",s).setGroup(oh),t=vd("near","float",s).setGroup(oh),i=vd("far","float",s).setGroup(oh);return Ib(e,Lb(t,i))}_t("Renderer: Unsupported fog configuration.",s)});t.fogNode=e,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){const e=this.getCacheNode("environment",s,()=>!0===s.isCubeTexture?bd(s):!0===s.isTexture?Ju(s):void _t("Nodes: Unsupported environment configuration.",s));t.environmentNode=e,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,r=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=s,n.camera=i,n.material=r,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;return e.isArrayTexture?Ju(e,cc).depth(ac("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):Ju(e,cc).renderOutput(t.toneMapping,t.currentColorSpace)}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const e of s.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new lx,this.nodeBuilderCache=new Map,this.cacheLib={}}}const Fx=new vr;class Lx{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new zt,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,s){const i=e.length;for(let r=0;r<i;r++){Fx.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=Fx.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=Fx.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let s=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,r=i.length;let n,a;if(this.clipIntersection?(n=this.intersectionPlanes,a=e.intersectionPlanes.length):(n=this.unionPlanes,a=e.unionPlanes.length),n.length!==a+r){n.length=a+r;for(let e=0;e<r;e++)n[a+e]=new ss;s=!0}this.projectPlanes(i,n,a),s&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return void 0===t&&(t=new Lx(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class Dx{constructor(e,t,s){this.bundleGroup=e,this.camera=t,this.renderContext=s}}const Ix=[];class Ox{constructor(){this.bundles=new gy}get(e,t,s){const i=this.bundles;Ix[0]=e,Ix[1]=t,Ix[2]=s;let r=i.get(Ix);return void 0===r&&(r=new Dx(e,t,s),i.set(Ix,r)),Ix[0]=null,Ix[1]=null,Ix[2]=null,r}dispose(){this.bundles=new gy}}class Ux{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(null!==s){t=new s;for(const s in e)t[s]=e[s]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t))bt(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}}addClass(e,t,s){if(s.has(t))bt(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}}const kx=new Xb,zx=new WeakMap;class Vx{createNode(e=[]){return(new Xb).setLights(e)}getNode(e){if(e.isQuadMesh)return kx;let t=zx.get(e);return void 0===t&&(t=this.createNode(),zx.set(e,t)),t}}class Gx extends is{constructor(e=1,t=1,s={}){super(e,t,s),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const jx=new Ot,$x=new Ot,Wx=new WeakMap;class Hx extends St{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new hn,this._cameraL.viewport=new ss,this._cameraR=new hn,this._cameraR.viewport=new ss,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Tn,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._createXRLayer=Qx.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new Dt,this._onSessionEvent=Xx.bind(this),this._onSessionEnd=Yx.bind(this),this._onInputSourcesChange=Kx.bind(this),this._onAnimationFrame=Zx.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(null!==this._glProjLayer||null!==this._glBaseLayer)return this._foveation}setFoveation(e){this._foveation=e,null!==this._glProjLayer&&(this._glProjLayer.fixedFoveation=e),null!==this._glBaseLayer&&void 0!==this._glBaseLayer.fixedFoveation&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,!0===this.isPresenting&&bt("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&bt("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(null!==this._session)return this._session.environmentBlendMode}getBinding(){return null===this._glBinding&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,s,i,r,n,a,o={}){const h=new Or(e,t),l=new Gx(r,n,{format:re,type:j,depthTexture:new Fr(r,n,o.stencil?J:X,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?ae:ne),stencilBuffer:o.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});l._autoAllocateDepthBuffer=!0;const c=new sr({color:16777215,side:0});c.map=l.texture,c.map.offset.y=1,c.map.repeat.y=-1;const d=new mr(h,c);d.position.copy(s),d.quaternion.copy(i);const m={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:r,pixelheight:n,plane:d,material:c,rendercall:a,renderTarget:l};if(this._layers.push(m),null!==this._session){m.plane.material=new sr({color:16777215,side:0}),m.plane.material.blending=5,m.plane.material.blendEquation=u,m.plane.material.blendSrc=p,m.plane.material.blendDst=p,m.xrlayer=this._createXRLayer(m);const e=this._session.renderState.layers;e.unshift(m.xrlayer),this._session.updateRenderState({layers:e})}else l.isXRRenderTarget=!1;return d}createCylinderLayer(e,t,s,i,r,n,a,o,h={}){const l=new Ir(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),c=new Gx(n,a,{format:re,type:j,depthTexture:new Fr(n,a,h.stencil?J:X,void 0,void 0,void 0,void 0,void 0,void 0,h.stencil?ae:ne),stencilBuffer:h.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});c._autoAllocateDepthBuffer=!0;const d=new sr({color:16777215,side:1});d.map=c.texture,d.map.offset.y=1,d.map.repeat.y=-1;const m=new mr(l,d);m.position.copy(i),m.quaternion.copy(r);const g={type:"cylinder",radius:e,centralAngle:t,aspectratio:s,translation:i,quaternion:r,pixelwidth:n,pixelheight:a,plane:m,material:d,rendercall:o,renderTarget:c};if(this._layers.push(g),null!==this._session){g.plane.material=new sr({color:16777215,side:1}),g.plane.material.blending=5,g.plane.material.blendEquation=u,g.plane.material.blendSrc=p,g.plane.material.blendDst=p,g.xrlayer=this._createXRLayer(g);const e=this._session.renderState.layers;e.unshift(g.xrlayer),this._session.updateRenderState({layers:e})}else c.isXRRenderTarget=!1;return m}renderLayers(){const e=new Ot,t=new It,s=this._renderer,i=this.isPresenting;this.isPresenting=!1;const r=new Dt;s.getSize(r);const n=s.getRenderTarget();for(const i of this._layers){i.renderTarget.isXRRenderTarget=null!==this._session,i.renderTarget._hasExternalTextures=i.renderTarget.isXRRenderTarget;const r=s.contextNode;let n;if(i.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){i.xrlayer.transform=new XRRigidTransform(i.plane.getWorldPosition(e),i.plane.getWorldQuaternion(t));const a=this._glBinding.getSubImage(i.xrlayer,this._xrFrame);s.backend.setXRRenderTargetTextures(i.renderTarget,a.colorTexture,void 0),s._setXRLayerSize(i.renderTarget.width,i.renderTarget.height),n=Wx.get(r),void 0===n&&(n=r.context({getOutput:e=>Uu(e,s.toneMapping,s.outputColorSpace)}),Wx.set(r,n))}else n=r;s.contextNode=n,s.setRenderTarget(i.renderTarget),i.rendercall(),s.contextNode=r}s.setRenderTarget(n),s._setXRLayerSize(r.x,r.y),this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer,s=t.backend;this._gl=t.getContext();const i=this._gl,r=i.getContextAttributes();if(this._session=e,null!==e){if(!0===s.isWebGPUBackend)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await s.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._supportsLayers){let s=null,n=null,a=null;t.depth&&(a=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,s=t.stencil?ae:ne,n=t.stencil?J:X);const o={colorFormat:i.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const h=this._glBinding.createProjectionLayer(o),l=[h];this._glProjLayer=h,t.setPixelRatio(1),t._setXRLayerSize(h.textureWidth,h.textureHeight);const c=this._useMultiview?2:1,d=new Fr(h.textureWidth,h.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,s,c);if(this._xrRenderTarget=new Gx(h.textureWidth,h.textureHeight,{format:re,type:j,colorSpace:t.outputColorSpace,depthTexture:d,stencilBuffer:t.stencil,samples:r.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const e of this._layers)e.plane.material=new sr({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=u,e.plane.material.blendSrc=p,e.plane.material.blendDst=p,e.xrlayer=this._createXRLayer(e),l.unshift(e.xrlayer);e.updateRenderState({layers:l})}else{const s={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,i,s);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t._setXRLayerSize(r.framebufferWidth,r.framebufferHeight),this._xrRenderTarget=new Gx(r.framebufferWidth,r.framebufferHeight,{format:re,type:j,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===r.ignoreDepthValues,resolveStencilBuffer:!1===r.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const s=e.near,i=e.far,r=this._cameraXR,n=this._cameraL,a=this._cameraR;r.near=a.near=n.near=s,r.far=a.far=n.far=i,r.isMultiViewCamera=this._useMultiview,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),r.layers.mask=6|e.layers.mask,n.layers.mask=-5&r.layers.mask,a.layers.mask=-3&r.layers.mask;const o=e.parent,h=r.cameras;qx(r,o);for(let e=0;e<h.length;e++)qx(h[e],o);2===h.length?function(e,t,s){jx.setFromMatrixPosition(t.matrixWorld),$x.setFromMatrixPosition(s.matrixWorld);const i=jx.distanceTo($x),r=t.projectionMatrix.elements,n=s.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),h=(r[9]+1)/r[5],l=(r[9]-1)/r[5],u=(r[8]-1)/r[0],c=(n[8]+1)/n[0],d=a*u,p=a*c,m=i/(-u+c),g=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(g),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===r[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+m,s=o+m,r=d-g,n=p+(i-g),u=h*o/s*t,c=l*o/s*t;e.projectionMatrix.makePerspective(r,n,u,c,t,s),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(r,n,a):r.projectionMatrix.copy(n.projectionMatrix),function(e,t,s){null===s?e.matrix.copy(t.matrixWorld):(e.matrix.copy(s.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*At*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,r,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new Ds,this._controllers[e]=t),t}}function qx(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function Xx(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const s=this._controllers[t];if(void 0!==s){const t=this.getReferenceSpace();s.update(e.inputSource,e.frame,t),s.dispatchEvent({type:e.type,data:e.inputSource})}}function Yx(){const e=this._session,t=this._renderer;e.removeEventListener("select",this._onSessionEvent),e.removeEventListener("selectstart",this._onSessionEvent),e.removeEventListener("selectend",this._onSessionEvent),e.removeEventListener("squeeze",this._onSessionEvent),e.removeEventListener("squeezestart",this._onSessionEvent),e.removeEventListener("squeezeend",this._onSessionEvent),e.removeEventListener("end",this._onSessionEnd),e.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let e=0;e<this._controllers.length;e++){const t=this._controllerInputSources[e];null!==t&&(this._controllerInputSources[e]=null,this._controllers[e].disconnect(t))}if(this._currentDepthNear=null,this._currentDepthFar=null,t._resetXRState(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._glBaseLayer=null,this._glProjLayer=null,!0===this._sessionUsesLayers)for(const e of this._layers)e.renderTarget=new Gx(e.pixelwidth,e.pixelheight,{format:re,type:j,depthTexture:new Fr(e.pixelwidth,e.pixelheight,e.stencilBuffer?J:X,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?ae:ne),stencilBuffer:e.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,e.material.map.offset.y=1,e.material.map.repeat.y=-1,delete e.xrlayer;this.isPresenting=!1,this._useMultiview=!1,t._animation.stop(),t._animation.setAnimationLoop(this._currentAnimationLoop),t._animation.setContext(this._currentAnimationContext),t._animation.start(),t.setPixelRatio(this._currentPixelRatio),t.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function Kx(e){const t=this._controllers,s=this._controllerInputSources;for(let i=0;i<e.removed.length;i++){const r=e.removed[i],n=s.indexOf(r);n>=0&&(s[n]=null,t[n].disconnect(r))}for(let i=0;i<e.added.length;i++){const r=e.added[i];let n=s.indexOf(r);if(-1===n){for(let e=0;e<t.length;e++){if(e>=s.length){s.push(r),n=e;break}if(null===s[e]){s[e]=r,n=e;break}}if(-1===n)break}const a=t[n];a&&a.connect(r)}}function Qx(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function Zx(e,t){if(void 0===t)return;const s=this._cameraXR,i=this._renderer,r=i.backend,n=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views;null!==this._glBaseLayer&&r.setXRTarget(n.framebuffer);let t=!1;e.length!==s.cameras.length&&(s.cameras.length=0,t=!0);for(let i=0;i<e.length;i++){const a=e[i];let o;if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,a);o=e.viewport,0===i&&r.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else o=n.getViewport(a);let h=this._cameras[i];void 0===h&&(h=new hn,h.layers.enable(i),h.viewport=new ss,this._cameras[i]=h),h.matrix.fromArray(a.transform.matrix),h.matrix.decompose(h.position,h.quaternion,h.scale),h.projectionMatrix.fromArray(a.projectionMatrix),h.projectionMatrixInverse.copy(h.projectionMatrix).invert(),h.viewport.set(o.x,o.y,o.width,o.height),0===i&&(s.matrix.copy(h.matrix),s.matrix.decompose(s.position,s.quaternion,s.scale)),!0===t&&s.cameras.push(h)}i.setOutputRenderTarget(this._xrRenderTarget)}for(let e=0;e<this._controllers.length;e++){const s=this._controllerInputSources[e],i=this._controllers[e];null!==s&&void 0!==i&&i.update(s,t,a)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class Jx extends St{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new ss(0,0,this._width,this._height),this._scissor=new ss(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new Pr,this.depthTexture=new Fr}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===s&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,s,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,r=0,n=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,s,i),a.minDepth=r,a.maxDepth=n}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const ev=new Gs,tv=new Dt,sv=new ss,iv=new Mr,rv=new Er,nv=new ns,av=new ss,ov={[o]:1,[h]:0,[l]:2};class hv{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,reversedDepthBuffer:i=!1,alpha:r=!0,depth:n=!0,stencil:a=!1,antialias:o=!1,samples:h=0,getFallback:l=null,outputBufferType:u=K,multiview:c=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=s,this.reversedDepthBuffer=i,this.outputColorSpace=qe,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=n,this.stencil=a,this.info=new Py,this.contextNode=Jl(),this.library=new Ux,this.lighting=new Vx,this._samples=h||!0===o?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new Jx(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new zu,this._inspector.setRenderer(this),this._getFallback=l,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;const d=!0===this.alpha?0:1;this._clearColor=new Qy(0,0,0,d),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._outputBufferType=u,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:1},this.xr=new Hx(this,c),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,s)=>{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(this._renderTarget,this._mrt),n=e.overrideMaterial||s.material,a=this._objects.get(s,n,e,t,i.lightsNode,r,r.clippingContext),{fragmentShader:o,vertexShader:h}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:h}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let s=this.backend;try{await s.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=s=this._getFallback(e),await s.init(this)}catch(e){return void t(e)}}this._nodes=new Bx(this,s),this._animation=new my(this,this._nodes,this.info),this._attributes=new Ny(s,this.info),this._background=new E_(this,this._nodes),this._geometries=new Cy(this._attributes,this.info),this._textures=new Ky(this,s,this.info),this._pipelines=new Oy(s,this._nodes,this.info),this._bindings=new Uy(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new _y(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new $y(this.lighting),this._bundles=new Ox,this._renderContexts=new Xy(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,n=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._handleObjectFunction,h=this._compilationPromises;null===s&&(s=e);const l=!0===e.isScene?e:!0===s.isScene?s:ev,u=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,c=this._renderContexts.get(u,this._mrt),d=this._activeMipmapLevel,p=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,i.renderId++,i.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new Lx),c.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,u);const m=this._renderLists.get(l,t);if(m.begin(),this._projectObject(e,t,0,m,c.clippingContext),s!==e&&s.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&m.pushLight(e)}),m.finish(),null!==u){this._textures.updateRenderTarget(u,d);const e=this._textures.get(u);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;s!==e?this._background.update(s,m,c):this._background.update(l,m,c);const g=m.opaque,f=m.transparent,y=m.transparentDoublePass,b=m.lightsNode;!0===this.opaque&&g.length>0&&this._renderObjects(g,t,l,b),!0===this.transparent&&f.length>0&&this._renderTransparents(f,y,t,l,b),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._handleObjectFunction=o,this._compilationPromises=h;for(const e of p){const t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,this._geometries.updateForRender(t),await this._nodes.getForRenderAsync(t),this._nodes.updateBefore(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t);const s=[];this._pipelines.getForRender(t,s),s.length>0&&await Promise.all(s),this._nodes.updateAfter(t),await vt()}}async renderAsync(e,t){xt('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){_t("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=Uc,t.modelNormalViewMatrix=kc):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Uc&&e.modelNormalViewMatrix===kc}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return xt('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),_t(t),this._isDeviceLost=!0}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(i,r,a),h=this.backend.get(o),l=i.version!==h.version;if(l||void 0===h.bundleGPU){this.backend.beginBundle(a),(void 0===h.renderObjects||l)&&(h.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:u,opaque:c}=n;!0===this.opaque&&c.length>0&&this._renderObjects(c,r,t,s),!0===this.transparent&&u.length>0&&this._renderTransparents(u,e,r,t,s),this._currentRenderBundle=null,this.backend.finishBundle(a,o),h.version=i.version}else{const{renderObjects:e}=h;for(let t=0,s=e.length;t<s;t++){const s=e[t];this._nodes.needsRefresh(s)&&(this._nodes.updateBefore(s),this._nodes.updateForRender(s),this._bindings.updateForRender(s),this._nodes.updateAfter(s))}}this.backend.addBundle(a,o)}render(e,t){if(!1===this._initialized)throw new Error('Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this,s=0!==e,i=t!==Wt.workingColorSpace;if(!1===s&&!1===i)return null;const{width:r,height:n}=this.getDrawingBufferSize(tv),{depth:a,stencil:o}=this,h=this._outputRenderTarget||this._canvasTarget;let l=this._frameBufferTargets.get(h);if(void 0===l){l=new is(r,n,{depthBuffer:a,stencilBuffer:o,type:this._outputBufferType,format:re,colorSpace:Wt.workingColorSpace,generateMipmaps:!1,minFilter:z,magFilter:z,samples:this.samples}),l.isPostProcessingRenderTarget=!0;const e=()=>{h.removeEventListener("dispose",e),l.dispose(),this._frameBufferTargets.delete(h)};h.addEventListener("dispose",e),this._frameBufferTargets.set(h,l)}const u=this.getOutputRenderTarget();l.depthBuffer=a,l.stencilBuffer=o,null!==u?l.setSize(u.width,u.height,u.depth):l.setSize(r,n,1);const c=this._outputRenderTarget?this._outputRenderTarget.viewport:h._viewport,d=this._outputRenderTarget?this._outputRenderTarget.scissor:h._scissor,p=this._outputRenderTarget?1:h._pixelRatio,m=this._outputRenderTarget?this._outputRenderTarget.scissorTest:h._scissorTest;return l.viewport.copy(c),l.scissor.copy(d),l.viewport.multiplyScalar(p),l.scissor.multiplyScalar(p),l.scissorTest=m,l.multiview=null!==u&&u.multiview,l.resolveDepthBuffer=null===u||u.resolveDepthBuffer,l._autoAllocateDepthBuffer=null!==u&&u._autoAllocateDepthBuffer,l}_renderScene(e,t,s=!0){if(!0===this._isDeviceLost)return;const i=s?this._getFrameBufferTarget():null,r=this._nodes.nodeFrame,n=r.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,h=this._handleObjectFunction;this._callDepth++;const l=!0===e.isScene?e:ev,u=this._renderTarget||this._outputRenderTarget,c=this._activeCubeFace,d=this._activeMipmapLevel;let p;if(null!==i?(p=i,this.setRenderTarget(p)):p=u,null!==p&&!0===p.depthBuffer){const e=this._textures.get(p);!0!==e.depthInitialized&&((!1===this.autoClear||!0===this.autoClear&&!1===this.autoClearDepth)&&this.clearDepth(),e.depthInitialized=!0)}const m=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=m,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(m),this.inspector.beginRender(this.backend.getTimestampUID(m),e,t,p);const g=this.xr;if(!1===g.isPresenting){let e=!1;if(!0===this.reversedDepthBuffer&&!0!==t.reversedDepth){if(t._reversedDepth=!0,t.isArrayCamera)for(const e of t.cameras)e._reversedDepth=!0;e=!0}const s=this.coordinateSystem;if(t.coordinateSystem!==s){if(t.coordinateSystem=s,t.isArrayCamera)for(const e of t.cameras)e.coordinateSystem=s;e=!0}if(!0===e&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.updateProjectionMatrix()}!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===g.enabled&&!0===g.isPresenting&&(!0===g.cameraAutoUpdate&&g.updateCamera(t),t=g.getCamera());const f=this._canvasTarget;let y=f._viewport,b=f._scissor,_=f._pixelRatio;null!==p&&(y=p.viewport,b=p.scissor,_=1),this.getDrawingBufferSize(tv),sv.set(0,0,tv.width,tv.height);const x=void 0===y.minDepth?0:y.minDepth,v=void 0===y.maxDepth?1:y.maxDepth;m.viewportValue.copy(y).multiplyScalar(_).floor(),m.viewportValue.width>>=d,m.viewportValue.height>>=d,m.viewportValue.minDepth=x,m.viewportValue.maxDepth=v,m.viewport=!1===m.viewportValue.equals(sv),m.scissorValue.copy(b).multiplyScalar(_).floor(),m.scissor=f._scissorTest&&!1===m.scissorValue.equals(sv),m.scissorValue.width>>=d,m.scissorValue.height>>=d,m.clippingContext||(m.clippingContext=new Lx),m.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,p);const T=t.isArrayCamera?rv:iv;t.isArrayCamera||(nv.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),T.setFromProjectionMatrix(nv,t.coordinateSystem,t.reversedDepth));const S=this._renderLists.get(e,t);if(S.begin(),this._projectObject(e,t,0,S,m.clippingContext),S.finish(),!0===this.sortObjects&&S.sort(this._opaqueSort,this._transparentSort),null!==p){this._textures.updateRenderTarget(p,d);const e=this._textures.get(p);m.textures=e.textures,m.depthTexture=e.depthTexture,m.width=e.width,m.height=e.height,m.renderTarget=p,m.depth=p.depthBuffer,m.stencil=p.stencilBuffer}else m.textures=null,m.depthTexture=null,m.width=tv.width,m.height=tv.height,m.depth=this.depth,m.stencil=this.stencil;m.width>>=d,m.height>>=d,m.activeCubeFace=c,m.activeMipmapLevel=d,m.occlusionQueryCount=S.occlusionQueryCount,m.scissorValue.max(av.set(0,0,0,0)),m.scissorValue.x+m.scissorValue.width>m.width&&(m.scissorValue.width=Math.max(m.width-m.scissorValue.x,0)),m.scissorValue.y+m.scissorValue.height>m.height&&(m.scissorValue.height=Math.max(m.height-m.scissorValue.y,0)),this._background.update(l,S,m),m.camera=t,this.backend.beginRender(m);const{bundles:w,lightsNode:M,transparentDoublePass:N,transparent:A,opaque:E}=S;return w.length>0&&this._renderBundles(w,l,M),!0===this.opaque&&E.length>0&&this._renderObjects(E,t,l,M),!0===this.transparent&&A.length>0&&this._renderTransparents(A,N,t,l,M),this.backend.finishRender(m),r.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=h,this._callDepth--,null!==i&&(this.setRenderTarget(u,c,d),this._renderOutput(p)),l.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(m)),m}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._nodes.getOutputCacheKey();let s,i=this._quadCache.get(e.texture);if(void 0===i){s=new lb(new Em),s.name="Output Color Transform",s.material.name="outputColorTransform",s.material.fragmentNode=this._nodes.getOutputNode(e.texture),i={quad:s,cacheKey:t},this._quadCache.set(e.texture,i);const r=()=>{s.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",r)};e.texture.addEventListener("dispose",r)}else s=i.quad,i.cacheKey!==t&&(s.material.fragmentNode=this._nodes.getOutputNode(e.texture),s.material.needsUpdate=!0,i.cacheKey=t);const r=this.autoClear,n=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(s,s.camera,!1),this.autoClear=r,this.xr.enabled=n}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,s=0,i=-1){if(null!==t&&t.isReadbackBuffer&&!1===this.info.memoryMap.has(t)){this.info.createReadbackBuffer(t);const e=()=>{t.removeEventListener("dispose",e),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",e)}if(s%4!=0||i>0&&i%4!=0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,s,i)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,s)}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,s)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,s,i){this._canvasTarget.setScissor(e,t,s,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,s,i,r=0,n=1){this._canvasTarget.setViewport(e,t,s,i,r,n)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,s=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i){this._textures.updateRenderTarget(i);const e=this._textures.get(i);r=this._renderContexts.get(i,null,-1),r.textures=e.textures,r.depthTexture=e.depthTexture,r.width=e.width,r.height=e.height,r.renderTarget=i,r.depth=i.depthBuffer,r.stencil=i.stencilBuffer;const t=this.backend.getClearColor();r.clearColorValue.r=t.r,r.clearColorValue.g=t.g,r.clearColorValue.b=t.b,r.clearColorValue.a=t.a,r.clearDepthValue=this.getClearDepth(),r.clearStencilValue=this.getClearStencil(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel(),!0===i.depthBuffer&&(e.depthInitialized=!0)}this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){xt('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,s)}async clearColorAsync(){xt('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){xt('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){xt('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=0!==this.currentToneMapping,t=this.currentColorSpace!==Wt.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Wt.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){if(!0===this._initialized){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})}this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null);for(const e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return bt("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const s=this._nodes.nodeFrame,i=s.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,s.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const r=this.backend,n=this._pipelines,a=this._bindings,o=this._nodes,h=Array.isArray(e)?e:[e];if(void 0===h[0]||!0!==h[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const s of h){if(!1===n.has(s)){const e=()=>{s.removeEventListener("dispose",e),n.delete(s),a.deleteForCompute(s),o.delete(s)};s.addEventListener("dispose",e);const t=s.onInitFunction;null!==t&&t.call(s,{renderer:this})}o.updateForCompute(s),a.updateForCompute(s);const i=a.getForCompute(s),h=n.getForCompute(s,i);r.compute(e,s,i,h,t)}r.finishCompute(e),s.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return xt('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){xt('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),s=this._renderContexts.get(e);s.textures=t.textures,s.depthTexture=t.depthTexture,s.width=t.width,s.height=t.height,s.renderTarget=e,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,this.backend.initRenderTarget(s)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=av.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void _t("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=av.copy(t).floor()}else t=av.set(0,0,e.image.width,e.image.height);let s,i=this._currentRenderContext;null!==i?s=i.renderTarget:(s=this._renderTarget||this._getFrameBufferTarget(),null!==s&&(this._textures.updateRenderTarget(s),i=this._textures.get(s))),this._textures.updateTexture(e,{renderTarget:s}),this.backend.copyFramebufferToTexture(e,i,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,r,n),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,s,i,r,n=0,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,a)}_projectObject(e,t,s,i,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)s=e.renderOrder,e.isClippingGroup&&e.enabled&&(r=r.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const n=t.isArrayCamera?rv:iv;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&av.setFromMatrixPosition(e.matrixWorld).applyMatrix4(nv);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,av.z,null,r)}}else if(e.isLineLoop)_t("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?rv:iv;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),av.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(nv)),Array.isArray(n)){const a=t.groups;for(let o=0,h=a.length;o<h;o++){const h=a[o],l=n[h.materialIndex];l&&l.visible&&i.push(e,t,l,s,av.z,h,r)}}else n.visible&&i.push(e,t,n,s,av.z,null,r)}}if(!0===e.isBundleGroup&&void 0!==this.backend.beginBundle){const s=i;(i=this._renderLists.get(e,t)).begin(),s.pushBundle({bundleGroup:e,camera:t,renderList:i}),i.finish()}const n=e.children;for(let e=0,a=n.length;e<a;e++)this._projectObject(n[e],t,s,i,r)}_renderBundles(e,t,s){for(const i of e)this._renderBundle(i,t,s)}_renderTransparents(e,t,s,i,r){if(t.length>0){for(const{material:e}of t)e.side=1;this._renderObjects(t,s,i,r,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,s,i,r);for(const{material:e}of t)e.side=2}else this._renderObjects(e,s,i,r)}_renderObjects(e,t,s,i,r=null){for(let n=0,a=e.length;n<a;n++){const{object:a,geometry:o,material:h,group:l,clippingContext:u}=e[n];this._currentRenderObjectFunction(a,s,t,o,h,l,i,u,r)}}_getShadowNodes(e){const t=e.version;let s=this._cacheShadowNodes.get(e);if(void 0===s||s.version!==t){const i=null!==e.map,r=e.colorNode&&e.colorNode.isNode,n=e.castShadowNode&&e.castShadowNode.isNode,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let o=null,h=null,l=null;if(i||r||n||a){let t,s;if(n?(t=e.castShadowNode.rgb,s=e.castShadowNode.a,!0!==this.shadowMap.transmitted&&xt("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(t=go(0),s=ao(1)),i&&(s=s.mul(vd("map","texture",e).a)),r&&(s=s.mul(e.colorNode.a)),h=_o(t,s),a){const t=e.maskShadowNode||e.maskNode;h=eo(([e])=>(t.not().discard(),e))(h)}}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),s={version:t,colorNode:h,depthNode:l,positionNode:o},this._cacheShadowNodes.set(e,s)}return s}renderObject(e,t,s,i,r,n,a,o=null,h=null){let l,u,c,d,p=!1;if(e.onBeforeRender(this,t,s,i,r,n),!0===r.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,l=e.isNodeMaterial?e.colorNode:null,u=e.isNodeMaterial?e.depthNode:null,c=e.isNodeMaterial?e.positionNode:null,d=t.overrideMaterial.side,r.positionNode&&r.positionNode.isNode&&(e.positionNode=r.positionNode),e.alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.transparent=r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:s,positionNode:i}=this._getShadowNodes(r);3===this.shadowMap.type?e.side=null!==r.shadowSide?r.shadowSide:r.side:e.side=null!==r.shadowSide?r.shadowSide:ov[r.side],null!==t&&(e.colorNode=t),null!==s&&(e.depthNode=s),null!==i&&(e.positionNode=i)}r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,s,a,n,o,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,s,a,n,o,h),r.side=2):this._handleObjectFunction(e,r,t,s,a,n,o,h),p&&(t.overrideMaterial.colorNode=l,t.overrideMaterial.depthNode=u,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=d),e.onAfterRender(this,t,s,i,r,n)}hasCompatibility(e){if(!1===this._initialized)throw new Error('Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,s,i,r,n,a,o){const h=this._objects.get(e,t,s,i,r,this._currentRenderContext,a,o);if(h.drawRange=e.geometry.drawRange,h.group=n,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(h),h.bundle=this._currentRenderBundle.bundleGroup}const l=this._nodes.needsRefresh(h);l&&(this._nodes.updateBefore(h),this._geometries.updateForRender(h),this._nodes.updateForRender(h),this._bindings.updateForRender(h)),this._pipelines.updateForRender(h),this._pipelines.isReady(h)&&(this.backend.draw(h,this.info),l&&this._nodes.updateAfter(h))}_createObjectPipeline(e,t,s,i,r,n,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,scene:s,camera:i,lightsNode:r,group:n,clippingContext:a,passId:o,renderContext:this._currentRenderContext});const h=this._objects.get(e,t,s,i,r,this._currentRenderContext,a,o);h.drawRange=e.geometry.drawRange,h.group=n,this._nodes.updateBefore(h),this._geometries.updateForRender(h),this._nodes.updateForRender(h),this._bindings.updateForRender(h),this._pipelines.getForRender(h,this._compilationPromises),this._nodes.updateAfter(h)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class lv{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}class uv extends lv{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(My-e%My)%My;var e}get buffer(){return this._buffer}update(){return!0}}class cv extends uv{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let dv=0;class pv extends cv{constructor(e,t){super("UniformBuffer_"+dv++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class mv extends cv{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(!0!==this._updateRangeCache.has(t)){const s=this.updateRanges,i={start:e.offset,count:e.itemSize};s.push(i),this._updateRangeCache.set(t,i)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let s=0,i=this.uniforms.length;s<i;s++){const i=this.uniforms[s],r=i.boundary,n=i.itemSize*e,a=t%My,o=a%r,h=a+o;t+=o,0!==h&&My-h<n&&(t+=My-h),i.offset=t/e,i.index=s,t+=n}return Math.ceil(t/My)*My}update(){let e=!1;for(const t of this.uniforms)!0===this.updateByType(t)&&(e=!0);return e}updateByType(e){return e.isNumberUniform?this.updateNumber(e):e.isVector2Uniform?this.updateVector2(e):e.isVector3Uniform?this.updateVector3(e):e.isVector4Uniform?this.updateVector4(e):e.isColorUniform?this.updateColor(e):e.isMatrix3Uniform?this.updateMatrix3(e):e.isMatrix4Uniform?this.updateMatrix4(e):void _t("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r]!==i){this._getBufferForType(n)[r]=s[r]=i,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y){const a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z){const a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,a[r+2]=s[r+2]=i.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z||s[r+3]!==i.w){const a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,a[r+2]=s[r+2]=i.z,a[r+3]=s[r+3]=i.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset;if(s[r+0]!==i.r||s[r+1]!==i.g||s[r+2]!==i.b){const n=this.buffer;n[r+0]=s[r+0]=i.r,n[r+1]=s[r+1]=i.g,n[r+2]=s[r+2]=i.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const s=this.values,i=e.getValue().elements,r=e.offset;if(s[r+0]!==i[0]||s[r+1]!==i[1]||s[r+2]!==i[2]||s[r+4]!==i[3]||s[r+5]!==i[4]||s[r+6]!==i[5]||s[r+8]!==i[6]||s[r+9]!==i[7]||s[r+10]!==i[8]){const n=this.buffer;n[r+0]=s[r+0]=i[0],n[r+1]=s[r+1]=i[1],n[r+2]=s[r+2]=i[2],n[r+4]=s[r+4]=i[3],n[r+5]=s[r+5]=i[4],n[r+6]=s[r+6]=i[5],n[r+8]=s[r+8]=i[6],n[r+9]=s[r+9]=i[7],n[r+10]=s[r+10]=i[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const s=this.values,i=e.getValue().elements,r=e.offset;if(!1===function(e,t,s){for(let i=0,r=t.length;i<r;i++)if(e[s+i]!==t[i])return!1;return!0}(s,i,r)){this.buffer.set(i,r),function(e,t,s){for(let i=0,r=t.length;i<r;i++)e[s+i]=t[i]}(s,i,r),t=!0,this.addUniformUpdateRange(e)}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let gv=0;class fv extends mv{constructor(e,t){super(e),this.id=gv++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class yv extends lv{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let bv=0;class _v extends yv{constructor(e,t){super(e,t),this.id=bv++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class xv extends _v{constructor(e,t,s,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s,this.access=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class vv extends xv{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class Tv extends xv{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const Sv={bitcast_int_uint:new Pb("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new Pb("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},wv={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},Mv={low:"lowp",medium:"mediump",high:"highp"},Nv={swizzleAssign:!0,storageBuffer:!1},Av={perspective:"smooth",linear:"noperspective"},Ev={centroid:"centroid"},Rv="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n";class Cv extends hx{constructor(e,t){super(e,t,new Rx),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==He}_include(e){const t=Sv[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==Sv[e]&&this._include(e),wv[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,s){return`${e} ? ${t} : ${s}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {\n\n\t${s.vars}\n\n${s.code}\n\treturn ${s.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,s=t.count*t.itemSize,{itemSize:i}=t,r=t.array.constructor.name.toLowerCase().includes("int");let n=r?he:oe;2===i?n=r?ue:le:3===i?n=r?1032:ie:4===i&&(n=r?ce:re);const a={Float32Array:Y,Uint8Array:j,Uint16Array:H,Uint32Array:X,Int8Array:$,Int16Array:W,Int32Array:q,Uint8ClampedArray:j},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(s/i))));let h=Math.ceil(s/i/o);o*h*i<s&&h++;const l=o*h*i,u=new e.constructor(l);u.set(e,0),t.array=u;const c=new fr(t.array,o,h,n,a[t.array.constructor.name]||Y);c.needsUpdate=!0,c.isPBOTexture=!0;const d=new Qu(c,null,null);d.setPrecision("high"),t.pboNode=d,t.pbo=d.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:s}=e,i=t.value;if(this.renderer.backend.has(i)){this.renderer.backend.get(i).pbo=i.pbo}const r=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName),n=this.getPropertyName(r);this.increaseUsage(s);const a=s.build(this,"uint"),o=this.getDataFromNode(e);let h=o.propertyName;if(void 0===h){const s=this.getVarFromNode(e);h=this.getPropertyName(s);const r=this.getDataFromNode(t);let l=r.propertySizeName;void 0===l&&(l=h+"Size",this.getVarFromNode(t,l,"uint"),this.addLineFlowCode(`${l} = uint( textureSize( ${n}, 0 ).x )`,e),r.propertySizeName=l);const{itemSize:u}=i,c="."+Jn.join("").slice(0,u),d=`ivec2(${a} % ${l}, ${a} / ${l})`,p=this.generateTextureLoad(null,n,d,"0",null,null);let m="vec4";i.pbo.type===X?m="uvec4":i.pbo.type===q&&(m="ivec4"),this.addLineFlowCode(`${h} = ${m}(${p})${c}`,e),o.propertyName=h}return h}generateTextureLoad(e,t,s,i,r,n){let a;return null===i&&(i="0"),a=r?n?`texelFetchOffset( ${t}, ivec3( ${s}, ${r} ), int( ${i} ), ${n} )`:`texelFetch( ${t}, ivec3( ${s}, ${r} ), int( ${i} ) )`:n?`texelFetchOffset( ${t}, ${s}, int( ${i} ), ${n} )`:`texelFetch( ${t}, ${s}, int( ${i} ) )`,null!==e&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,s,i,r){return i&&(s=`vec3( ${s}, ${i} )`),e.isDepthTexture?r?`textureOffset( ${t}, ${s}, ${r} ).x`:`texture( ${t}, ${s} ).x`:r?`textureOffset( ${t}, ${s}, ${r} )`:`texture( ${t}, ${s} )`}generateTextureLevel(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureLodOffset( ${t}, ${s}, ${i}, ${n} )`:`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureOffset( ${t}, ${s}, ${n}, ${i} )`:`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureGradOffset( ${t}, ${s}, ${i[0]}, ${i[1]}, ${n} )`:`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return e.isCubeTexture?`texture( ${t}, vec4( ${s}, ${i} ) )`:r?n?`textureOffset( ${t}, vec4( ${s}, ${r}, ${i} ), ${n} )`:`texture( ${t}, vec4( ${s}, ${r}, ${i} ) )`:n?`textureOffset( ${t}, vec3( ${s}, ${i} ), ${n} )`:`texture( ${t}, vec3( ${s}, ${i} ) )`;_t(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}getUniforms(e){const t=this.uniforms[e],s=[],i={};for(const e of t){let t=null,r=!1;if("texture"===e.type||"texture3D"===e.type){const s=e.node.value;let i="";!0!==s.isDataTexture&&!0!==s.isData3DTexture||(s.type===X?i="u":s.type===q&&(i="i")),t="texture3D"===e.type&&!1===s.isArrayTexture?`${i}sampler3D ${e.name};`:s.compareFunction?!0===s.isArrayTexture?`sampler2DArrayShadow ${e.name};`:`sampler2DShadow ${e.name};`:!0===s.isArrayTexture||!0===s.isDataArrayTexture||!0===s.isCompressedArrayTexture?`${i}sampler2DArray ${e.name};`:`${i}sampler2D ${e.name};`}else if("cubeTexture"===e.type)t=`samplerCube ${e.name};`;else if("cubeDepthTexture"===e.type){t=e.node.value.compareFunction?`samplerCubeShadow ${e.name};`:`samplerCube ${e.name};`}else if("buffer"===e.type){const s=e.node,i=this.getType(s.bufferType),r=s.bufferCount,n=r>0?r:"";t=`${s.name} {\n\t${i} ${e.name}[${n}];\n};\n`}else{const t=e.groupNode.name;if(void 0===i[t]){const e=this.uniformGroups[t];if(void 0!==e){const s=[];for(const t of e.uniforms){const e=t.getType(),i=this.getVectorType(e),r=t.nodeUniform.node.precision;let n=`${i} ${t.name};`;null!==r&&(n=Mv[r]+" "+n),s.push("\t"+n)}i[t]=s}}r=!0}if(!r){const i=e.node.precision;null!==i&&(t=Mv[i]+" "+t),t="uniform "+t,s.push(t)}}let r="";for(const e in i){const t=i[e];r+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==q){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const i=s.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let s=0;for(const i of e)t+=`layout( location = ${s++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[];for(const s of e.members)t.push(`\t${s.type} ${s.name};`);return t.join("\n")}getStructs(e){const t=[],s=this.structs[e],i=[];for(const e of s)if(e.output)for(const t of e.members)i.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let s="struct "+e.name+" {\n";s+=this.getStructMembers(e),s+="\n};\n",t.push(s)}return 0===i.length&&i.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+i.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const s=this.varyings;if("vertex"===e||"compute"===e)for(const i of s){"compute"===e&&(i.needsInterpolation=!0);const s=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){t+=`${Av[i.interpolationType]||i.interpolationType} ${Ev[i.interpolationSampling]||""} out ${s} ${i.name};\n`}else{t+=`${s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":""}out ${s} ${i.name};\n`}else t+=`${s} ${i.name};\n`}else if("fragment"===e)for(const e of s)if(e.needsInterpolation){const s=this.getType(e.type);if(e.interpolationType){t+=`${Av[e.interpolationType]||e.interpolationType} ${Ev[e.interpolationSampling]||""} in ${s} ${e.name};\n`}else{t+=`${s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":""}in ${s} ${e.name};\n`}}for(const s of this.builtins[e])t+=`${s};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){_t("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){_t("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){_t("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,s=this.shaderStage){const i=this.extensions[s]||(this.extensions[s]=new Map);!1===i.has(e)&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const s=this.extensions[e];if(void 0!==s)for(const{name:e,behavior:i}of s.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=Nv[e];if(void 0===t){let s;switch(t=!1,e){case"float32Filterable":s="OES_texture_float_linear";break;case"clipDistance":s="WEBGL_clip_cull_distance"}if(void 0!==s){const e=this.renderer.backend.extensions;e.has(s)&&(e.get(s),t=!0)}Nv[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s<e.length;s++){const i=e[s],r=this.getPropertyName(i.attributeNode);r&&(t+=`${i.varyingName} = ${r};\n\t`)}return t}_getGLSLUniformStruct(e,t){return`\nlayout( std140 ) uniform ${e} {\n${t}\n};`}_getGLSLVertexCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${Rv}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// transforms\n\t${e.transforms}\n\n\t// flow\n\t${e.flow}\n\n\tgl_PointSize = 1.0;\n\n}\n`}_getGLSLFragmentCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${Rv}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// flow\n\t${e.flow}\n\n}\n`}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let s="// code\n\n";s+=this.flowCode[t];const i=this.flowNodes[t],r=i[i.length-1];for(const e of i){const i=this.getFlowData(e),n=e.name;n&&(s.length>0&&(s+="\n"),s+=`\t// flow -> ${n}\n\t`),s+=`${i.code}\n\t`,e===r&&"compute"!==t&&(s+="// result\n\t","vertex"===t?(s+="gl_Position = ",s+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${i.result};`)))}const n=e[t];if(n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t,!0),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=s,"vertex"===t){const e=this.renderer.backend.extensions;this.object.isBatchedMesh&&!1===e.has("WEBGL_multi_draw")&&(n.uniforms+="\nuniform uint nodeUniformDrawId;\n")}}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);let a=n.uniformGPU;if(void 0===a){const i=e.groupNode,o=i.name,h=this.getBindGroupArray(o,s);if("texture"===t)a=new xv(r.name,r.node,i),h.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new vv(r.name,r.node,i),h.push(a);else if("texture3D"===t)a=new Tv(r.name,r.node,i),h.push(a);else if("buffer"===t){r.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let s=t.buffer;void 0===s&&(e.name=`NodeBuffer_${e.id}`,s=new pv(e,i),s.name=e.name,t.buffer=s),h.push(s),a=s}else{let e=this.uniformGroups[o];void 0===e?(e=new fv(o,i),this.uniformGroups[o]=e,h.push(e)):-1===h.indexOf(e)&&h.push(e),a=this.getNodeUniform(r,t);const s=a.name,n=e.uniforms.some(e=>e.name===s);n||e.addUniform(a)}n.uniformGPU=a}return r}}let Pv=null,Bv=null;class Fv{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[ct]:null,[ut]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),s=this.renderer.info.frame;let i;i=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+e.id+":f"+s}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?ut:ct;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void xt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const s=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=s,s}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return Pv=Pv||new Dt,this.renderer.getDrawingBufferSize(Pv)}setScissorTest(){}getClearColor(){const e=this.renderer;return Bv=Bv||new Qy,e.getClearColor(Bv),Bv.getRGB(Bv),Bv}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=mt("canvas");return e.style.display="block",e}(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${a} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let Lv,Dv,Iv=0;class Ov{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class Uv{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=s.get(a);let h,l=o.bufferGPU;if(void 0===l&&(l=this._createBuffer(i,t,r,n),o.bufferGPU=l,o.bufferType=t,o.version=a.version),r instanceof Float32Array)h=i.FLOAT;else if("undefined"!=typeof Float16Array&&r instanceof Float16Array)h=i.HALF_FLOAT;else if(r instanceof Uint16Array)h=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)h=i.SHORT;else if(r instanceof Uint32Array)h=i.UNSIGNED_INT;else if(r instanceof Int32Array)h=i.INT;else if(r instanceof Int8Array)h=i.BYTE;else if(r instanceof Uint8Array)h=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);h=i.UNSIGNED_BYTE}let u={bufferGPU:l,bufferType:t,type:h,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:h===i.INT||h===i.UNSIGNED_INT||e.gpuType===q,id:Iv++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);u=new Ov(u,e)}s.set(e,u)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,n=t.get(r),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(a,n.bufferGPU),0===o.length)s.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e<t;e++){const t=o[e];s.bufferSubData(a,t.start*i.BYTES_PER_ELEMENT,i,t.start,t.count)}r.clearUpdateRanges()}s.bindBuffer(a,null),n.version=r.version}destroyAttribute(e){const t=this.backend,{gl:s}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);s.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e,t=null,s=0,i=-1){const r=this.backend,{gl:n}=r,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a),{bufferGPU:h}=o,l=-1===i?o.byteLength-s:i;let u;if(null===t)u=new Uint8Array(new ArrayBuffer(l));else if(t.isReadbackBuffer){if(!0===t._mapped)throw new Error("WebGPURenderer: ReadbackBuffer must be released before being used again.");const e=()=>{t.buffer=null,t._mapped=!1,t.removeEventListener("release",e),t.removeEventListener("dispose",e)};t.addEventListener("release",e),t.addEventListener("dispose",e),u=new Uint8Array(new ArrayBuffer(l)),t.buffer=u.buffer}else u=new Uint8Array(t);return n.bindBuffer(n.COPY_READ_BUFFER,h),n.getBufferSubData(n.COPY_READ_BUFFER,s,u),n.bindBuffer(n.COPY_READ_BUFFER,null),n.bindBuffer(n.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:u.buffer}_createBuffer(e,t,s,i){const r=e.createBuffer();return e.bindBuffer(t,r),e.bufferData(t,s,i),e.bindBuffer(t,null),r}}class kv{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;Lv={[u]:e.FUNC_ADD,[c]:e.FUNC_SUBTRACT,[d]:e.FUNC_REVERSE_SUBTRACT},Dv={[p]:e.ZERO,[m]:e.ONE,[g]:e.SRC_COLOR,[y]:e.SRC_ALPHA,[S]:e.SRC_ALPHA_SATURATE,[v]:e.DST_COLOR,[_]:e.DST_ALPHA,[f]:e.ONE_MINUS_SRC_COLOR,[b]:e.ONE_MINUS_SRC_ALPHA,[T]:e.ONE_MINUS_DST_COLOR,[x]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=(new ss).fromArray(t),this.currentViewport=(new ss).fromArray(s),this._tempVec4=new ss}enable(e){const{enabled:t}=this;!0!==t[e]&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;!1!==t[e]&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;0!==e?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(1===e?t.cullFace(t.BACK):2===e?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:s}=this;e!==t&&(s.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,s){const i=this.gl,r=this.backend.drawBuffersIndexedExt;if(r)for(let n=0;n<e.length;n++){const a=e[n];let o=null;if(null!==t){const e=t.getBlendMode(a.name);6===e.blending?o=s:0!==e.blending&&(o=e)}else o=s;null!==o?this._setMRTBlendingIndex(n,o):r.blendFuncSeparateiOES(n,i.ONE,i.ZERO,i.ONE,i.ZERO)}else xt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.")}_setMRTBlendingIndex(e,t){const{gl:s}=this,i=this.backend.drawBuffersIndexedExt,r=t.blending,n=t.blendSrc,a=t.blendDst,o=t.blendEquation,h=t.premultipliedAlpha;if(5===r){const s=null!==t.blendSrcAlpha?t.blendSrcAlpha:n,r=null!==t.blendDstAlpha?t.blendDstAlpha:a,h=null!==t.blendEquationAlpha?t.blendEquationAlpha:o;i.blendEquationSeparateiOES(e,Lv[o],Lv[h]),i.blendFuncSeparateiOES(e,Dv[n],Dv[a],Dv[s],Dv[r])}else if(i.blendEquationSeparateiOES(e,s.FUNC_ADD,s.FUNC_ADD),h)switch(r){case 1:default:i.blendFuncSeparateiOES(e,s.ONE,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,s.ONE,s.ONE,s.ONE,s.ONE);break;case 3:i.blendFuncSeparateiOES(e,s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:i.blendFuncSeparateiOES(e,s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ZERO,s.ONE)}else switch(r){case 1:default:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE,s.ONE,s.ONE);break;case 3:i.blendFuncSeparateiOES(e,s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:i.blendFuncSeparateiOES(e,s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ZERO,s.ONE)}}setBlending(e,t,s,i,r,n,a,o){const{gl:h}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(h.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,n=n||s,a=a||i,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(h.blendEquationSeparate(Lv[t],Lv[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(h.blendFuncSeparate(Dv[s],Dv[i],Dv[n],Dv[a]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=n,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||o!==this.currentPremultipledAlpha){if(this.currentBlendEquation===u&&this.currentBlendEquationAlpha===u||(h.blendEquation(h.FUNC_ADD),this.currentBlendEquation=u,this.currentBlendEquationAlpha=u),o)switch(e){case 1:h.blendFuncSeparate(h.ONE,h.ONE_MINUS_SRC_ALPHA,h.ONE,h.ONE_MINUS_SRC_ALPHA);break;case 2:h.blendFunc(h.ONE,h.ONE);break;case 3:h.blendFuncSeparate(h.ZERO,h.ONE_MINUS_SRC_COLOR,h.ZERO,h.ONE);break;case 4:h.blendFuncSeparate(h.DST_COLOR,h.ONE_MINUS_SRC_ALPHA,h.ZERO,h.ONE);break;default:_t("WebGLState: Invalid blending: ",e)}else switch(e){case 1:h.blendFuncSeparate(h.SRC_ALPHA,h.ONE_MINUS_SRC_ALPHA,h.ONE,h.ONE_MINUS_SRC_ALPHA);break;case 2:h.blendFuncSeparate(h.SRC_ALPHA,h.ONE,h.ONE,h.ONE);break;case 3:_t("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:_t("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:_t("WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=o}}else!0===this.currentBlendingEnabled&&(this.disable(h.BLEND),this.currentBlendingEnabled=!1)}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setReversedDepth(e){if(this.currentDepthReversed!==e){const t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=Tt[e]),this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}this.currentDepthFunc=e}}scissor(e,t,s,i){const r=this._tempVec4.set(e,t,s,i);if(!1===this.currentScissor.equals(r)){const{gl:e}=this;e.scissor(r.x,r.y,r.z,r.w),this.currentScissor.copy(r)}}viewport(e,t,s,i){const r=this._tempVec4.set(e,t,s,i);if(!1===this.currentViewport.equals(r)){const{gl:e}=this;e.viewport(r.x,r.y,r.z,r.w),this.currentViewport.copy(r)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,s){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===s||(this.gl.stencilFunc(e,t,s),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=s)}setStencilOp(e,t,s){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===s||(this.gl.stencilOp(e,t,s),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=s)}setMaterial(e,t,s){const{gl:i}=this;2===e.side?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let r=1===e.side;t&&(r=!r),this.setFlipSided(r),1===e.blending&&!1===e.transparent?this.setBlending(0):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const n=e.stencilWrite;if(this.setStencilTest(n),n&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage&&this.backend.renderer.currentSamples>0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),s>0&&this.currentClippingPlanes!==s){const e=12288;for(let t=0;t<8;t++)t<s?this.enable(e+t):this.disable(e+t)}}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===s||(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const s=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(s.bindVertexArray(e),null!==t&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0)}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:s,currentBoundFramebuffers:i}=this;return i[e]!==t&&(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:s}=this;let i=[],r=!1;if(null!==e.textures){i=this.currentDrawbuffers.get(t),void 0===i&&(i=[],this.currentDrawbuffers.set(t,i));const n=e.textures;if(i.length!==n.length||i[0]!==s.COLOR_ATTACHMENT0){for(let e=0,t=n.length;e<t;e++)i[e]=s.COLOR_ATTACHMENT0+e;i.length=n.length,r=!0}}else i[0]!==s.BACK&&(i[0]=s.BACK,r=!0);r&&s.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:s,maxTextures:i}=this;void 0===e&&(e=t.TEXTURE0+i-1),s!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,s){const{gl:i,currentTextureSlot:r,currentBoundTextures:n,maxTextures:a}=this;void 0===s&&(s=null===r?i.TEXTURE0+a-1:r);let o=n[s];void 0===o&&(o={type:void 0,texture:void 0},n[s]=o),o.type===e&&o.texture===t||(r!==s&&(i.activeTexture(s),this.currentTextureSlot=s),i.bindTexture(e,t),o.type=e,o.texture=t)}bindBufferBase(e,t,s){const{gl:i}=this,r=`${e}-${t}`;return this.currentBoundBufferBases[r]!==s&&(i.bindBufferBase(e,t,s),this.currentBoundBufferBases[r]=s,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:s}=this,i=s[t];void 0!==i&&void 0!==i.type&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}getParameter(e){const{gl:t,parameters:s}=this;return void 0!==s[e]?s[e]:t.getParameter(e)}pixelStorei(e,t){const{gl:s,parameters:i}=this;i[e]!==t&&(s.pixelStorei(e,t),i[e]=t)}}class zv{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=""){const{gl:s,extensions:i}=this;let r;const n=Wt.getTransfer(t);if(e===j)return s.UNSIGNED_BYTE;if(e===Q)return s.UNSIGNED_SHORT_4_4_4_4;if(e===Z)return s.UNSIGNED_SHORT_5_5_5_1;if(e===ee)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===te)return s.UNSIGNED_INT_10F_11F_11F_REV;if(e===$)return s.BYTE;if(e===W)return s.SHORT;if(e===H)return s.UNSIGNED_SHORT;if(e===q)return s.INT;if(e===X)return s.UNSIGNED_INT;if(e===Y)return s.FLOAT;if(e===K)return s.HALF_FLOAT;if(e===se)return s.ALPHA;if(e===ie)return s.RGB;if(e===re)return s.RGBA;if(e===ne)return s.DEPTH_COMPONENT;if(e===ae)return s.DEPTH_STENCIL;if(e===oe)return s.RED;if(e===he)return s.RED_INTEGER;if(e===le)return s.RG;if(e===ue)return s.RG_INTEGER;if(e===ce)return s.RGBA_INTEGER;if(e===de||e===pe||e===me||e===ge)if(n===Ke){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===de)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===pe)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===me)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===ge)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===de)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===pe)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===me)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===ge)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===fe||e===ye||e===be||e===_e){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(e===fe)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===ye)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===be)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===_e)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===xe||e===ve||e===Te||e===Se||e===we||e===Me||e===Ne){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(e===xe||e===ve)return n===Ke?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===Te)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===Se)return r.COMPRESSED_R11_EAC;if(e===we)return r.COMPRESSED_SIGNED_R11_EAC;if(e===Me)return r.COMPRESSED_RG11_EAC;if(e===Ne)return r.COMPRESSED_SIGNED_RG11_EAC}if(e===Ae||e===Ee||e===Re||e===Ce||e===Pe||e===Be||e===Fe||e===Le||e===De||e===Ie||e===Oe||e===Ue||e===ke||e===ze){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===Ae)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Ee)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Re)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Ce)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Pe)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===Be)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Fe)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Le)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===De)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Ie)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Oe)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Ue)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===ke)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===ze)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===Ve){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===Ve)return n===Ke?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(e===Ge||e===je||e===$e||e===We){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===Ge)return r.COMPRESSED_RED_RGTC1_EXT;if(e===je)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===$e)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===We)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===J?s.UNSIGNED_INT_24_8:void 0!==s[e]?s[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((s,i)=>{!function r(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void i();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),s()):requestAnimationFrame(r)}()})}}let Vv,Gv,jv,$v=!1;class Wv{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===$v&&(this._init(),$v=!0)}_init(){const e=this.gl;Vv={[L]:e.REPEAT,[D]:e.CLAMP_TO_EDGE,[I]:e.MIRRORED_REPEAT},Gv={[O]:e.NEAREST,[U]:e.NEAREST_MIPMAP_NEAREST,[k]:e.NEAREST_MIPMAP_LINEAR,[z]:e.LINEAR,[V]:e.LINEAR_MIPMAP_NEAREST,[G]:e.LINEAR_MIPMAP_LINEAR},jv={[Ze]:e.NEVER,[nt]:e.ALWAYS,[Je]:e.LESS,[tt]:e.LEQUAL,[et]:e.EQUAL,[rt]:e.GEQUAL,[st]:e.GREATER,[it]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,r,n=!1){const{gl:a,extensions:o}=this;if(null!==e){if(void 0!==a[e])return a[e];bt("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let h=null;i&&(h=o.get("EXT_texture_norm16"),h||bt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let l=t;if(t===a.RED&&(s===a.FLOAT&&(l=a.R32F),s===a.HALF_FLOAT&&(l=a.R16F),s===a.UNSIGNED_BYTE&&(l=a.R8),s===a.BYTE&&(l=a.R8_SNORM),s===a.UNSIGNED_SHORT&&h&&(l=h.R16_EXT),s===a.SHORT&&h&&(l=h.R16_SNORM_EXT)),t===a.RED_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.R8UI),s===a.UNSIGNED_SHORT&&(l=a.R16UI),s===a.UNSIGNED_INT&&(l=a.R32UI),s===a.BYTE&&(l=a.R8I),s===a.SHORT&&(l=a.R16I),s===a.INT&&(l=a.R32I)),t===a.RG&&(s===a.FLOAT&&(l=a.RG32F),s===a.HALF_FLOAT&&(l=a.RG16F),s===a.UNSIGNED_BYTE&&(l=a.RG8),s===a.BYTE&&(l=a.RG8_SNORM),s===a.UNSIGNED_SHORT&&h&&(l=h.RG16_EXT),s===a.SHORT&&h&&(l=h.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.RG8UI),s===a.UNSIGNED_SHORT&&(l=a.RG16UI),s===a.UNSIGNED_INT&&(l=a.RG32UI),s===a.BYTE&&(l=a.RG8I),s===a.SHORT&&(l=a.RG16I),s===a.INT&&(l=a.RG32I)),t===a.RGB){const e=n?Ye:Wt.getTransfer(r);s===a.FLOAT&&(l=a.RGB32F),s===a.HALF_FLOAT&&(l=a.RGB16F),s===a.UNSIGNED_BYTE&&(l=e===Ke?a.SRGB8:a.RGB8),s===a.BYTE&&(l=a.RGB8_SNORM),s===a.UNSIGNED_SHORT&&h&&(l=h.RGB16_EXT),s===a.SHORT&&h&&(l=h.RGB16_SNORM_EXT),s===a.UNSIGNED_SHORT_5_6_5&&(l=a.RGB565),s===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1),s===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGB4),s===a.UNSIGNED_INT_5_9_9_9_REV&&(l=a.RGB9_E5),s===a.UNSIGNED_INT_10F_11F_11F_REV&&(l=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.RGB8UI),s===a.UNSIGNED_SHORT&&(l=a.RGB16UI),s===a.UNSIGNED_INT&&(l=a.RGB32UI),s===a.BYTE&&(l=a.RGB8I),s===a.SHORT&&(l=a.RGB16I),s===a.INT&&(l=a.RGB32I)),t===a.RGBA){const e=n?Ye:Wt.getTransfer(r);s===a.FLOAT&&(l=a.RGBA32F),s===a.HALF_FLOAT&&(l=a.RGBA16F),s===a.UNSIGNED_BYTE&&(l=e===Ke?a.SRGB8_ALPHA8:a.RGBA8),s===a.BYTE&&(l=a.RGBA8_SNORM),s===a.UNSIGNED_SHORT&&h&&(l=h.RGBA16_EXT),s===a.SHORT&&h&&(l=h.RGBA16_SNORM_EXT),s===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGBA4),s===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.RGBA8UI),s===a.UNSIGNED_SHORT&&(l=a.RGBA16UI),s===a.UNSIGNED_INT&&(l=a.RGBA32UI),s===a.BYTE&&(l=a.RGBA8I),s===a.SHORT&&(l=a.RGBA16I),s===a.INT&&(l=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(s===a.UNSIGNED_SHORT&&(l=a.DEPTH_COMPONENT16),s===a.UNSIGNED_INT&&(l=a.DEPTH_COMPONENT24),s===a.FLOAT&&(l=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&s===a.UNSIGNED_INT_24_8&&(l=a.DEPTH24_STENCIL8),l!==a.R16F&&l!==a.R32F&&l!==a.RG16F&&l!==a.RG32F&&l!==a.RGBA16F&&l!==a.RGBA32F||o.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this,{state:n}=this.backend,a=Wt.getPrimaries(Wt.workingColorSpace),o=t.colorSpace===He?null:Wt.getPrimaries(t.colorSpace),h=t.colorSpace===He||a===o?s.NONE:s.BROWSER_DEFAULT_WEBGL;n.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,h),s.texParameteri(e,s.TEXTURE_WRAP_S,Vv[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,Vv[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,Vv[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,Gv[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,u=t.minFilter===z&&l?G:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,Gv[u]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,jv[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===O)return;if(t.minFilter!==k&&t.minFilter!==G)return;if(t.type===Y&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,r=this.getGLTextureType(e);let n=i[r];void 0===n&&(n=t.createTexture(),s.state.bindTexture(r,n),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=n),s.set(e,{textureGPU:n,glTextureType:r})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:r,width:n,height:a,depth:o}=t,h=i.utils.convert(e.format,e.colorSpace),l=i.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,h,l,e.normalized,e.colorSpace,e.isVideoTexture),c=s.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,c),this.setTextureParameters(d,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,r,u,n,a,o):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,r,u,n,a,o):e.isVideoTexture||s.texStorage2D(d,r,u,n,a),i.set(e,{textureGPU:c,glTextureType:d,glFormat:h,glType:l,glInternalFormat:u})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{state:r}=i,{textureGPU:n,glTextureType:a,glFormat:o,glType:h}=i.get(t),{width:l,height:u}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(a,n),r.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(a,0,0,0,l,u,o,h,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:r}=t,{textureGPU:n,glTextureType:a,glFormat:o,glType:h,glInternalFormat:l}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t<i.length;t++){const n=i[t];e.isCompressedArrayTexture?e.format!==s.RGBA?null!==o?s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,o,n.data):bt("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):s.texSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,o,h,n.data):null!==o?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,o,n.data):bt("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const n=t.images,a=e.mipmaps;for(let e=0;e<6;e++){const t=Hv(n[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,i,r,o,h,t);for(let t=0;t<a.length;t++){const i=Hv(a[t].images[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,i.width,i.height,o,h,i)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const i=t.image;if(e.layerUpdates.size>0){const t=Mn(i.width,i.height,e.format,e.type);for(const r of e.layerUpdates){const e=i.data.subarray(r*t/i.data.BYTES_PER_ELEMENT,(r+1)*t/i.data.BYTES_PER_ELEMENT);s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,r,i.width,i.height,1,o,h,e)}e.clearLayerUpdates()}else s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,i.width,i.height,i.depth,o,h,i.data)}else if(e.isData3DTexture){const e=t.image;s.texSubImage3D(s.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,h,e.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(a,0,l,o,h,t.image);else if(e.isHTMLTexture)"function"==typeof s.texElementImage2D&&s.texElementImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,t.image);else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e<t;e++){const t=n[e],i=Hv(t);s.texSubImage2D(a,e,0,0,t.width,t.height,o,h,i)}else{const e=Hv(t.image);s.texSubImage2D(a,0,0,0,i,r,o,h,e)}}}generateMipmaps(e){const{gl:t,backend:s}=this,{textureGPU:i,glTextureType:r}=s.get(e);s.state.bindTexture(r,i),t.generateMipmap(r)}deallocateRenderBuffers(e){const{gl:t,backend:s}=this;if(e){const i=s.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const e in i.framebuffers)t.deleteFramebuffer(i.framebuffers[e]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let e=0;e<i.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(i.msaaRenderbuffers[e]);delete i.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:s,backend:i}=this,{textureGPU:r,renderTarget:n}=i.get(e);this.deallocateRenderBuffers(n),!1===t&&s.deleteTexture(r),i.delete(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){const{gl:a,backend:o}=this,{state:h}=this.backend,{textureGPU:l,glTextureType:u,glType:c,glFormat:d}=o.get(t);let p,m,g,f,y,b,_,x,v;h.bindTexture(u,l);const T=e.isCompressedTexture?e.mipmaps[n]:e.image;if(null!==s)p=s.max.x-s.min.x,m=s.max.y-s.min.y,g=s.isBox3?s.max.z-s.min.z:1,f=s.min.x,y=s.min.y,b=s.isBox3?s.min.z:0;else{const t=Math.pow(2,-r);p=Math.floor(T.width*t),m=Math.floor(T.height*t),g=e.isDataArrayTexture||e.isArrayTexture?T.depth:e.isData3DTexture?Math.floor(T.depth*t):1,f=0,y=0,b=0}null!==i?(_=i.x,x=i.y,v=i.z):(_=0,x=0,v=0),h.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),h.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),h.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const S=h.getParameter(a.UNPACK_ROW_LENGTH),w=h.getParameter(a.UNPACK_IMAGE_HEIGHT),M=h.getParameter(a.UNPACK_SKIP_PIXELS),N=h.getParameter(a.UNPACK_SKIP_ROWS),A=h.getParameter(a.UNPACK_SKIP_IMAGES);h.pixelStorei(a.UNPACK_ROW_LENGTH,T.width),h.pixelStorei(a.UNPACK_IMAGE_HEIGHT,T.height),h.pixelStorei(a.UNPACK_SKIP_PIXELS,f),h.pixelStorei(a.UNPACK_SKIP_ROWS,y),h.pixelStorei(a.UNPACK_SKIP_IMAGES,b);const E=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,R=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const s=o.get(e),i=o.get(t),u=o.get(s.renderTarget),c=o.get(i.renderTarget),d=u.framebuffers[s.cacheKey],T=c.framebuffers[i.cacheKey];h.bindFramebuffer(a.READ_FRAMEBUFFER,d),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,T);for(let e=0;e<g;e++)E&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,s.textureGPU,r,b+e),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,l,n,v+e)),a.blitFramebuffer(f,y,p,m,_,x,p,m,a.DEPTH_BUFFER_BIT,a.NEAREST);h.bindFramebuffer(a.READ_FRAMEBUFFER,null),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else if(0!==r||e.isRenderTargetTexture||o.has(e)){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer()),h.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<g;e++)E?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,t.textureGPU,r,b+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t.textureGPU,r),R?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,l,n,v+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,l,n),0!==r?a.blitFramebuffer(f,y,p,m,_,x,p,m,a.COLOR_BUFFER_BIT,a.NEAREST):R?a.copyTexSubImage3D(u,n,_,x,v+e,f,y,p,m):a.copyTexSubImage2D(u,n,_,x,f,y,p,m);h.bindFramebuffer(a.READ_FRAMEBUFFER,null),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else R?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(u,n,_,x,v,p,m,g,d,c,T.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(u,n,_,x,v,p,m,g,d,T.data):a.texSubImage3D(u,n,_,x,v,p,m,g,d,c,T):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,n,_,x,p,m,d,c,T.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,n,_,x,T.width,T.height,d,T.data):a.texSubImage2D(a.TEXTURE_2D,n,_,x,p,m,d,c,T);h.pixelStorei(a.UNPACK_ROW_LENGTH,S),h.pixelStorei(a.UNPACK_IMAGE_HEIGHT,w),h.pixelStorei(a.UNPACK_SKIP_PIXELS,M),h.pixelStorei(a.UNPACK_SKIP_ROWS,N),h.pixelStorei(a.UNPACK_SKIP_IMAGES,A),0===n&&t.generateMipmaps&&a.generateMipmap(u),h.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:r}=this.backend,{textureGPU:n}=this.backend.get(e),{x:a,y:o,z:h,w:l}=s,u=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(u){const s=0!==a||0!==o;let u,d;if(!0===e.isDepthTexture?(u=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(u|=i.STENCIL_BUFFER_BIT)):(u=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),s){const e=this.backend.get(t.renderTarget),s=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,s),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=c-o-l;i.blitFramebuffer(a,p,a+h,p+l,a,p,a+h,p+l,u,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,s),r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,p,h,l),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,n,0),i.blitFramebuffer(0,0,h,l,0,0,h,l,u,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,c-l-o,h,l),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,s,i=!1){const{gl:r}=this,n=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:h,width:l,height:u}=n;if(r.bindRenderbuffer(r.RENDERBUFFER,e),o&&!h){let t=r.DEPTH_COMPONENT24;if(!0===i){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,n.samples,t,l,u)}else s>0?(a&&a.isDepthTexture&&a.type===r.FLOAT&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,s,t,l,u)):r.renderbufferStorage(r.RENDERBUFFER,t,l,u);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else o&&h&&(s>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,s,r.DEPTH24_STENCIL8,l,u):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,l,u),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e));r.bindRenderbuffer(r.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,s,i,r,n){const{backend:a,gl:o}=this,{textureGPU:h,glFormat:l,glType:u}=this.backend.get(e),c=o.createFramebuffer();a.state.bindFramebuffer(o.READ_FRAMEBUFFER,c);const d=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,d,h,0);const p=this._getTypedArrayType(u),m=i*r*this._getBytesPerTexel(u,l),g=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,g),o.bufferData(o.PIXEL_PACK_BUFFER,m,o.STREAM_READ),o.readPixels(t,s,i,r,l,u,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new p(m/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,g),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteFramebuffer(c),f}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:s}=this;let i=0;return e===s.UNSIGNED_BYTE&&(i=1),e!==s.UNSIGNED_SHORT_4_4_4_4&&e!==s.UNSIGNED_SHORT_5_5_5_1&&e!==s.UNSIGNED_SHORT_5_6_5&&e!==s.UNSIGNED_SHORT&&e!==s.HALF_FLOAT||(i=2),e!==s.UNSIGNED_INT&&e!==s.FLOAT||(i=4),t===s.RGBA?4*i:t===s.RGB?3*i:t===s.ALPHA?i:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function Hv(e){return e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas?e:e.data}class qv{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class Xv{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}getUniformBufferLimit(){if(null!==this.maxUniformBlockSize)return this.maxUniformBlockSize;const e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}}const Yv={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class Kv{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:s,mode:i,object:r,type:n,info:a,index:o}=this;0!==o?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),a.update(r,t,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:a,object:o,info:h}=this;0!==s&&(0!==a?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),h.update(o,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:a}=this;if(0===s)return;const o=i.get("WEBGL_multi_draw");if(null===o)for(let i=0;i<s;i++)this.render(e[i],t[i]);else{0!==this.index?o.multiDrawElementsWEBGL(r,t,0,this.type,e,0,s):o.multiDrawArraysWEBGL(r,e,0,t,0,s);let i=0;for(let e=0;e<s;e++)i+=t[e];a.update(n,i,1)}}}class Qv{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return void 0===t&&(bt(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class Zv extends Qv{constructor(e,t,s=2048){if(super(s),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return bt("EXT_disjoint_timer_query not supported; timestamps will be disabled."),void(this.trackTimestamp=!1);this.queries=[];for(let t=0;t<this.maxQueries;t++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return xt(`WebGLTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const s=this.queries[t];if(s)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,s),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){_t("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){_t("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[t,s]of this.queryOffsets){if("ended"===this.queryStates.get(s)){const i=this.queries[s];e.set(t,this.resolveQuery(i))}}if(0===e.size)return this.lastValue;const t={},s=[];for(const[i,r]of e){const e=i.match(/^(.*):f(\d+)$/),n=parseInt(e[2]);!1===s.includes(n)&&s.push(n),void 0===t[n]&&(t[n]=0);const a=await r;this.timestamps.set(i,a),t[n]+=a}const i=t[s[s.length-1]];return this.lastValue=i,this.frames=s,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return _t("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed)return void t(this.lastValue);let s,i=!1;const r=e=>{i||(i=!0,s&&(clearTimeout(s),s=null),t(e))},n=()=>{if(this.isDisposed)r(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void r(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(s=setTimeout(n,1));const i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(i)/1e6)}catch(e){_t("Error checking query:",e),t(this.lastValue)}};n()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class Jv extends Fv{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,s={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=void 0!==t.context?t.context:e.domElement.getContext("webgl2",s);function r(t){t.preventDefault();const s={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(s)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=i,this.extensions=new qv(this),this.capabilities=new Xv(this),this.attributeUtils=new Uv(this),this.textureUtils=new Wv(this),this.bufferRenderer=new Kv(this),this.state=new kv(this),this.utils=new zv(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),t.reversedDepthBuffer&&(this.extensions.has("EXT_clip_control")?e.reversedDepthBuffer=!0:(bt("WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return ht}async getArrayBufferAsync(e,t=null,s=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,s,i)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,s=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),null!==s){const t=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:s,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&bt("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new Zv(this.gl,e,2048));const s=this.timestampQueryPool[e];null!==s.allocateQueriesForContext(t)&&s.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,s=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:s}=this.getDrawingBufferSize();t.viewport(0,0,e,s)}if(e.scissor)this.updateScissor(e);else{const{width:e,height:s}=this.getDrawingBufferSize();t.scissor(0,0,e,s)}this.initTimestampQuery(ct,this.getTimestampUID(e)),s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext;s.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e<a.length;e++){const t=a[e];t.generateMipmaps&&this.generateMipmaps(t)}if(this._currentContext=r,this._resolveRenderTarget(e),null!==r){if(this._setFramebuffer(r),r.viewport)this.updateViewport(r);else{const{width:e,height:t}=this.getDrawingBufferSize();s.viewport(0,0,e,t)}if(r.scissor)this.updateScissor(r);else{const{width:e,height:t}=this.getDrawingBufferSize();s.scissor(0,0,e,t)}}this.prepareTimestampBuffer(ct,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const e=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const n=()=>{let a=0;for(let t=0;t<s.length;t++){const n=s[t];null!==n&&(r.getQueryParameter(n,r.QUERY_RESULT_AVAILABLE)&&(0===r.getQueryParameter(n,r.QUERY_RESULT)&&e.add(i[t]),s[t]=null,r.deleteQuery(n),a++))}a<s.length?requestAnimationFrame(n):t.occluded=e};n()}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:s,y:i,width:r,height:n}=e.viewportValue;t.viewport(s,e.height-n-i,r,n)}updateScissor(e){const{state:t}=this,{x:s,y:i,width:r,height:n}=e.scissorValue;t.scissor(s,e.height-n-i,r,n)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,s,i=null,r=!0,n=!0){const{gl:a,renderer:o}=this;if(null===i){i={textures:null,clearColorValue:this.getClearColor()}}let h=0;if(e&&(h|=a.COLOR_BUFFER_BIT),t&&(h|=a.DEPTH_BUFFER_BIT),s&&(h|=a.STENCIL_BUFFER_BIT),0!==h){let l;l=i.clearColorValue?i.clearColorValue:this.getClearColor();const u=o.getClearDepth(),c=o.getClearStencil();if(t&&this.state.setDepthMask(!0),null===i.textures)a.clearColor(l.r,l.g,l.b,l.a),a.clear(h);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++)0===e?a.clearBufferfv(a.COLOR,e,[l.r,l.g,l.b,l.a]):a.clearBufferfv(a.COLOR,e,[0,0,0,1]);t&&s?a.clearBufferfi(a.DEPTH_STENCIL,0,u,c):t?a.clearBufferfv(a.DEPTH,0,[u]):s&&a.clearBufferiv(a.STENCIL,0,[c]),r&&n&&this._resolveRenderTarget(i)}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(ut,this.getTimestampUID(e))}compute(e,t,s,i,r=null){const{state:n,gl:a}=this;!1===this.discard&&(n.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformBuffers:h,attributes:l}=this.get(i),u=this._getVaoKey(l),c=this.vaoCache[u];void 0===c?this.vaoCache[u]=this._createVao(l):n.setVertexState(c),n.useProgram(o),this._bindUniforms(s);const d=this._getTransformFeedback(h);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,d),a.beginTransformFeedback(a.POINTS),r=null!==r?r:t.count,Array.isArray(r)?(xt("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute&&(xt("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),r=t.count),l[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,r):a.drawArrays(a.POINTS,0,r),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let e=0;e<h.length;e++){const t=h[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const{state:t,gl:s}=this;this.discard=!1,t.disable(s.RASTERIZER_DISCARD),this.prepareTimestampBuffer(ut,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}_draw(e,t,s,i,r,n){if(e.isBatchedMesh)if(!1===this.hasFeature("WEBGL_multi_draw")){const{gl:s}=this,i=s.getUniformLocation(n,"nodeUniformDrawId"),r=e._multiDrawStarts,a=e._multiDrawCounts,o=e._multiDrawCount;for(let e=0;e<o;e++)s.uniform1ui(i,e),t.render(r[e],a[e])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else r>1?t.renderInstances(s,i,r):t.render(s,i)}draw(e){const{object:t,pipeline:s,material:i,context:r,hardwareClippingPlanes:n}=e,{programGPU:a}=this.get(s),{gl:o,state:h}=this,l=this.get(r),u=e.getDrawParameters();if(null===u)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinant()<0;h.setMaterial(i,c,n),null!==r.mrt&&null!==r.textures&&h.setMRTBlending(r.textures,r.mrt,i),h.useProgram(a);const d=e.getAttributes(),p=this.get(d);let m=p.vaoGPU;if(void 0===m){const e=this._getVaoKey(d);m=this.vaoCache[e],void 0===m&&(m=this._createVao(d),this.vaoCache[e]=m,p.vaoGPU=m)}const g=e.getIndex(),f=null!==g?this.get(g).bufferGPU:null;h.setVertexState(m,f);const y=l.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}const b=this.bufferRenderer;t.isPoints?b.mode=o.POINTS:t.isLineSegments?b.mode=o.LINES:t.isLine?b.mode=o.LINE_STRIP:t.isLineLoop?b.mode=o.LINE_LOOP:!0===i.wireframe?(h.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=o.LINES):b.mode=o.TRIANGLES;const{vertexCount:_,instanceCount:x}=u;let{firstVertex:v}=u;if(b.object=t,null!==g){v*=g.array.BYTES_PER_ELEMENT;const e=this.get(g);b.index=g.count,b.type=e.type}else b.index=0;if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const s=this.get(e.camera),i=e.camera.cameras,r=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===s.indexesGPU||s.indexesGPU.length!==i.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let s=0,r=i.length;s<r;s++){const i=o.createBuffer();e[0]=s,o.bindBuffer(o.UNIFORM_BUFFER,i),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(i)}s.indexesGPU=t}let n=0;e:for(const t of e.getBindings())for(const e of t.bindings){if(e===r)break e;(e.isUniformsGroup||e.isUniformBuffer)&&n++}const l=this.renderer.getPixelRatio(),u=this._currentContext.renderTarget,c=this._isRenderCameraDepthArray(this._currentContext),d=this._currentContext.activeCubeFace;if(c){const e=this.get(u.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=u;for(let e=0,s=i.length;e<s;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1,!1);this.renderer._activeCubeFace=d,this._currentContext.activeCubeFace=d}}for(let r=0,u=i.length;r<u;r++){const u=i[r];if(t.layers.test(u.layers)){c&&(this.renderer._activeCubeFace=r,this._currentContext.activeCubeFace=r,this._setFramebuffer(this._currentContext));const i=u.viewport;if(void 0!==i){const t=i.x*l,s=i.y*l,r=i.width*l,n=i.height*l;h.viewport(Math.floor(t),Math.floor(e.context.height-n-s),Math.floor(r),Math.floor(n))}h.bindBufferBase(o.UNIFORM_BUFFER,n,s.indexesGPU[r]),this._draw(t,b,v,_,x,a)}this._currentContext.activeCubeFace=d,this.renderer._activeCubeFace=d}}else this._draw(t,b,v,_,x,a)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}updateSampler(){return""}createNodeBuilder(e,t){return new Cv(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,r="fragment"===s?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:n}=i,a=s.createProgram(),o=this.get(r).shaderGPU,h=this.get(n).shaderGPU;if(s.attachShader(a,o),s.attachShader(a,h),s.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:o,vertexShader:h}),null!==t&&this.parallel){const r=new Promise(t=>{const r=this.parallel,n=()=>{s.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(n)};n()});return void t.push(r)}this._completeCompile(e,i)}_handleSource(e,t){const s=e.split("\n"),i=[],r=Math.max(t-6,0),n=Math.min(t+6,s.length);for(let e=r;e<n;e++){const r=e+1;i.push(`${r===t?">":" "} ${r}: ${s[e]}`)}return i.join("\n")}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const n=/ERROR: 0:(\d+)/.exec(r);if(n){const i=parseInt(n[1]);return s.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=(i.getProgramInfoLog(e)||"").trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,s,t);else{const n=this._getShaderErrors(i,s,"vertex"),a=this._getShaderErrors(i,t,"fragment");_t("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+a)}else""!==r&&bt("WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,a,o),s.useProgram(n);const h=e.getBindings();this._setupBindings(h,n),this.set(t,{programGPU:n,pipeline:n})}createComputePipeline(e,t){const{state:s,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:n}=e,a=i.createProgram(),o=this.get(r).shaderGPU,h=this.get(n).shaderGPU,l=n.transforms,u=[],c=[];for(let e=0;e<l.length;e++){const t=l[e];u.push(t.varyingName),c.push(t.attributeNode)}i.attachShader(a,o),i.attachShader(a,h),i.transformFeedbackVaryings(a,u,i.SEPARATE_ATTRIBS),i.linkProgram(a),!1===i.getProgramParameter(a,i.LINK_STATUS)&&this._logProgramError(a,o,h),s.useProgram(a),this._setupBindings(t,a);const d=n.attributes,p=[],m=[];for(let e=0;e<d.length;e++){const t=d[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER)}for(let e=0;e<c.length;e++){const t=c[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER);const s=this.get(t);m.push(s)}this.set(e,{programGPU:a,transformBuffers:m,attributes:p})}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,s=0;for(const i of t){this.set(i,{textures:s,uniformBuffers:e});for(const t of i.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&s++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this;for(const s of e.bindings){const e=this.get(s);if(s.isUniformsGroup||s.isUniformBuffer){const i=s.buffer;let{bufferGPU:r}=this.get(i);void 0===r?(r=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,r),t.bufferData(t.UNIFORM_BUFFER,i.byteLength,t.DYNAMIC_DRAW),this.set(i,{bufferGPU:r})):t.bindBuffer(t.UNIFORM_BUFFER,r);const n=s.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,r),0===n.length)t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW);else{const e=pt(i),s=e?1:i.BYTES_PER_ELEMENT;for(let r=0,a=n.length;r<a;r++){const a=n[r],o=a.start*s,h=a.count*s,l=o*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,l,i,o,h)}}e.bufferGPU=r,this.set(s,e)}else if(s.isSampledTexture){const{textureGPU:t,glTextureType:i}=this.get(s.texture);e.textureGPU=t,e.glTextureType=i,this.set(s,e)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const s=this.get(e).bufferGPU,i=e.buffer,r=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,s),0===r.length)t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW);else{const e=pt(i),s=e?1:i.BYTES_PER_ELEMENT;for(let n=0,a=r.length;n<a;n++){const a=r[n],o=a.start*s,h=a.count*s,l=o*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,l,i,o,h)}}}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(Yv).filter(t=>Yv[t]===e),s=this.extensions;for(let e=0;e<t.length;e++)if(s.has(t[e]))return!0;return!1}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){this.textureUtils.copyTextureToTexture(e,t,s,i,r,n)}copyFramebufferToTexture(e,t,s){this.textureUtils.copyFramebufferToTexture(e,t,s)}hasCompatibility(e){return e===dt||super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:s}=this;this._setFramebuffer(e),s.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(null!==e.textures){const r=e.renderTarget,n=this.get(r),{samples:a,depthBuffer:o,stencilBuffer:h}=r,l=!0===r.isCubeRenderTarget,u=!0===r.isRenderTarget3D,c=r.depth>1,d=!0===r.isXRRenderTarget,p=!0===d&&!0===r._hasExternalTextures;let m=n.msaaFrameBuffer,g=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(r),_=qy(e);let x;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),x=n.cubeFramebuffers[_]):d&&!1===p?x=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),x=n.framebuffers[_]),void 0===x){x=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,x);const i=e.textures,o=[];if(l){n.cubeFramebuffers[_]=x;const{textureGPU:e}=this.get(i[0]),s=this.renderer._activeCubeFace,r=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+s,e,r)}else{n.framebuffers[_]=x;for(let s=0;s<i.length;s++){const n=i[s],o=this.get(n);o.renderTarget=e.renderTarget,o.cacheKey=_;const h=t.COLOR_ATTACHMENT0+s;if(r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,h,o.textureGPU,0,a,0,2);else if(u||c){const e=this.renderer._activeCubeFace,s=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,h,o.textureGPU,s,e)}else if(b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,h,t.TEXTURE_2D,o.textureGPU,0,a);else{const e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,h,t.TEXTURE_2D,o.textureGPU,e)}}}const d=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const s=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(s,e,0,b),n.xrDepthRenderbuffer=s,o.push(h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,d,t.RENDERBUFFER,s)}else if(null!==e.depthTexture){o.push(h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const s=this.get(e.depthTexture);if(s.renderTarget=e.renderTarget,s.cacheKey=_,r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,d,s.textureGPU,0,a,0,2);else if(p&&b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,d,t.TEXTURE_2D,s.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,d,s.textureGPU,0,e)}else if(e.depthTexture.isCubeTexture){const e=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_2D,s.textureGPU,0)}n.depthInvalidationArray=o}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,x);const i=this.renderer._activeCubeFace,r=this.get(e.depthTexture),n=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,n,r.textureGPU,0,i)}if((d||b||r.multiview)&&!0!==r._isOpaqueFramebuffer){s.bindFramebuffer(t.FRAMEBUFFER,x);const i=this.get(e.textures[0]);r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,i.textureGPU,0,a,0,2):b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0);const o=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const e=n.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,o,t.RENDERBUFFER,e)}else{const s=this.get(e.depthTexture);r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,s.textureGPU,0,a,0,2):b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,s.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,s.textureGPU,0)}}}if(a>0&&!1===b&&!r.multiview){if(void 0===m){const i=[];m=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,m);const r=[],l=e.textures;for(let s=0;s<l.length;s++){r[s]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,r[s]),i.push(t.COLOR_ATTACHMENT0+s);const n=e.textures[s],o=this.get(n);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,o.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+s,t.RENDERBUFFER,r[s])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),n.msaaFrameBuffer=m,n.msaaRenderbuffers=r,o&&void 0===g){g=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(g,e,a),n.depthRenderbuffer=g;const s=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;i.push(s)}n.invalidationArray=i}i=n.msaaFrameBuffer}else i=x;s.drawBuffers(e,x)}s.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let s=0;s<e.length;s++){t+=":"+this.get(e[s]).id}return t}_createVao(e){const{gl:t}=this,s=t.createVertexArray();t.bindVertexArray(s);for(let s=0;s<e.length;s++){const i=e[s],r=this.get(i);let n,a;t.bindBuffer(t.ARRAY_BUFFER,r.bufferGPU),t.enableVertexAttribArray(s),!0===i.isInterleavedBufferAttribute?(n=i.data.stride*r.bytesPerElement,a=i.offset*r.bytesPerElement):(n=0,a=0),r.isInteger?t.vertexAttribIPointer(s,i.itemSize,r.type,n,a):t.vertexAttribPointer(s,i.itemSize,r.type,i.normalized,n,a),i.isInstancedBufferAttribute&&!i.isInterleavedBufferAttribute?t.vertexAttribDivisor(s,i.meshPerAttribute):i.isInterleavedBufferAttribute&&i.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(s,i.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),s}_getTransformFeedback(e){let t="";for(let s=0;s<e.length;s++)t+=":"+e[s].id;let s=this.transformFeedbackCache[t];if(void 0!==s)return s;const{gl:i}=this;s=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,s);for(let t=0;t<e.length;t++){const s=e[t];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,t,s.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=s,s}_setupBindings(e,t){const s=this.gl;let i=0,r=0;for(const n of e)for(const e of n.bindings)if(e.isUniformsGroup||e.isUniformBuffer){const r=i++,n=s.getUniformBlockIndex(t,e.name);s.uniformBlockBinding(t,n,r)}else if(e.isSampledTexture){const i=r++,n=s.getUniformLocation(t,e.name);s.uniform1i(n,i)}}_bindUniforms(e){const{gl:t,state:s}=this;let i=0,r=0;for(const n of e)for(const e of n.bindings){const n=this.get(e);if(e.isUniformsGroup||e.isUniformBuffer){const e=i++;s.bindBufferBase(t.UNIFORM_BUFFER,e,n.bufferGPU)}else if(e.isSampledTexture){const e=r++;s.bindTexture(n.glTextureType,n.textureGPU,t.TEXTURE0+e)}}}_resolveRenderTarget(e){const{gl:t,state:s}=this,i=e.renderTarget;if(null!==e.textures&&i){const r=this.get(i);if(i.samples>0&&!1===this._useMultisampledExtension(i)){const n=r.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=r.msaaFrameBuffer,h=r.msaaRenderbuffers,l=e.textures,u=l.length>1;if(s.bindFramebuffer(t.READ_FRAMEBUFFER,o),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),u)for(let e=0;e<l.length;e++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);for(let s=0;s<l.length;s++){if(u){const{textureGPU:e}=this.get(l[s]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,h[s]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:s,y:i,width:r,height:n}=e.scissorValue,o=e.height-n-i;t.blitFramebuffer(s,o,s+r,o+n,s,o,s+r,o+n,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,t.NEAREST)}if(u)for(let e=0;e<l.length;e++){const{textureGPU:s}=this.get(l[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,h[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,s,0)}!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,r.invalidationArray)}else if(!1===i.resolveDepthBuffer&&r.framebuffers){const i=r.framebuffers[e.getCacheKey()];s.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,r.depthInvalidationArray)}}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const eT="point-list",tT="line-list",sT="line-strip",iT="triangle-list",rT="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},nT="never",aT="less",oT="equal",hT="less-equal",lT="greater",uT="not-equal",cT="greater-equal",dT="always",pT="store",mT="load",gT="clear",fT="ccw",yT="cw",bT="none",_T="back",xT="uint16",vT="uint32",TT="r8unorm",ST="r8snorm",wT="r8uint",MT="r8sint",NT="r16uint",AT="r16sint",ET="r16float",RT="rg8unorm",CT="rg8snorm",PT="rg8uint",BT="rg8sint",FT="r16unorm",LT="r16snorm",DT="r32uint",IT="r32sint",OT="r32float",UT="rg16uint",kT="rg16sint",zT="rg16float",VT="rgba8unorm",GT="rgba8unorm-srgb",jT="rgba8snorm",$T="rgba8uint",WT="rgba8sint",HT="bgra8unorm",qT="bgra8unorm-srgb",XT="rg16unorm",YT="rg16snorm",KT="rgb9e5ufloat",QT="rgb10a2unorm",ZT="rg11b10ufloat",JT="rg32uint",eS="rg32sint",tS="rg32float",sS="rgba16uint",iS="rgba16sint",rS="rgba16float",nS="rgba16unorm",aS="rgba16snorm",oS="rgba32uint",hS="rgba32sint",lS="rgba32float",uS="depth16unorm",cS="depth24plus",dS="depth24plus-stencil8",pS="depth32float",mS="depth32float-stencil8",gS="bc1-rgba-unorm",fS="bc1-rgba-unorm-srgb",yS="bc2-rgba-unorm",bS="bc2-rgba-unorm-srgb",_S="bc3-rgba-unorm",xS="bc3-rgba-unorm-srgb",vS="bc4-r-unorm",TS="bc4-r-snorm",SS="bc5-rg-unorm",wS="bc5-rg-snorm",MS="bc6h-rgb-ufloat",NS="bc6h-rgb-float",AS="bc7-rgba-unorm",ES="bc7-rgba-unorm-srgb",RS="etc2-rgb8unorm",CS="etc2-rgb8unorm-srgb",PS="etc2-rgb8a1unorm",BS="etc2-rgb8a1unorm-srgb",FS="etc2-rgba8unorm",LS="etc2-rgba8unorm-srgb",DS="eac-r11unorm",IS="eac-r11snorm",OS="eac-rg11unorm",US="eac-rg11snorm",kS="astc-4x4-unorm",zS="astc-4x4-unorm-srgb",VS="astc-5x4-unorm",GS="astc-5x4-unorm-srgb",jS="astc-5x5-unorm",$S="astc-5x5-unorm-srgb",WS="astc-6x5-unorm",HS="astc-6x5-unorm-srgb",qS="astc-6x6-unorm",XS="astc-6x6-unorm-srgb",YS="astc-8x5-unorm",KS="astc-8x5-unorm-srgb",QS="astc-8x6-unorm",ZS="astc-8x6-unorm-srgb",JS="astc-8x8-unorm",ew="astc-8x8-unorm-srgb",tw="astc-10x5-unorm",sw="astc-10x5-unorm-srgb",iw="astc-10x6-unorm",rw="astc-10x6-unorm-srgb",nw="astc-10x8-unorm",aw="astc-10x8-unorm-srgb",ow="astc-10x10-unorm",hw="astc-10x10-unorm-srgb",lw="astc-12x10-unorm",uw="astc-12x10-unorm-srgb",cw="astc-12x12-unorm",dw="astc-12x12-unorm-srgb",pw="clamp-to-edge",mw="repeat",gw="mirror-repeat",fw="linear",yw="nearest",bw="zero",_w="one",xw="src",vw="one-minus-src",Tw="src-alpha",Sw="one-minus-src-alpha",ww="dst",Mw="one-minus-dst",Nw="dst-alpha",Aw="one-minus-dst-alpha",Ew="src-alpha-saturated",Rw="constant",Cw="one-minus-constant",Pw="add",Bw="subtract",Fw="reverse-subtract",Lw="min",Dw="max",Iw=0,Ow=15,Uw="keep",kw="zero",zw="replace",Vw="invert",Gw="increment-clamp",jw="decrement-clamp",$w="increment-wrap",Ww="decrement-wrap",Hw="storage",qw="read-only-storage",Xw="write-only",Yw="read-only",Kw="read-write",Qw="non-filtering",Zw="comparison",Jw="float",eM="unfilterable-float",tM="depth",sM="sint",iM="uint",rM="2d",nM="3d",aM="2d",oM="2d-array",hM="cube",lM="3d",uM="all",cM="vertex",dM="instance",pM={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},mM={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class gM extends yv{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class fM extends uv{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let yM=0;class bM extends fM{constructor(e,t){super("StorageBuffer_"+yM++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Kn,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class _M extends xy{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:fw}),this.flipYSampler=e.createSampler({minFilter:yw}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar<uniform> flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d<f32>;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array<f32>;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube<f32>;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n"})}getTransferPipeline(e,t){const s=`${e}-${t=t||"2d-array"}`;let i=this.transferPipelines[s];return void 0===i&&(i=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[s]=i),i}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,a=this.device.createTexture({size:{width:r,height:n},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),o=this.getTransferPipeline(i,e.textureBindingViewDimension),h=this.getTransferPipeline(i,a.textureBindingViewDimension),l=this.device.createCommandEncoder({}),u=(e,t,s,i,r,n)=>{const a=e.getBindGroupLayout(0),o=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t.createView({dimension:t.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:n?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),h=l.beginRenderPass({colorAttachments:[{view:i.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:r,arrayLayerCount:1}),loadOp:gT,storeOp:pT}]});h.setPipeline(e),h.setBindGroup(0,o),h.draw(3,1,0,s),h.end()};u(o,e,s,a,0,!1),u(h,a,0,e,s,!0),this.device.queue.submit([l.finish()]),a.destroy()}generateMipmaps(e,t=null){const s=this.get(e),i=s.layers||this._mipmapCreateBundles(e),r=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(r,i),null===t&&this.device.queue.submit([r.finish()]),s.layers=i}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",s=this.getTransferPipeline(e.format,t),i=s.getBindGroupLayout(0),r=[];for(let n=1;n<e.mipLevelCount;n++)for(let a=0;a<e.depthOrArrayLayers;a++){const o=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:e.createView({dimension:t,baseMipLevel:n-1,mipLevelCount:1})},{binding:2,resource:{buffer:this.noFlipUniformBuffer}}]}),h={colorAttachments:[{view:e.createView({dimension:"2d",baseMipLevel:n,mipLevelCount:1,baseArrayLayer:a,arrayLayerCount:1}),loadOp:gT,storeOp:pT}]},l=this.device.createRenderBundleEncoder({colorFormats:[e.format]});l.setPipeline(s),l.setBindGroup(0,o),l.draw(3,1,0,a),r.push({renderBundles:[l.finish()],passDescriptor:h})}return r}_mipmapRunBundles(e,t){const s=t.length;for(let i=0;i<s;i++){const s=t[i],r=e.beginRenderPass(s.passDescriptor);r.executeBundles(s.renderBundles),r.end()}}}const xM={[Ze]:"never",[Je]:"less",[et]:"equal",[tt]:"less-equal",[st]:"greater",[rt]:"greater-equal",[nt]:"always",[it]:"not-equal"},vM=[0,1,3,2,4,5];class TM{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,s=e.minFilter+"-"+e.magFilter+"-"+e.wrapS+"-"+e.wrapT+"-"+(e.wrapR||"0")+"-"+e.anisotropy+"-"+(e.compareFunction||0);let i=this._samplerCache.get(s);if(void 0===i){const r={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};e.isDepthTexture&&null===e.compareFunction&&(r.magFilter=yw,r.minFilter=yw,r.mipmapFilter=yw),r.magFilter===fw&&r.minFilter===fw&&r.mipmapFilter===fw&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&t.hasCompatibility(dt)&&(r.compare=xM[e.compareFunction]);i={sampler:t.device.createSampler(r),usedTimes:0},this._samplerCache.set(s,i)}const r=t.get(e);if(r.sampler!==i.sampler){if(void 0!==r.sampler){const e=this._samplerCache.get(r.samplerKey);e.usedTimes--,0===e.usedTimes&&this._samplerCache.delete(r.samplerKey)}r.samplerKey=s,r.sampler=i.sampler,i.usedTimes++}return s}createDefaultTexture(e){let t;const s=SM(e,this.backend.device);t=e.isCubeTexture?this._getDefaultCubeTextureGPU(s):this._getDefaultTextureGPU(s),this.backend.get(e).texture=t}createTexture(e,t={}){const s=this.backend,i=s.get(e);if(i.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");if(e.isExternalTexture)return i.texture=e.sourceTexture,void(i.initialized=!0);void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:r,height:n,depth:a,levels:o}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const h=this._getDimension(e),l=e.internalFormat||t.format||SM(e,s.device);i.format=l;const{samples:u,primarySamples:c,isMSAA:d}=s.utils.getTextureSampleData(e);let p=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(p|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&l!==KT&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:r,height:n,depthOrArrayLayers:a},mipLevelCount:o,sampleCount:c,dimension:h,format:l,usage:p};if(void 0===l)return bt("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(m.textureBindingViewDimension=hM);try{i.texture=s.device.createTexture(m)}catch(t){return bt("WebGPURenderer: Failed to create texture with descriptor:",m),void this.createDefaultTexture(e)}if(d){const e=Object.assign({},m);e.label=e.label+"-msaa",e.sampleCount=u,e.mipLevelCount=1,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e,t=!1){const s=this.backend,i=s.get(e);void 0!==i.texture&&!1===t&&i.texture.destroy(),void 0!==i.msaaTexture&&i.msaaTexture.destroy(),s.delete(e)}generateMipmaps(e,t=null){const s=this.backend.get(e);this._generateMipmaps(s.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:s,height:i}=e.getDrawingBufferSize(),r=e.renderer.currentSamples,n=t.colorTexture,a=e.get(n);if(n.width===s&&n.height===i&&n.samples===r)return a.texture;let o=a.texture;return o&&o.destroy(),o=e.device.createTexture({label:"colorBuffer",size:{width:s,height:i,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.currentSamples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),n.source.width=s,n.source.height=i,n.samples=r,a.texture=o,o}getDepthBuffer(e=!0,t=!1){const s=this.backend,i=s.renderer.getCanvasTarget(),{width:r,height:n}=s.getDrawingBufferSize(),a=s.renderer.currentSamples,o=i.depthTexture;if(o.width===r&&o.height===n&&o.samples===a&&o.depth===e&&o.stencil===t)return s.get(o).texture;const h=s.get(o).texture;let l,u;if(t?(l=ae,u=!0===s.renderer.reversedDepthBuffer?Y:J):e&&(l=ne,u=!0===s.renderer.reversedDepthBuffer?Y:X),void 0!==h){if(o.image.width===r&&o.image.height===n&&o.format===l&&o.type===u&&o.samples===a)return h;this.destroyTexture(o)}return o.name="depthBuffer",o.format=l,o.type=u,o.image.width=r,o.image.height=n,o.samples=a,this.createTexture(o,{width:r,height:n}),s.get(o).texture}updateTexture(e,t){const s=this.backend.get(e),i=e.mipmaps,{textureDescriptorGPU:r}=s;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture)if(i.length>0)for(let t=0,n=i.length;t<n;t++){const n=i[t];this._copyBufferToTexture(n,s.texture,r,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,s.texture,r,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)if(e.layerUpdates&&e.layerUpdates.size>0){for(const i of e.layerUpdates)this._copyBufferToTexture(t.image,s.texture,r,i,e.flipY,i);e.clearLayerUpdates()}else for(let i=0;i<t.image.depth;i++)this._copyBufferToTexture(t.image,s.texture,r,i,e.flipY,i);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,s.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,s.texture,r);else if(e.isHTMLTexture){const t=this.backend.device,i=this.backend.renderer.domElement,n=e.image;if("function"!=typeof t.queue.copyElementImageToTexture)return;if(!s.hasPaintCallback)return s.hasPaintCallback=!0,void i.requestPaint();const a=r.size.width,o=r.size.height;t.queue.copyElementImageToTexture(n,a,o,{texture:s.texture}),e.flipY&&this._flipY(s.texture,r)}else if(i.length>0)for(let t=0,n=i.length;t<n;t++){const n=i[t];this._copyImageToTexture(n,s.texture,r,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,s.texture,r,0,e.flipY,e.premultiplyAlpha);s.version=e.version}}async copyTextureToBuffer(e,t,s,i,r,n){const a=this.backend.device,o=this.backend.get(e),h=o.texture,l=o.textureDescriptorGPU.format,u=this._getBytesPerTexel(l);let c=i*u;c=256*Math.ceil(c/256);const d=a.createBuffer({size:(r-1)*c+i*u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=a.createCommandEncoder();p.copyTextureToBuffer({texture:h,origin:{x:t,y:s,z:n}},{buffer:d,bytesPerRow:c},{width:i,height:r});const m=this._getTypedArrayType(l);a.queue.submit([p.finish()]),await d.mapAsync(GPUMapMode.READ);const g=d.getMappedRange().slice();return d.destroy(),new m(g)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const s=new ts;s.minFilter=O,s.magFilter=O,this.createTexture(s,{width:1,height:1,format:e}),this.defaultTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const s=new Br;s.minFilter=O,s.magFilter=O,this.createTexture(s,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=s}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,s){const i=e.images,r=e.mipmaps;for(let n=0;n<6;n++){const a=i[n],o=!0===e.flipY?vM[n]:n;a.isDataTexture?this._copyBufferToTexture(a.image,t,s,o,e.flipY):this._copyImageToTexture(a,t,s,o,e.flipY,e.premultiplyAlpha);for(let i=0;i<r.length;i++){const a=r[i].images[n];a.isDataTexture?this._copyBufferToTexture(a.image,t,s,o,e.flipY,0,i+1):this._copyImageToTexture(a,t,s,o,e.flipY,e.premultiplyAlpha,i+1)}}}_copyImageToTexture(e,t,s,i,r,n,a=0){const o=this.backend.device,h=a>0?e.width:s.size.width,l=a>0?e.height:s.size.height;try{o.queue.copyExternalImageToTexture({source:e,flipY:r},{texture:t,mipLevel:a,origin:{x:0,y:0,z:i},premultipliedAlpha:n},{width:h,height:l,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new _M(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,r,n=0,a=0){const o=this.backend.device,h=e.data,l=this._getBytesPerTexel(s.format),u=e.width*l;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:i}},h,{offset:e.width*e.height*l*n,bytesPerRow:u},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===r&&this._flipY(t,s,i)}_copyCompressedBufferToTexture(e,t,s){const i=this.backend.device,r=this._getBlockData(s.format),n=s.size.depthOrArrayLayers>1;for(let a=0;a<e.length;a++){const o=e[a],h=o.width,l=o.height,u=n?s.size.depthOrArrayLayers:1,c=Math.ceil(h/r.width)*r.byteLength,d=c*Math.ceil(l/r.height);for(let e=0;e<u;e++)i.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:e}},o.data,{offset:e*d,bytesPerRow:c,rowsPerImage:Math.ceil(l/r.height)},{width:Math.ceil(h/r.width)*r.width,height:Math.ceil(l/r.height)*r.height,depthOrArrayLayers:1})}}_getBlockData(e){return e===gS||e===fS?{byteLength:8,width:4,height:4}:e===yS||e===bS||e===_S||e===xS?{byteLength:16,width:4,height:4}:e===vS||e===TS?{byteLength:8,width:4,height:4}:e===SS||e===wS||e===MS||e===NS||e===AS||e===ES?{byteLength:16,width:4,height:4}:e===RS||e===CS||e===PS||e===BS?{byteLength:8,width:4,height:4}:e===FS||e===LS?{byteLength:16,width:4,height:4}:e===DS||e===IS?{byteLength:8,width:4,height:4}:e===OS||e===US||e===kS||e===zS?{byteLength:16,width:4,height:4}:e===VS||e===GS?{byteLength:16,width:5,height:4}:e===jS||e===$S?{byteLength:16,width:5,height:5}:e===WS||e===HS?{byteLength:16,width:6,height:5}:e===qS||e===XS?{byteLength:16,width:6,height:6}:e===YS||e===KS?{byteLength:16,width:8,height:5}:e===QS||e===ZS?{byteLength:16,width:8,height:6}:e===JS||e===ew?{byteLength:16,width:8,height:8}:e===tw||e===sw?{byteLength:16,width:10,height:5}:e===iw||e===rw?{byteLength:16,width:10,height:6}:e===nw||e===aw?{byteLength:16,width:10,height:8}:e===ow||e===hw?{byteLength:16,width:10,height:10}:e===lw||e===uw?{byteLength:16,width:12,height:10}:e===cw||e===dw?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=pw;return e===L?t=mw:e===I&&(t=gw),t}_convertFilterMode(e){let t=fw;return e!==O&&1004!==e&&e!==k||(t=yw),t}_getBytesPerTexel(e){return e===TT||e===ST||e===wT||e===MT?1:e===NT||e===AT||e===ET||e===RT||e===CT||e===PT||e===BT||e===FT||e===LT?2:e===DT||e===IT||e===OT||e===UT||e===kT||e===zT||e===VT||e===GT||e===jT||e===$T||e===WT||e===HT||e===qT||e===XT||e===YT||e===KT||e===QT||e===ZT||e===pS||e===cS||e===dS||e===mS?4:e===JT||e===eS||e===tS||e===sS||e===iS||e===rS||e===nS||e===aS?8:e===oS||e===hS||e===lS?16:void 0}_getTypedArrayType(e){return e===wT?Uint8Array:e===MT?Int8Array:e===TT?Uint8Array:e===ST?Int8Array:e===PT?Uint8Array:e===BT?Int8Array:e===RT?Uint8Array:e===CT?Int8Array:e===$T?Uint8Array:e===WT?Int8Array:e===VT||e===GT?Uint8Array:e===jT?Int8Array:e===NT?Uint16Array:e===AT?Int16Array:e===UT?Uint16Array:e===kT?Int16Array:e===sS?Uint16Array:e===iS?Int16Array:e===ET||e===zT||e===rS||e===FT?Uint16Array:e===LT?Int16Array:e===XT?Uint16Array:e===YT?Int16Array:e===nS?Uint16Array:e===aS?Int16Array:e===DT?Uint32Array:e===IT?Int32Array:e===OT?Float32Array:e===JT?Uint32Array:e===eS?Int32Array:e===tS?Float32Array:e===oS?Uint32Array:e===hS?Int32Array:e===lS?Float32Array:e===HT||e===qT?Uint8Array:e===QT||e===KT||e===ZT?Uint32Array:e===pS?Float32Array:e===cS||e===dS?Uint32Array:e===mS?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?nM:rM,t}}function SM(e,t){const s=e.format,i=e.type,r=e.normalized,n=e.colorSpace,a=Wt.getTransfer(n);let o,h=!1;if(r&&(h=t.features.has(pM.TextureFormatsTier1),!1===h&&bt("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(s){case de:case pe:o=a===Ke?fS:gS;break;case me:o=a===Ke?bS:yS;break;case ge:o=a===Ke?xS:_S;break;case Ge:o=vS;break;case je:o=TS;break;case $e:o=SS;break;case We:o=wS;break;case Ve:o=a===Ke?ES:AS;break;case ve:case xe:o=a===Ke?CS:RS;break;case Te:o=a===Ke?LS:FS;break;case Se:o=DS;break;case we:o=IS;break;case Me:o=OS;break;case Ne:o=US;break;case Ae:o=a===Ke?zS:kS;break;case Ee:o=a===Ke?GS:VS;break;case Re:o=a===Ke?$S:jS;break;case Ce:o=a===Ke?HS:WS;break;case Pe:o=a===Ke?XS:qS;break;case Be:o=a===Ke?KS:YS;break;case Fe:o=a===Ke?ZS:QS;break;case Le:o=a===Ke?ew:JS;break;case De:o=a===Ke?sw:tw;break;case Ie:o=a===Ke?rw:iw;break;case Oe:o=a===Ke?aw:nw;break;case Ue:o=a===Ke?hw:ow;break;case ke:o=a===Ke?uw:lw;break;case ze:o=a===Ke?dw:cw;break;case re:o=a===Ke?GT:VT;break;default:_t("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case re:switch(i){case $:o=jT;break;case W:o=h?aS:iS;break;case H:o=h?nS:sS;break;case X:o=oS;break;case q:o=hS;break;case j:o=a===Ke?GT:VT;break;case K:o=rS;break;case Y:o=lS;break;default:_t("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case ie:switch(i){case ee:o=KT;break;case te:o=ZT;break;default:_t("WebGPURenderer: Unsupported texture type with RGBFormat.",i)}break;case oe:switch(i){case $:o=ST;break;case W:o=h?LT:AT;break;case H:o=h?FT:NT;break;case X:o=DT;break;case q:o=IT;break;case j:o=TT;break;case K:o=ET;break;case Y:o=OT;break;default:_t("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case le:switch(i){case $:o=CT;break;case W:o=h?YT:kT;break;case H:o=h?XT:UT;break;case X:o=JT;break;case q:o=eS;break;case j:o=RT;break;case K:o=zT;break;case Y:o=tS;break;default:_t("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case ne:switch(i){case H:o=uS;break;case X:o=cS;break;case Y:o=pS;break;default:_t("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case ae:switch(i){case J:o=dS;break;case Y:t&&!1===t.features.has(pM.Depth32FloatStencil8)&&_t('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=mS;break;default:_t("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case he:switch(i){case q:o=IT;break;case X:o=DT;break;default:_t("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case ue:switch(i){case q:o=eS;break;case X:o=JT;break;default:_t("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case ce:switch(i){case q:o=hS;break;case X:o=oS;break;default:_t("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:_t("WebGPURenderer: Unsupported texture format.",s)}return o}const wM=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,MM=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,NM={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class AM extends wx{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(wM);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=MM.exec(s));)i.push({name:r[1],type:r[2]});const n=[];for(let e=0;e<i.length;e++){const{name:t,type:s}=i[e];let r=s;r.startsWith("ptr")?r="pointer":(r.startsWith("texture")&&(r=s.split("<")[0]),r=NM[r]),n.push(new ux(r,t))}const a=e.substring(t[0].length),o=t[3]||"void",h=void 0!==t[1]?t[1]:"";return{type:NM[o]||o,inputs:n,name:h,inputsCode:s,blockCode:a,outputType:o}}throw new Error("FunctionNode: Function is not a WGSL code.")})(e);super(t,s,i),this.inputsCode=r,this.blockCode=n,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class EM extends Sx{parseFunction(e){return new AM(e)}}const RM={[Xn]:"read",[Yn]:"write",[Kn]:"read_write"},CM={[L]:"repeat",[D]:"clamp",[I]:"mirror"},PM={vertex:rT.VERTEX,fragment:rT.FRAGMENT,compute:rT.COMPUTE},BM={instance:!0,swizzleAssign:!1,storageBuffer:!0},FM={"^^":"tsl_xor"},LM={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},DM={},IM={tsl_xor:new Pb("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Pb("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Pb("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Pb("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Pb("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Pb("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Pb("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Pb("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new Pb("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new Pb("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Pb("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new Pb("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Pb("\nfn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new Pb("\nfn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},OM={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let UM="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(UM+="diagnostic( off, derivative_uniformity );\n");class kM extends hx{constructor(e,t){super(e,t,new EM),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,s,i,r,n=this.shaderStage){return"fragment"===n?i?r?`textureSample( ${t}, ${t}_sampler, ${s}, ${i}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:r?`textureSample( ${t}, ${t}_sampler, ${s}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.generateTextureSampleLevel(e,t,s,"0",i)}generateTextureSampleLevel(e,t,s,i,r,n){return!1===this.isUnfilterable(e)?r?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i,r):this.generateTextureLod(e,t,s,r,n,i)}generateWrapFunction(e){const t=`tsl_coord_${CM[e.wrapS]}S_${CM[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let s=DM[t];if(void 0===s){const i=[],r=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const a=(e,t)=>{e===L?(i.push(IM.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===D?(i.push(IM.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===I?(i.push(IM.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,bt(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",DM[t]=s=new Pb(n,i)}return s.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,s){const i=this.getDataFromNode(e,this.shaderStage,this.cache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[s];if(void 0===i.dimensionsSnippet[s]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),h=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3<u32>":"vec2<u32>",n=h||e.isStorageTexture?t:`${t}${s?`, u32( ${s} )`:""}`,r=new tu(new Du(`textureDimensions( ${n} )`,a)),i.dimensionsSnippet[s]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new tu(new Du(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new tu(new Du("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,s,i,r="0u",n){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r);return i&&(s=`${s} + vec2<f32>(${i}) / ${o}`),n?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${s} ), ${o}, u32( ${n} ), u32( ${r} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${s} ), ${o}, u32( ${r} ) )`)}generateTextureLod(e,t,s,i,r,n="0u"){if(!0===e.isCubeTexture){r&&(s=`${s} + vec3<f32>(${r})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${e.isDepthTexture?"u32":"f32"}( ${n} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),h=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";r&&(s=`${s} + ${h}<f32>(${r}) / ${h}<f32>( ${o} )`);return s=`${h}<u32>( clamp( floor( ${a}( ${s} ) * ${h}<f32>( ${o} ) ), ${`${h}<f32>( 0 )`}, ${`${h}<f32>( ${o} - ${"vec3"===h?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,s,n,i,null)}generateStorageTextureLoad(e,t,s,i,r,n){let a;return n&&(s=`${s} + ${n}`),a=r?`textureLoad( ${t}, ${s}, ${r} )`:`textureLoad( ${t}, ${s} )`,a}generateTextureLoad(e,t,s,i,r,n){let a;return null===i&&(i="0u"),n&&(s=`${s} + ${n}`),r?a=`textureLoad( ${t}, ${s}, ${r}, u32( ${i} ) )`:(a=`textureLoad( ${t}, ${s}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,s,i,r){let n;return n=i?`textureStore( ${t}, ${s}, ${i}, ${r} )`:`textureStore( ${t}, ${s}, ${r} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(dt)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&e.type===Y||!1===this.isSampleCompare(e)&&e.minFilter===O&&e.magFilter===O||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,s,i,r,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,s,i,r,"0",n):this._generateTextureSample(e,t,s,i,r,n),a}generateTextureGrad(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return r?n?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${r}, ${i[0]}, ${i[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${r}, ${i[0]}, ${i[1]} )`:n?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;_t(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?n?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;_t(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,s,i,r,n){return!1===this.isUnfilterable(e)?r?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i,r):this.generateTextureLod(e,t,s,r,n,i)}generateTextureBias(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return r?n?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;_t(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,s=e.type;return"texture"===s||"cubeTexture"===s||"cubeDepthTexture"===s||"storageTexture"===s||"texture3D"===s?t:"buffer"===s||"storageBuffer"===s||"indirectStorageBuffer"===s?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=FM[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(bt("WebGPURenderer: Atomic operations are only supported in compute shaders."),Kn):Xn:e.access}getStorageAccess(e,t){return RM[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);if(void 0===n.uniformGPU){let a;const o=e.groupNode,h=o.name,l=this.getBindGroupArray(h,s);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const n=this.getNodeAccess(e,s);"texture"===t||"storageTexture"===t?i=!0===e.value.is3DTexture?new Tv(r.name,r.node,o,n):new xv(r.name,r.node,o,n):"cubeTexture"===t||"cubeDepthTexture"===t?i=new vv(r.name,r.node,o,n):"texture3D"===t&&(i=new Tv(r.name,r.node,o,n)),i.store=!0===e.isStorageTextureNode,i.mipLevel=i.store?e.mipLevel:0,i.setVisibility(PM[s]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===i.store){const e=new gM(`${r.name}_sampler`,r.node,o);e.setVisibility(PM[s]),l.push(e,i),a=[e,i]}else l.push(i),a=[i]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=this.getSharedDataFromNode(e);let h=n.buffer;if(void 0===h){h=new("buffer"===t?pv:bM)(e,o),n.buffer=h}h.setVisibility(h.getVisibility()|PM[s]),l.push(h),a=h,r.name=i||"NodeBuffer_"+r.id}else{let e=this.uniformGroups[h];void 0===e&&(e=new fv(h,o),e.setVisibility(rT.VERTEX|rT.FRAGMENT|rT.COMPUTE),this.uniformGroups[h]=e),-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(r,t);const s=a.name,i=e.uniforms.some(e=>e.name===s);i||e.addUniform(a)}n.uniformGPU=a}return r}getBuiltin(e,t,s,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:s}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${s.vars}\n${s.code}\n`;return s.result&&(r+=`\treturn ${s.result};\n`),r+="\n}\n",r}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],s=this.directives[e];if(void 0!==s)for(const e of s)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){const t=[],s=this.builtins[e];if(void 0!==s)for(const{name:e,property:i,type:r}of s.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,s,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:s,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:s,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const n=this.getType(i);t.push(`var<${s}> ${e}: array< ${n}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const s=this.getAttributesArray();for(let e=0,i=s.length;e<i;e++){const i=s[e],r=i.name,n=this.getType(i.type);t.push(`@location( ${e} ) ${r} : ${n}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const s of e.members){const i=e.output?"@location( "+s.index+" ) ":"";let r=this.getType(s.type);s.atomic&&(r="atomic< "+r+" >"),t.push(`\t${i+s.name} : ${r}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const s=this.structs[e];if(s.length>0){const e=[];for(const t of s){let s=`struct ${t.name} {\n`;s+=this.getStructMembers(t),s+="\n};",e.push(s)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,s=null,i=""){let r=`var${i} ${t} : `;return r+=null!==s?this.generateArrayDeclaration(e,s):this.getType(e),r}getVars(e,t=!1){let s="";t&&(s="<private>");const i=[],r=this.vars[e];if(void 0!==r)for(const e of r)i.push(`${this.getVar(e.type,e.name,e.count,s)};`);return t?i.join("\n"):`\n\t${i.join("\n\t")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,i=this.vars[e];let r=0;for(let n=0;n<s.length;n++){const a=s[n];if(a.needsInterpolation){let e=`@location( ${r++} )`;if(a.interpolationType){const t=null!==a.interpolationSampling?`, ${a.interpolationSampling} )`:" )";e+=` @interpolate( ${a.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(a.type)&&(e+=" @interpolate(flat, either)");t.push(`${e} ${a.name} : ${this.getType(a.type)}`)}else"vertex"===e&&!1===i.includes(a)&&i.push(a)}}const s=this.getBuiltins(e);s&&t.push(s);const i=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+i):i}isCustomStruct(e){const t=e.value,s=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&null!==s.structTypeNode,r=s.value&&s.value.array&&"number"==typeof s.value.itemSize&&s.value.array.length>s.value.itemSize;return i&&!r}getUniforms(e){const t=this.renderer.backend,s=this.uniforms[e],i=[],r=[],n=[],a={};for(const n of s){const s=n.groupNode.name,o=this.bindingsIndexes[s];if("texture"===n.type||"cubeTexture"===n.type||"cubeDepthTexture"===n.type||"storageTexture"===n.type||"texture3D"===n.type){const s=n.node.value;let r;(!0===s.isCubeTexture||!1===this.isUnfilterable(s)&&!0!==n.node.isStorageTextureNode)&&(this.isSampleCompare(s)?i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler_comparison;`):i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler;`));let a="";const{primarySamples:h}=t.utils.getTextureSampleData(s);if(h>1&&(a="_multisampled"),!0===s.isCubeTexture&&!0===s.isDepthTexture)r="texture_depth_cube";else if(!0===s.isCubeTexture)r="texture_cube<f32>";else if(!0===s.isDepthTexture)r=t.compatibilityMode&&null===s.compareFunction?`texture${a}_2d<f32>`:`texture_depth${a}_2d${!0===s.isArrayTexture?"_array":""}`;else if(!0===n.node.isStorageTextureNode){const i=SM(s,t.device),a=this.getStorageAccess(n.node,e),o=n.node.value.is3DTexture,h=n.node.value.isArrayTexture;r=`texture_storage_${o?"3d":"2d"+(h?"_array":"")}<${i}, ${a}>`}else if(!0===s.isArrayTexture||!0===s.isDataArrayTexture||!0===s.isCompressedArrayTexture)r="texture_2d_array<f32>";else if(!0===s.is3DTexture||!0===s.isData3DTexture)r="texture_3d<f32>";else{r=`texture${a}_2d<${this.getComponentTypeFromTexture(s).charAt(0)}32>`}i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name} : ${r};`)}else if("buffer"===n.type||"storageBuffer"===n.type||"indirectStorageBuffer"===n.type){const t=n.node,s=this.getType(t.getNodeType(this)),i=t.bufferCount,a=i>0&&"buffer"===n.type?", "+i:"",h=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(n))r.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${h}> ${n.name} : ${s};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${s}>`:`${s}`}${a} >`;r.push(this._getWGSLStructBinding(n.name,e,h,o.binding++,o.group))}}else{const e=n.groupNode.name;if(void 0===a[e]){const t=this.uniformGroups[e];if(void 0!==t){const s=[];for(const e of t.uniforms){const t=e.getType(),i=this.getType(this.getVectorType(t));s.push(`\t${e.name} : ${i}`)}let i=this.uniformGroupsBindings[e];void 0===i&&(i={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=i),a[e]={index:i.index,id:i.id,snippets:s}}}}}for(const e in a){const t=a[e];n.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...i,...r,...n].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const s=this.allowGlobalVariables,i=e[t];i.uniforms=this.getUniforms(t),i.attributes=this.getAttributes(t),i.varyings=this.getVaryings(t),i.structs=this.getStructs(t),i.vars=this.getVars(t,s),i.codes=this.getCodes(t),i.directives=this.getDirectives(t),i.scopedArrays=this.getScopedArrays(t);let r="// code\n\n";r+=this.flowCode[t];const n=this.flowNodes[t],a=n[n.length-1],o=a.outputNode,h=void 0!==o&&!0===o.isOutputStructNode;for(const e of n){const s=this.getFlowData(e),n=e.name;if(n&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${n}\n`),r+=`${s.code}\n\t`,e===a&&"compute"!==t)if(r+="// result\n\n\t","vertex"===t)r+=`varyings.builtinClipSpace = ${s.result};`;else if("fragment"===t)if(h)i.returnType=o.getNodeType(this),i.structs+="var<private> output : "+i.returnType+";",r+=`return ${s.result};`;else{let e="\t@location( 0 ) color: vec4<f32>";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),i.returnType="OutputStruct",i.structs+=this._getWGSLStruct("OutputStruct",e),i.structs+="\nvar<private> output : OutputStruct;",r+=`output.color = ${s.result};\n\n\treturn output;`}}i.flow=r}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,s){return`select( ${s}, ${t}, ${e} )`}getType(e){return LM[e]||e}isAvailable(e){let t=BM[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),BM[e]=t),t}_getWGSLMethod(e){return void 0!==IM[e]&&this._include(e),OM[e]}_include(e){const t=IM[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar<private> varyings : VaryingsStruct;\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${UM}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[s,i,r]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${s}, ${i}, ${r} )\nfn main( ${e.attributes} ) {\n\n\t// local vars\n\t${this.allowGlobalVariables?"":e.vars}\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${s} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${s} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y );\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,s,i=0,r=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${s}> ${e} : ${n};`}}class zM{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?!0===this.backend.renderer.reversedDepthBuffer?mS:dS:!0===this.backend.renderer.reversedDepthBuffer?pS:cS),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,s=e.getRenderTarget();t=s?s.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const s=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:s?1:t,isMSAA:s}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return null!==e.textures?e.textures.map(e=>this.getTextureFormatGPU(e)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?eT:e.isLineSegments||e.isMesh&&!0===t.wireframe?tT:e.isLine?sT:e.isMesh?iT:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===j)return HT;if(e===K)return rS;throw new Error("Unsupported output buffer type.")}}const VM=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&VM.set(Float16Array,["float16"]);const GM=new Map([[Ei,["float16"]]]),jM=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class $M{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,r=i.get(s);let n=r.buffer;if(void 0===n){const a=i.device;let o=s.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e<o.length;e++)65535===o[e]&&(o[e]=4294967295);if(s.array=o,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&3===s.itemSize){o=new o.constructor(4*s.count);for(let e=0;e<s.count;e++)o.set(s.array.subarray(3*e,3*e+3),4*e);s.itemSize=4,s.array=o,r._force3to4BytesAlignment=!0}const h=o.byteLength,l=h+(4-h%4)%4;n=a.createBuffer({label:s.name,size:l,usage:t,mappedAtCreation:!0}),new o.constructor(n.getMappedRange()).set(o),n.unmap(),r.buffer=n}}updateAttribute(e){const t=this._getBufferAttribute(e),s=this.backend,i=s.device,r=s.get(t),n=s.get(t).buffer;let a=t.array;if(!0===r._force3to4BytesAlignment){a=new a.constructor(4*t.count);for(let e=0;e<t.count;e++)a.set(t.array.subarray(3*e,3*e+3),4*e);t.array=a}const o=t.updateRanges;if(0===o.length)i.queue.writeBuffer(n,0,a,0);else{const e=pt(a),s=e?1:a.BYTES_PER_ELEMENT;for(let t=0,h=o.length;t<h;t++){const h=o[t];let l,u;if(!0===r._force3to4BytesAlignment){l=4*Math.floor(h.start/3)*s,u=4*Math.ceil(h.count/3)*s}else l=h.start*s,u=h.count*s;const c=l*(e?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(n,c,a,l,u)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),s=new Map;for(let e=0;e<t.length;e++){const i=t[e],r=i.array.BYTES_PER_ELEMENT,n=this._getBufferAttribute(i);let a=s.get(n);if(void 0===a){let e,t;!0===i.isInterleavedBufferAttribute?(e=i.data.stride*r,t=i.data.isInstancedInterleavedBuffer?dM:cM):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?dM:cM),!1!==i.normalized||i.array.constructor!==Int16Array&&i.array.constructor!==Uint16Array||(e=4),a={arrayStride:e,attributes:[],stepMode:t},s.set(n,a)}const o=this._getVertexFormat(i),h=!0===i.isInterleavedBufferAttribute?i.offset*r:0;a.attributes.push({shaderLocation:e,offset:h,format:o})}return Array.from(s.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,s=0,i=-1){const r=this.backend,n=r.device,a=r.get(this._getBufferAttribute(e)).buffer,o=-1===i?a.size-s:i;let h;if(null!==t&&t.isReadbackBuffer){const e=r.get(t);if(!0===t._mapped)throw new Error("WebGPURenderer: ReadbackBuffer must be released before being used again.");if(t._mapped=!0,void 0===e.readBufferGPU){h=n.createBuffer({label:`${t.name}_readback`,size:t.maxByteLength,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});const s=()=>{t.buffer=null,t._mapped=!1,h.unmap()},i=()=>{t.buffer=null,t._mapped=!1,h.destroy(),r.delete(t),t.removeEventListener("release",s),t.removeEventListener("dispose",i)};t.addEventListener("release",s),t.addEventListener("dispose",i),e.readBufferGPU=h}else h=e.readBufferGPU}else h=n.createBuffer({label:`${e.name}_readback`,size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});const l=n.createCommandEncoder({label:`readback_encoder_${e.name}`});l.copyBufferToBuffer(a,s,h,0,o);const u=l.finish();if(n.queue.submit([u]),await h.mapAsync(GPUMapMode.READ,0,o),null===t){const e=h.getMappedRange(0,o).slice();return h.destroy(),e}if(t.isReadbackBuffer)return t.buffer=h.getMappedRange(0,o),t;{const e=h.getMappedRange(0,o);return new Uint8Array(t).set(new Uint8Array(e)),h.destroy(),t}}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,r=e.constructor;let n;if(1===t)n=jM.get(i);else{const e=(GM.get(r)||VM.get(i))[s?1:0];if(e){const s=i.BYTES_PER_ELEMENT*t,r=4*Math.floor((s+3)/4)/i.BYTES_PER_ELEMENT;if(r%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");n=`${e}x${r}`}}return n||_t("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class WM{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class HM{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,s=t.device,i=t.get(e);if(i.layout)return i.layout.layoutGPU;const r=this._createLayoutEntries(e),n=Ln(JSON.stringify(r));let a=this._bindGroupLayoutCache.get(n);return void 0===a&&(a=new WM(s.createBindGroupLayout({entries:r})),this._bindGroupLayoutCache.set(n,a)),a.usedTimes++,i.layout=a,i.layoutKey=n,a.layoutGPU}createBindings(e,t,s,i=0){const{backend:r}=this,n=r.get(e),a=this.createBindingsLayout(e);let o;s>0&&(void 0===n.groups&&(n.groups=[],n.versions=[]),n.versions[s]===i&&(o=n.groups[s])),void 0===o&&(o=this.createBindGroup(e,a),s>0&&(n.groups[s]=o,n.versions[s]=i)),n.group=o}updateBinding(e){const t=this.backend,s=t.device,i=e.buffer,r=t.get(e).buffer,n=e.updateRanges;if(0===n.length)s.queue.writeBuffer(r,0,i,0);else{const e=pt(i),t=e?1:i.BYTES_PER_ELEMENT;for(let a=0,o=n.length;a<o;a++){const o=n[a],h=o.start*t,l=o.count*t,u=h*(e?i.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(r,u,i,h,l)}}}createBindGroupIndex(e,t){const s=this.backend.device,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0],n=s.createBuffer({label:"bindingCameraIndex_"+r,size:16,usage:i});s.queue.writeBuffer(n,0,e,0);const a=[{binding:0,resource:{buffer:n}}];return s.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:a})}createBindGroup(e,t){const s=this.backend,i=s.device;let r=0;const n=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=s.get(t);if(void 0===e.buffer){const s=t.byteLength,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=[];t.visibility&rT.VERTEX&&n.push("vertex"),t.visibility&rT.FRAGMENT&&n.push("fragment"),t.visibility&rT.COMPUTE&&n.push("compute");const a=`(${n.join(",")})`,o=i.createBuffer({label:`bindingBuffer${t.id}_${t.name}_${a}`,size:s,usage:r});e.buffer=o}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=s.get(t.attribute).buffer;n.push({binding:r,resource:{buffer:e}})}else if(t.isSampledTexture){const e=s.get(t.texture);let a;if(void 0!==e.externalTexture)a=i.importExternalTexture({source:e.externalTexture});else{const s=t.store?1:e.texture.mipLevelCount,i=t.store?t.mipLevel:0;let r=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(r+=`-${e.texture.depthOrArrayLayers}`),r+=`-${s}-${i}`,a=e[r],void 0===a){const n=uM;let o;o=t.isSampledCubeTexture?hM:t.isSampledTexture3D?lM:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?oM:aM,a=e[r]=e.texture.createView({aspect:n,dimension:o,mipLevelCount:s,baseMipLevel:i})}}n.push({binding:r,resource:a})}else if(t.isSampler){const e=s.get(t.texture);n.push({binding:r,resource:e.sampler})}r++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}_createLayoutEntries(e){const t=[];let s=0;for(const i of e.bindings){const e=this.backend,r={binding:s,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){const e={};i.isStorageBuffer&&(i.visibility&rT.COMPUTE&&(i.access===Kn||i.access===Yn)?e.type=Hw:e.type=qw),r.buffer=e}else if(i.isSampledTexture&&i.store){const e={};e.format=this.backend.get(i.texture).texture.format;const t=i.access;e.access=t===Kn?Kw:t===Yn?Xw:Yw,i.texture.isArrayTexture?e.viewDimension=oM:i.texture.is3DTexture&&(e.viewDimension=lM),r.storageTexture=e}else if(i.isSampledTexture){const t={},{primarySamples:s}=e.utils.getTextureSampleData(i.texture);if(s>1&&(t.multisampled=!0,i.texture.isDepthTexture||(t.sampleType=eM)),i.texture.isDepthTexture)e.compatibilityMode&&null===i.texture.compareFunction?t.sampleType=eM:t.sampleType=tM;else if(i.texture.isDataTexture||i.texture.isDataArrayTexture||i.texture.isData3DTexture||i.texture.isStorageTexture){const e=i.texture.type;e===q?t.sampleType=sM:e===X?t.sampleType=iM:e===Y&&(this.backend.hasFeature("float32-filterable")?t.sampleType=Jw:t.sampleType=eM)}i.isSampledCubeTexture?t.viewDimension=hM:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?t.viewDimension=oM:i.isSampledTexture3D&&(t.viewDimension=lM),r.texture=t}else if(i.isSampler){const t={};i.texture.isDepthTexture&&(null!==i.texture.compareFunction&&e.hasCompatibility(dt)?t.type=Zw:t.type=Qw),r.sampler=t}else _t(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(r),s++}return t}deleteBindGroupData(e){const{backend:t}=this,s=t.get(e);s.layout&&(s.layout.usedTimes--,0===s.layout.usedTimes&&this._bindGroupLayoutCache.delete(s.layoutKey),s.layout=void 0,s.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class qM{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}class XM{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:s,material:i,geometry:r,pipeline:n}=e,{vertexProgram:a,fragmentProgram:o}=n,h=this.backend,l=h.device,u=h.utils,c=h.get(n),d=[];for(const t of e.getBindings()){const e=h.get(t),{layoutGPU:s}=e.layout;d.push(s)}const p=h.attributeUtils.createShaderVertexBuffers(e);let m;0===i.blending||1===i.blending&&!1===i.transparent||(m=this._getBlending(i));let g={};!0===i.stencilWrite&&(g={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const f=this._getColorWriteMask(i),y=[];if(null!==e.context.textures){const t=e.context.textures,s=e.context.mrt;for(let e=0;e<t.length;e++){const i=t[e],r=u.getTextureFormatGPU(i);let n;if(null!==s)if(!0!==this.backend.compatibilityMode){const e=s.getBlendMode(i.name);6===e.blending?n=m:0!==e.blending&&(n=this._getBlending(e))}else xt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),n=m;else n=m;y.push({format:r,blend:n,writeMask:f})}}else{const t=u.getCurrentColorFormat(e.context);y.push({format:t,blend:m,writeMask:f})}const b=h.get(a).module,_=h.get(o).module,x=this._getPrimitiveState(s,r,i),v=this._getDepthCompare(i),T=u.getCurrentDepthStencilFormat(e.context),S=this._getSampleCount(e.context),w={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},b,{buffers:p}),fragment:Object.assign({},_,{targets:y}),primitive:x,multisample:{count:S,alphaToCoverageEnabled:i.alphaToCoverage&&S>1},layout:l.createPipelineLayout({bindGroupLayouts:d})},M={},N=e.context.depth,A=e.context.stencil;if(!0!==N&&!0!==A||(!0===N&&(M.format=T,M.depthWriteEnabled=i.depthWrite,M.depthCompare=v),!0===A&&(M.stencilFront=g,M.stencilBack=g,M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(M.depthBias=i.polygonOffsetUnits,M.depthBiasSlopeScale=i.polygonOffsetFactor,M.depthBiasClamp=0),w.depthStencil=M),l.pushErrorScope("validation"),null===t)c.pipeline=l.createRenderPipeline(w),l.popErrorScope().then(e=>{null!==e&&(c.error=!0,_t(e.message))});else{const e=new Promise(async e=>{try{c.pipeline=await l.createRenderPipelineAsync(w)}catch(e){}const t=await l.popErrorScope();null!==t&&(c.error=!0,_t(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const s=this.backend,{utils:i,device:r}=s,n=i.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:i.getCurrentColorFormats(e),depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return r.createRenderBundleEncoder(a)}createComputePipeline(e,t){const s=this.backend,i=s.device,r=s.get(e.computeProgram).module,n=s.get(e),a=[];for(const e of t){const t=s.get(e),{layoutGPU:i}=t.layout;a.push(i)}n.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,a=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,o=null!==e.blendDstAlpha?e.blendDstAlpha:n,h=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(a)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(h)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:Pw},s={srcFactor:r,dstFactor:n,operation:Pw}};if(e.premultipliedAlpha)switch(i){case 1:r(_w,Sw,_w,Sw);break;case 2:r(_w,_w,_w,_w);break;case 3:r(bw,vw,bw,_w);break;case 4:r(ww,Sw,bw,_w)}else switch(i){case 1:r(Tw,Sw,_w,Sw);break;case 2:r(Tw,_w,_w,_w);break;case 3:_t(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case 4:_t(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};_t("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case p:t=bw;break;case 201:t=_w;break;case 202:t=xw;break;case 203:t=vw;break;case y:t=Tw;break;case b:t=Sw;break;case 208:t=ww;break;case 209:t=Mw;break;case 206:t=Nw;break;case 207:t=Aw;break;case 210:t=Ew;break;case 211:t=Rw;break;case 212:t=Cw;break;default:_t("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=nT;break;case 519:t=dT;break;case 513:t=aT;break;case 515:t=hT;break;case 514:t=oT;break;case 518:t=cT;break;case 516:t=lT;break;case 517:t=uT;break;default:_t("WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case Qe:t=Uw;break;case 0:t=kw;break;case 7681:t=zw;break;case 5386:t=Vw;break;case 7682:t=Gw;break;case 7683:t=jw;break;case 34055:t=$w;break;case 34056:t=Ww;break;default:_t("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case u:t=Pw;break;case 101:t=Bw;break;case 102:t=Fw;break;case 103:t=Lw;break;case 104:t=Dw;break;default:_t("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},r=this.backend.utils;i.topology=r.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?xT:vT);let n=1===s.side;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),i.frontFace=!0===n?yT:fT,i.cullMode=2===s.side?bT:_T,i}_getColorWriteMask(e){return!0===e.colorWrite?Ow:Iw}_getDepthCompare(e){let t;if(!1===e.depthTest)t=dT;else{const s=this.backend.parameters.reversedDepthBuffer?Tt[e.depthFunc]:e.depthFunc;switch(s){case 0:t=nT;break;case 1:t=dT;break;case 2:t=aT;break;case 3:t=hT;break;case 4:t=oT;break;case 5:t=cT;break;case 6:t=lT;break;case 7:t=uT;break;default:_t("WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class YM extends Qv{constructor(e,t,s=2048){super(s),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return xt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,s=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,s);const r=i.finish();if(this.device.queue.submit([r]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,s),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,s)),a={},o=[];for(const[t,s]of e){const e=t.match(/^(.*):f(\d+)$/),i=parseInt(e[2]);!1===o.includes(i)&&o.push(i),void 0===a[i]&&(a[i]=0);const r=n[s],h=n[s+1],l=Number(h-r)/1e6;this.timestamps.set(t,l),a[i]+=l}const h=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=h,this.frames=o,h}catch(e){return _t("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){_t("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){_t("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}const KM={r:0,g:0,b:0,a:1};class QM extends Fv{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new zM(this),this.attributeUtils=new $M(this),this.bindingUtils=new HM(this),this.capabilities=new qM(this),this.pipelineUtils=new XM(this),this.textureUtils=new TM(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[dt]:t}}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:"compatibility"},i="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(pM),n=[];for(const e of r)i.features.has(e)&&n.push(e);const a={requiredFeatures:n,requiredLimits:t.requiredLimits};s=await i.requestDevice(a)}else s=t.device;this.compatibilityMode=!s.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),s.lost.then(t=>{if("destroyed"===t.reason)return;const s={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(s)}),this.device=s,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(pM.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let s=t.context;if(void 0===s){const i=this.parameters;s=!0===e.isDefaultCanvasTarget&&void 0!==i.context?i.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${a} webgpu`);const r=i.alpha?"premultiplied":"opaque",n=i.outputType===K?"extended":"standard";s.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r,toneMapping:{mode:n}}),t.context=s}return s}get coordinateSystem(){return lt}async getArrayBufferAsync(e,t=null,s=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,s,i)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),s=this.get(t),i=e.currentSamples;let r=s.descriptor;if(void 0===r||s.samples!==i){r={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(r.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=r.colorAttachments[0];i>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,s.descriptor=r,s.samples=i}const n=r.colorAttachments[0];return i>0?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),r}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const s=e.renderTarget,i=this.get(s);let r=i.descriptors;void 0!==r&&i.width===s.width&&i.height===s.height&&i.samples===s.samples||(r={},i.descriptors=r);const n=e.getCacheKey();let a=r[n];if(void 0===a){const t=e.textures,o=[];let h;const l=this._isRenderCameraDepthArray(e);for(let i=0;i<t.length;i++){const r=this.get(t[i]),n={label:`colorAttachment_${i}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:aM};if(s.isRenderTarget3D)h=e.activeCubeFace,n.baseArrayLayer=0,n.dimension=lM,n.depthOrArrayLayers=t[i].image.depth;else if(s.isRenderTarget&&t[i].image.depth>1)if(!0===l){const t=e.camera.cameras;for(let e=0;e<t.length;e++){const t={...n,baseArrayLayer:e,arrayLayerCount:1,dimension:aM},s=r.texture.createView(t);o.push({view:s,resolveTarget:void 0,depthSlice:void 0})}}else n.dimension=oM,n.depthOrArrayLayers=t[i].image.depth;if(!0!==l){const e=r.texture.createView(n);let t,s;void 0!==r.msaaTexture?(t=r.msaaTexture.createView(),s=e):(t=e,s=void 0),o.push({view:t,resolveTarget:s,depthSlice:h})}}if(a={textureViews:o},e.depth){const t=this.get(e.depthTexture),s={};(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(s.dimension=aM,s.arrayLayerCount=1,s.baseArrayLayer=e.activeCubeFace),a.depthStencilView=t.texture.createView(s)}r[n]=a,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const o={colorAttachments:[]};for(let e=0;e<a.textureViews.length;e++){const s=a.textureViews[e];let i={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(i=t.clearValue),o.colorAttachments.push({view:s.view,depthSlice:s.depthSlice,resolveTarget:s.resolveTarget,loadOp:t.loadOp||mT,storeOp:t.storeOp||pT,clearValue:i})}return a.depthStencilView&&(o.depthStencilAttachment={view:a.depthStencilView}),o}beginRender(e){const t=this.get(e),s=this.device,i=e.occlusionQueryCount;let r,n;i>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=s.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:mT}),this.initTimestampQuery(ct,this.getTimestampUID(e),n),n.occlusionQuerySet=r;const a=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let s=0;s<t.length;s++){const i=t[s];e.clearColor?(0===s?i.clearValue=e.clearColorValue:(KM.r=0,KM.g=0,KM.b=0,KM.a=1,i.clearValue=KM),i.loadOp=gT):i.loadOp=mT,i.storeOp=pT}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=gT):t.loadOp=mT,t.storeOp=pT}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=gT):a.depthLoadOp=mT,a.depthStoreOp=pT),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=gT):a.stencilLoadOp=mT,a.stencilStoreOp=pT);const o=s.createCommandEncoder({label:"renderContext_"+e.id});if(!0===this._isRenderCameraDepthArray(e)){const s=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===s.length?this._updateDepthLayerDescriptors(e,t,s):this._createDepthLayerDescriptors(e,t,n,s),t.bundleEncoders=[],t.bundleSets=[];for(let i=0;i<s.length;i++){const s=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+i),r={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(s),t.bundleSets.push(r)}t.currentPass=null}else{const s=o.beginRenderPass(n);t.currentPass=s,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=n,t.encoder=o,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,s,i){const r=s.depthStencilAttachment;t.layerDescriptors=[];const n=this.get(e.depthTexture);n.viewCache||(n.viewCache=[]);for(let a=0;a<i.length;a++){const i={...s,colorAttachments:[{...s.colorAttachments[0],view:s.colorAttachments[a].view}]};if(s.depthStencilAttachment){const t=a;n.viewCache[t]||(n.viewCache[t]=n.texture.createView({dimension:aM,baseArrayLayer:a,arrayLayerCount:1})),i.depthStencilAttachment={view:n.viewCache[t],depthLoadOp:r.depthLoadOp||gT,depthStoreOp:r.depthStoreOp||pT,depthClearValue:r.depthClearValue||1},e.stencil&&(i.depthStencilAttachment.stencilLoadOp=r.stencilLoadOp,i.depthStencilAttachment.stencilStoreOp=r.stencilStoreOp,i.depthStencilAttachment.stencilClearValue=r.stencilClearValue)}else i.depthStencilAttachment={...r};t.layerDescriptors.push(i)}}_updateDepthLayerDescriptors(e,t,s){for(let i=0;i<s.length;i++){const s=t.layerDescriptors[i];if(s.depthStencilAttachment){const t=s.depthStencilAttachment;e.depth&&(e.clearDepth?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=gT):t.depthLoadOp=mT),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=gT):t.stencilLoadOp=mT)}}}finishRender(e){const t=this.get(e),s=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const s=[];for(let e=0;e<t.bundleEncoders.length;e++){const i=t.bundleEncoders[e];s.push(i.finish())}for(let r=0;r<t.layerDescriptors.length;r++)if(r<s.length){const n=t.layerDescriptors[r],a=i.beginRenderPass(n);if(e.viewport){const{x:t,y:s,width:i,height:r,minDepth:n,maxDepth:o}=e.viewportValue;a.setViewport(t,s,i,r,n,o)}if(e.scissor){const{x:t,y:s,width:i,height:r}=e.scissorValue;a.setScissorRect(t,s,i,r)}a.executeBundles([s[r]]),a.end()}}else t.currentPass&&t.currentPass.end();if(s>0){const i=8*s;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const n=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,n,0,i),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;e<t.length;e++){const s=t[e];!0===s.generateMipmaps&&this.textureUtils.generateMipmaps(s)}}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await s.mapAsync(GPUMapMode.READ);const r=s.getMappedRange(),n=new BigUint64Array(r);for(let t=0;t<i.length;t++)n[t]===BigInt(0)&&e.add(i[t]);s.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:r,height:n,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(s,i,r,n,a,o)}updateScissor(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:r,height:n}=e.scissorValue;t.setScissorRect(s,i,r,n)}getClearColor(){const e=super.getClearColor();return!0===this.renderer.alpha&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,s,i=null){const r=this.device,n=this.renderer;let a,o,h,l=[];if(e){const e=this.getClearColor();KM.r=e.r,KM.g=e.g,KM.b=e.b,KM.a=e.a}if(null===i){o=n.depth,h=n.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){l=t.colorAttachments;const e=l[0];e.clearValue=KM,e.loadOp=gT,e.storeOp=pT}(o||h)&&(a=t.depthStencilAttachment)}else{o=i.depth,h=i.stencil;const r={loadOp:e?gT:mT,clearValue:e?KM:void 0};o&&(r.depthLoadOp=t?gT:mT,r.depthClearValue=t?n.getClearDepth():void 0,r.depthStoreOp=pT),h&&(r.stencilLoadOp=s?gT:mT,r.stencilClearValue=s?n.getClearStencil():void 0,r.stencilStoreOp=pT);const u=this._getRenderPassDescriptor(i,r);l=u.colorAttachments,a=u.depthStencilAttachment}o&&a&&(t?(a.depthLoadOp=gT,a.depthClearValue=n.getClearDepth(),a.depthStoreOp=pT):(a.depthLoadOp=mT,a.depthStoreOp=pT)),h&&a&&(s?(a.stencilLoadOp=gT,a.stencilClearValue=n.getClearStencil(),a.stencilStoreOp=pT):(a.stencilLoadOp=mT,a.stencilStoreOp=pT));const u=r.createCommandEncoder({label:"clear"});u.beginRenderPass({colorAttachments:l,depthStencilAttachment:a}).end(),r.queue.submit([u.finish()])}beginCompute(e){const t=this.get(e),s={label:"computeGroup_"+e.id};this.initTimestampQuery(ut,this.getTimestampUID(e),s),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(s)}compute(e,t,s,i,r=null){const n=this.get(t),{passEncoderGPU:a}=this.get(e),o=this.get(i).pipeline;this.pipelineUtils.setPipeline(a,o);for(let e=0,t=s.length;e<t;e++){const t=s[e],i=this.get(t);a.setBindGroup(e,i.group)}if(null===r&&(r=t.dispatchSize||t.count),r&&r.isIndirectStorageBufferAttribute){const e=this.get(r).buffer;return void a.dispatchWorkgroupsIndirect(e,0)}if("number"==typeof r){const e=r;if(void 0===n.dispatchSize||n.count!==e){n.dispatchSize=[0,1,1],n.count=e;const s=t.workgroupSize;let i=s[0];for(let e=1;e<s.length;e++)i*=s[e];const a=Math.ceil(e/i),o=this.device.limits.maxComputeWorkgroupsPerDimension;r=[a,1,1],a>o&&(r[0]=Math.min(a,o),r[1]=Math.ceil(a/o)),n.dispatchSize=r}r=n.dispatchSize}a.dispatchWorkgroups(r[0],r[1]||1,r[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}_draw(e,t,s,i,r,n,a,o,h){const{object:l,material:u,context:c}=e,d=e.getIndex(),p=null!==d;this.pipelineUtils.setPipeline(o,i),h.pipeline=i;const m=h.bindingGroups;for(let e=0,t=r.length;e<t;e++){const t=r[e],s=this.get(t);m[e]!==t.id&&(o.setBindGroup(e,s.group),m[e]=t.id)}if(!0===p&&h.index!==d){const e=this.get(d).buffer,t=d.array instanceof Uint16Array?xT:vT;o.setIndexBuffer(e,t),h.index=d}for(let e=0,t=n.length;e<t;e++){const t=n[e];if(h.attributes[e]!==t){const s=this.get(t).buffer;o.setVertexBuffer(e,s),h.attributes[e]=t}}if(!0===c.stencil&&!0===u.stencilWrite&&s.currentStencilRef!==u.stencilRef&&(o.setStencilReference(u.stencilRef),s.currentStencilRef=u.stencilRef),!0===l.isBatchedMesh){const e=l._multiDrawStarts,s=l._multiDrawCounts,i=l._multiDrawCount;let r=!0===p?d.array.BYTES_PER_ELEMENT:1;u.wireframe&&(r=l.geometry.attributes.position.count>65535?4:2);for(let n=0;n<i;n++)!0===p?o.drawIndexed(s[n],1,e[n]/r,0,n):o.draw(s[n],1,e[n],n),t.update(l,s[n],1)}else if(!0===p){const{vertexCount:s,instanceCount:i,firstVertex:r}=a,n=e.getIndirect();if(null!==n){const t=this.get(n).buffer,s=e.getIndirectOffset(),i=Array.isArray(s)?s:[s];for(let e=0;e<i.length;e++)o.drawIndexedIndirect(t,i[e])}else o.drawIndexed(s,i,r,0,0);t.update(l,s,i)}else{const{vertexCount:s,instanceCount:i,firstVertex:r}=a,n=e.getIndirect();if(null!==n){const t=this.get(n).buffer,s=e.getIndirectOffset(),i=Array.isArray(s)?s:[s];for(let e=0;e<i.length;e++)o.drawIndirect(t,i[e])}else o.draw(s,i,r,0);t.update(l,s,i)}}draw(e,t){const{object:s,context:i,pipeline:r}=e,n=this.get(i),a=this.get(r),o=a.pipeline;if(!0===a.error)return;const h=e.getDrawParameters();if(null===h)return;const l=e.getBindings(),u=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const r=this.get(e.camera),a=e.camera.cameras,c=e.getBindingGroup("cameraIndex");if(void 0===r.indexesGPU||r.indexesGPU.length!==a.length){const e=this.get(c),t=[],s=new Uint32Array([0,0,0,0]);for(let i=0,r=a.length;i<r;i++){s[0]=i;const{layoutGPU:r}=e.layout,n=this.bindingUtils.createBindGroupIndex(s,r);t.push(n)}r.indexesGPU=t}const d=this.renderer.getPixelRatio();for(let p=0,m=a.length;p<m;p++){const m=a[p];if(s.layers.test(m.layers)){const s=m.viewport;let a=n.currentPass,g=n.currentSets;if(n.bundleEncoders){a=n.bundleEncoders[p],g=n.bundleSets[p]}if(s&&a.setViewport(Math.floor(s.x*d),Math.floor(s.y*d),Math.floor(s.width*d),Math.floor(s.height*d),i.viewportValue.minDepth,i.viewportValue.maxDepth),c&&r.indexesGPU){const e=l.indexOf(c);a.setBindGroup(e,r.indexesGPU[p]),g.bindingGroups[e]=c.id}this._draw(e,t,n,o,l,u,h,a,g)}}}else if(n.currentPass){if(void 0!==n.occlusionQuerySet){const e=n.lastOcclusionObject;e!==s&&(null!==e&&!0===e.occlusionTest&&(n.currentPass.endOcclusionQuery(),n.occlusionQueryIndex++),!0===s.occlusionTest&&(n.currentPass.beginOcclusionQuery(n.occlusionQueryIndex),n.occlusionQueryObjects[n.occlusionQueryIndex]=s),n.lastOcclusionObject=s)}this._draw(e,t,n,o,l,u,h,n.currentPass,n.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),a=r.getCurrentColorSpace(e.context),o=r.getCurrentColorFormat(e.context),h=r.getCurrentDepthStencilFormat(e.context),l=r.getPrimitiveTopology(s,i);let u=!1;return t.material===i&&t.materialVersion===i.version&&t.transparent===i.transparent&&t.blending===i.blending&&t.premultipliedAlpha===i.premultipliedAlpha&&t.blendSrc===i.blendSrc&&t.blendDst===i.blendDst&&t.blendEquation===i.blendEquation&&t.blendSrcAlpha===i.blendSrcAlpha&&t.blendDstAlpha===i.blendDstAlpha&&t.blendEquationAlpha===i.blendEquationAlpha&&t.colorWrite===i.colorWrite&&t.depthWrite===i.depthWrite&&t.depthTest===i.depthTest&&t.depthFunc===i.depthFunc&&t.stencilWrite===i.stencilWrite&&t.stencilFunc===i.stencilFunc&&t.stencilFail===i.stencilFail&&t.stencilZFail===i.stencilZFail&&t.stencilZPass===i.stencilZPass&&t.stencilFuncMask===i.stencilFuncMask&&t.stencilWriteMask===i.stencilWriteMask&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===a&&t.colorFormat===o&&t.depthStencilFormat===h&&t.primitiveTopology===l&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=n,t.colorSpace=a,t.colorFormat=o,t.depthStencilFormat=h,t.primitiveTopology=l,t.clippingContextCacheKey=e.clippingContextCacheKey,u=!0),u}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,r=e.context,n=t.isMesh&&t.matrixWorld.determinant()<0;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,n,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,s),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}initTimestampQuery(e,t,s){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new YM(this.device,e,2048));const i=this.timestampQueryPool[e],r=i.allocateQueriesForContext(t);s.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:r,endOfPassWriteIndex:r+1}}createNodeBuilder(e,t){return new kM(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage+(""!==e.name?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),i=s.currentPass.finish();this.get(t).bundleGPU=i,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}hasFeature(e){return void 0!==mM[e]&&(e=mM[e]),this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){let a=0,o=0,h=0,l=0,u=0,c=0,d=e.image.width,p=e.image.height,m=1;null!==s&&(!0===s.isBox3?(l=s.min.x,u=s.min.y,c=s.min.z,d=s.max.x-s.min.x,p=s.max.y-s.min.y,m=s.max.z-s.min.z):(l=s.min.x,u=s.min.y,d=s.max.x-s.min.x,p=s.max.y-s.min.y,m=1)),null!==i&&(a=i.x,o=i.y,h=i.z||0);const g=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),f=this.get(e).texture,y=this.get(t).texture;g.copyTextureToTexture({texture:f,mipLevel:r,origin:{x:l,y:u,z:c}},{texture:y,mipLevel:n,origin:{x:a,y:o,z:h}},[d,p,m]),this.device.queue.submit([g.finish()]),0===n&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,s){const i=this.get(t);let r=null;r=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const n=this.get(e).texture;if(r.format!==n.format)return void _t("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,n.format);let a;if(i.currentPass?(i.currentPass.end(),a=i.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:r,origin:[s.x,s.y,0]},{texture:n},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,a),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=mT;t.depth&&(e.depthStencilAttachment.depthLoadOp=mT),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=mT),i.currentPass=a.beginRenderPass(e),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else this.device.queue.submit([a.finish()])}hasCompatibility(e){return void 0!==this._compatibility[e]?this._compatibility[e]:super.hasCompatibility(e)}dispose(){if(this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}if(this.timestampQueryPool)for(const e of Object.values(this.timestampQueryPool))null!==e&&e.dispose();void 0===this.parameters.device&&null!==this.device&&this.device.destroy()}}class ZM extends un{constructor(e,t,s,i,r,n){super(e,t,s,i,r,n),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class JM extends un{constructor(e,t,s,i,r,n){super(e,t,s,i,r,n),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class eN extends Ux{constructor(){super(),this.addMaterial(sg,"MeshPhongMaterial"),this.addMaterial(qf,"MeshStandardMaterial"),this.addMaterial(Yf,"MeshPhysicalMaterial"),this.addMaterial(Jf,"MeshToonMaterial"),this.addMaterial(qm,"MeshBasicMaterial"),this.addMaterial(eg,"MeshLambertMaterial"),this.addMaterial(Lm,"MeshNormalMaterial"),this.addMaterial(sy,"MeshMatcapMaterial"),this.addMaterial(Cm,"LineBasicMaterial"),this.addMaterial(Bm,"LineDashedMaterial"),this.addMaterial(ly,"PointsMaterial"),this.addMaterial(ay,"SpriteMaterial"),this.addMaterial(py,"ShadowMaterial"),this.addLight(M_,dn),this.addLight(dx,gn),this.addLight(Tx,yn),this.addLight(mx,un),this.addLight(cx,fn),this.addLight(px,Yr),this.addLight(fx,_n),this.addLight(gx,ZM),this.addLight(bx,JM),this.addToneMapping(vb,1),this.addToneMapping(Tb,2),this.addToneMapping(Sb,3),this.addToneMapping(Mb,4),this.addToneMapping(Rb,6),this.addToneMapping(Cb,7)}}class tN extends hv{constructor(e={}){let t;e.forceWebGL?t=Jv:(t=QM,e.getFallback=()=>(bt("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new Jv(e)));super(new t(e),e),this.library=new eN,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const sN={type:"change"},iN={type:"start"},rN={type:"end"},nN=1e-6,aN=-1,oN=0,hN=1,lN=2,uN=3,cN=4,dN=new e.Vector2,pN=new e.Vector2,mN=new e.Vector3,gN=new e.Vector3,fN=new e.Vector3,yN=new e.Quaternion,bN=new e.Vector3,_N=new e.Vector3,xN=new e.Vector3,vN=new e.Vector3;class TN extends e.Controls{constructor(t,s=null){super(t,s),this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:e.MOUSE.ROTATE,MIDDLE:e.MOUSE.DOLLY,RIGHT:e.MOUSE.PAN},this.target=new e.Vector3,this.state=aN,this.keyState=aN,this._lastPosition=new e.Vector3,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new e.Vector3,this._movePrev=new e.Vector2,this._moveCurr=new e.Vector2,this._lastAxis=new e.Vector3,this._zoomStart=new e.Vector2,this._zoomEnd=new e.Vector2,this._panStart=new e.Vector2,this._panEnd=new e.Vector2,this._pointers=[],this._pointerPositions={},this._onPointerMove=wN.bind(this),this._onPointerDown=SN.bind(this),this._onPointerUp=MN.bind(this),this._onPointerCancel=NN.bind(this),this._onContextMenu=FN.bind(this),this._onMouseWheel=BN.bind(this),this._onKeyDown=EN.bind(this),this._onKeyUp=AN.bind(this),this._onTouchStart=LN.bind(this),this._onTouchMove=DN.bind(this),this._onTouchEnd=IN.bind(this),this._onMouseDown=RN.bind(this),this._onMouseMove=CN.bind(this),this._onMouseUp=PN.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,null!==s&&(this.connect(s),this.handleResize()),this.update()}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){this._eye.subVectors(this.object.position,this.target),this.noRotate||this._rotateCamera(),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this._checkDistances(),this.object.lookAt(this.target),this._lastPosition.distanceToSquared(this.object.position)>nN&&(this.dispatchEvent(sN),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>nN||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(sN),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=aN,this.keyState=aN,this.target.copy(this._target0),this.object.position.copy(this._position0),this.object.up.copy(this._up0),this.object.zoom=this._zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(sN),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(pN.copy(this._panEnd).sub(this._panStart),pN.lengthSq()){if(this.object.isOrthographicCamera){const e=(this.object.right-this.object.left)/this.object.zoom/this.domElement.clientWidth,t=(this.object.top-this.object.bottom)/this.object.zoom/this.domElement.clientWidth;pN.x*=e,pN.y*=t}pN.multiplyScalar(this._eye.length()*this.panSpeed),gN.copy(this._eye).cross(this.object.up).setLength(pN.x),gN.add(mN.copy(this.object.up).setLength(pN.y)),this.object.position.add(gN),this.target.add(gN),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(pN.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){vN.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=vN.length();e?(this._eye.copy(this.object.position).sub(this.target),bN.copy(this._eye).normalize(),_N.copy(this.object.up).normalize(),xN.crossVectors(_N,bN).normalize(),_N.setLength(this._moveCurr.y-this._movePrev.y),xN.setLength(this._moveCurr.x-this._movePrev.x),vN.copy(_N.add(xN)),fN.crossVectors(vN,this._eye).normalize(),e*=this.rotateSpeed,yN.setFromAxisAngle(fN,e),this._eye.applyQuaternion(yN),this.object.up.applyQuaternion(yN),this._lastAxis.copy(fN),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),yN.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(yN),this.object.up.applyQuaternion(yN)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let t;this.state===cN?(t=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(t):this.object.isOrthographicCamera?(this.object.zoom=e.MathUtils.clamp(this.object.zoom/t,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(t=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==t&&t>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(t):this.object.isOrthographicCamera?(this.object.zoom=e.MathUtils.clamp(this.object.zoom/t,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor)}_getMouseOnScreen(e,t){return dN.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),dN}_getMouseOnCircle(e,t){return dN.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),dN}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId==e.pointerId)return void this._pointers.splice(t,1)}_trackPointer(t){let s=this._pointerPositions[t.pointerId];void 0===s&&(s=new e.Vector2,this._pointerPositions[t.pointerId]=s),s.set(t.pageX,t.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0].pointerId?this._pointers[1]:this._pointers[0];return this._pointerPositions[t.pointerId]}_checkDistances(){this.noZoom&&this.noPan||(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}}function SN(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e))}function wN(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function MN(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchEnd(e):this._onMouseUp(),this._removePointer(e),0===this._pointers.length&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp)))}function NN(e){this._removePointer(e)}function AN(){!1!==this.enabled&&(this.keyState=aN,window.addEventListener("keydown",this._onKeyDown))}function EN(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===aN&&(e.code!==this.keys[oN]||this.noRotate?e.code!==this.keys[hN]||this.noZoom?e.code!==this.keys[lN]||this.noPan||(this.keyState=lN):this.keyState=hN:this.keyState=oN))}function RN(t){let s;switch(t.button){case 0:s=this.mouseButtons.LEFT;break;case 1:s=this.mouseButtons.MIDDLE;break;case 2:s=this.mouseButtons.RIGHT;break;default:s=-1}switch(s){case e.MOUSE.DOLLY:this.state=hN;break;case e.MOUSE.ROTATE:this.state=oN;break;case e.MOUSE.PAN:this.state=lN;break;default:this.state=aN}const i=this.keyState!==aN?this.keyState:this.state;i!==oN||this.noRotate?i!==hN||this.noZoom?i!==lN||this.noPan||(this._panStart.copy(this._getMouseOnScreen(t.pageX,t.pageY)),this._panEnd.copy(this._panStart)):(this._zoomStart.copy(this._getMouseOnScreen(t.pageX,t.pageY)),this._zoomEnd.copy(this._zoomStart)):(this._moveCurr.copy(this._getMouseOnCircle(t.pageX,t.pageY)),this._movePrev.copy(this._moveCurr)),this.dispatchEvent(iN)}function CN(e){const t=this.keyState!==aN?this.keyState:this.state;t!==oN||this.noRotate?t!==hN||this.noZoom?t!==lN||this.noPan||this._panEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):this._zoomEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):(this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)))}function PN(){this.state=aN,this.dispatchEvent(rN)}function BN(e){if(!1!==this.enabled&&!0!==this.noZoom){switch(e.preventDefault(),e.deltaMode){case 2:this._zoomStart.y-=.025*e.deltaY;break;case 1:this._zoomStart.y-=.01*e.deltaY;break;default:this._zoomStart.y-=25e-5*e.deltaY}this.dispatchEvent(iN),this.dispatchEvent(rN)}}function FN(e){!1!==this.enabled&&e.preventDefault()}function LN(e){if(this._trackPointer(e),1===this._pointers.length)this.state=uN,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=cN;const e=this._pointers[0].pageX-this._pointers[1].pageX,t=this._pointers[0].pageY-this._pointers[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(e*e+t*t);const s=(this._pointers[0].pageX+this._pointers[1].pageX)/2,i=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(s,i)),this._panEnd.copy(this._panStart)}this.dispatchEvent(iN)}function DN(e){if(this._trackPointer(e),1===this._pointers.length)this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY));else{const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(s*s+i*i);const r=(e.pageX+t.x)/2,n=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(r,n))}}function IN(e){switch(this._pointers.length){case 0:this.state=aN;break;case 1:this.state=uN,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=cN;for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId!==e.pointerId){const e=this._pointerPositions[this._pointers[t].pointerId];this._moveCurr.copy(this._getMouseOnCircle(e.x,e.y)),this._movePrev.copy(this._moveCurr);break}}this.dispatchEvent(rN)}const ON={type:"change"},UN={type:"start"},kN={type:"end"},zN=new e.Ray,VN=new e.Plane,GN=Math.cos(70*e.MathUtils.DEG2RAD),jN=new e.Vector3,$N=2*Math.PI,WN=-1,HN=0,qN=1,XN=2,YN=3,KN=4,QN=5,ZN=6,JN=1e-6;class eA extends e.Controls{constructor(t,s=null){super(t,s),this.state=WN,this.target=new e.Vector3,this.cursor=new e.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:e.MOUSE.ROTATE,MIDDLE:e.MOUSE.DOLLY,RIGHT:e.MOUSE.PAN},this.touches={ONE:e.TOUCH.ROTATE,TWO:e.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new e.Vector3,this._lastQuaternion=new e.Quaternion,this._lastTargetPosition=new e.Vector3,this._quat=(new e.Quaternion).setFromUnitVectors(t.up,new e.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new e.Spherical,this._sphericalDelta=new e.Spherical,this._scale=1,this._panOffset=new e.Vector3,this._rotateStart=new e.Vector2,this._rotateEnd=new e.Vector2,this._rotateDelta=new e.Vector2,this._panStart=new e.Vector2,this._panEnd=new e.Vector2,this._panDelta=new e.Vector2,this._dollyStart=new e.Vector2,this._dollyEnd=new e.Vector2,this._dollyDelta=new e.Vector2,this._dollyDirection=new e.Vector3,this._mouse=new e.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=sA.bind(this),this._onPointerDown=tA.bind(this),this._onPointerUp=iA.bind(this),this._onContextMenu=uA.bind(this),this._onMouseWheel=aA.bind(this),this._onKeyDown=oA.bind(this),this._onTouchStart=hA.bind(this),this._onTouchMove=lA.bind(this),this._onMouseDown=rA.bind(this),this._onMouseMove=nA.bind(this),this._interceptControlDown=cA.bind(this),this._interceptControlUp=dA.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,this.domElement.style.cursor="grab"===e?"grab":"auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1});this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){null!==this._domElementKeyEvents&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(ON),this.update(),this.state=WN}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(t=null){const s=this.object.position;jN.copy(s).sub(this.target),jN.applyQuaternion(this._quat),this._spherical.setFromVector3(jN),this.autoRotate&&this.state===WN&&this._rotateLeft(this._getAutoRotationAngle(t)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let i=this.minAzimuthAngle,r=this.maxAzimuthAngle;isFinite(i)&&isFinite(r)&&(i<-Math.PI?i+=$N:i>Math.PI&&(i-=$N),r<-Math.PI?r+=$N:r>Math.PI&&(r-=$N),this._spherical.theta=i<=r?Math.max(i,Math.min(r,this._spherical.theta)):this._spherical.theta>(i+r)/2?Math.max(i,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),!0===this.enableDamping?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let n=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=e!=this._spherical.radius}if(jN.setFromSpherical(this._spherical),jN.applyQuaternion(this._quatInverse),s.copy(this.target).add(jN),this.object.lookAt(this.target),!0===this.enableDamping?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let t=null;if(this.object.isPerspectiveCamera){const e=jN.length();t=this._clampDistance(e*this._scale);const s=e-t;this.object.position.addScaledVector(this._dollyDirection,s),this.object.updateMatrixWorld(),n=!!s}else if(this.object.isOrthographicCamera){const s=new e.Vector3(this._mouse.x,this._mouse.y,0);s.unproject(this.object);const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),n=i!==this.object.zoom;const r=new e.Vector3(this._mouse.x,this._mouse.y,0);r.unproject(this.object),this.object.position.sub(r).add(s),this.object.updateMatrixWorld(),t=jN.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==t&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(t).add(this.object.position):(zN.origin.copy(this.object.position),zN.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(zN.direction))<GN?this.object.lookAt(this.target):(VN.setFromNormalAndCoplanarPoint(this.object.up,this.target),zN.intersectPlane(VN,this.target))))}else if(this.object.isOrthographicCamera){const e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),n=!0)}return this._scale=1,this._performCursorZoom=!1,!!(n||this._lastPosition.distanceToSquared(this.object.position)>JN||8*(1-this._lastQuaternion.dot(this.object.quaternion))>JN||this._lastTargetPosition.distanceToSquared(this.target)>JN)&&(this.dispatchEvent(ON),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?$N/60*this.autoRotateSpeed*e:$N/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(.01*e);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){jN.setFromMatrixColumn(t,0),jN.multiplyScalar(-e),this._panOffset.add(jN)}_panUp(e,t){!0===this.screenSpacePanning?jN.setFromMatrixColumn(t,1):(jN.setFromMatrixColumn(t,0),jN.crossVectors(this.object.up,jN)),jN.multiplyScalar(e),this._panOffset.add(jN)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;jN.copy(i).sub(this.target);let r=jN.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/s.clientHeight,this.object.matrix),this._panUp(2*t*r/s.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/s.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/s.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const s=this.domElement.getBoundingClientRect(),i=e-s.left,r=t-s.top,n=s.width,a=s.height;this._mouse.x=i/n*2-1,this._mouse.y=-r/a*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($N*this._rotateDelta.x/t.clientHeight),this._rotateUp($N*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp($N*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-$N*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft($N*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-$N*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(1===this._pointers.length)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(s,i)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(s,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(s*s+i*i);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateEnd.set(s,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($N*this._rotateDelta.x/t.clientHeight),this._rotateUp($N*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(s,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(s*s+i*i);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const n=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(n,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return void this._pointers.splice(t,1)}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(t){let s=this._pointerPositions[t.pointerId];void 0===s&&(s=new e.Vector2,this._pointerPositions[t.pointerId]=s),s.set(t.pageX,t.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,s={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:s.deltaY*=16;break;case 2:s.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(s.deltaY*=10),s}}function tA(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e),"grab"===this._cursorStyle&&(this.domElement.style.cursor="grabbing")))}function sA(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function iA(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(kN),this.state=WN,"grab"===this._cursorStyle&&(this.domElement.style.cursor="grab");break;case 1:const t=this._pointers[0],s=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:s.x,pageY:s.y})}}function rA(t){let s;switch(t.button){case 0:s=this.mouseButtons.LEFT;break;case 1:s=this.mouseButtons.MIDDLE;break;case 2:s=this.mouseButtons.RIGHT;break;default:s=-1}switch(s){case e.MOUSE.DOLLY:if(!1===this.enableZoom)return;this._handleMouseDownDolly(t),this.state=qN;break;case e.MOUSE.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=XN}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=HN}break;case e.MOUSE.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=HN}else{if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=XN}break;default:this.state=WN}this.state!==WN&&this.dispatchEvent(UN)}function nA(e){switch(this.state){case HN:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case qN:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case XN:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function aA(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===WN&&(e.preventDefault(),this.dispatchEvent(UN),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(kN))}function oA(e){!1!==this.enabled&&this._handleKeyDown(e)}function hA(t){switch(this._trackPointer(t),this._pointers.length){case 1:switch(this.touches.ONE){case e.TOUCH.ROTATE:if(!1===this.enableRotate)return;this._handleTouchStartRotate(t),this.state=YN;break;case e.TOUCH.PAN:if(!1===this.enablePan)return;this._handleTouchStartPan(t),this.state=KN;break;default:this.state=WN}break;case 2:switch(this.touches.TWO){case e.TOUCH.DOLLY_PAN:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(t),this.state=QN;break;case e.TOUCH.DOLLY_ROTATE:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(t),this.state=ZN;break;default:this.state=WN}break;default:this.state=WN}this.state!==WN&&this.dispatchEvent(UN)}function lA(e){switch(this._trackPointer(e),this.state){case YN:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case KN:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case QN:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case ZN:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=WN}}function uA(e){!1!==this.enabled&&e.preventDefault()}function cA(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function dA(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const pA={type:"change"},mA=1e-6,gA=new e.Quaternion;class fA extends e.Controls{constructor(t,s=null){super(t,s),this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1,this._moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this._moveVector=new e.Vector3(0,0,0),this._rotationVector=new e.Vector3(0,0,0),this._lastQuaternion=new e.Quaternion,this._lastPosition=new e.Vector3,this._status=0,this._onKeyDown=yA.bind(this),this._onKeyUp=bA.bind(this),this._onPointerMove=xA.bind(this),this._onPointerDown=_A.bind(this),this._onPointerUp=vA.bind(this),this._onPointerCancel=TA.bind(this),this._onContextMenu=SA.bind(this),null!==s&&this.connect(s)}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}update(e){if(!1===this.enabled)return;const t=this.object,s=e*this.movementSpeed,i=e*this.rollSpeed;t.translateX(this._moveVector.x*s),t.translateY(this._moveVector.y*s),t.translateZ(this._moveVector.z*s),gA.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(gA),(this._lastPosition.distanceToSquared(t.position)>mA||8*(1-this._lastQuaternion.dot(t.quaternion))>mA)&&(this.dispatchEvent(pA),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){const e=this._moveState.forward||this.autoForward&&!this._moveState.back?1:0;this._moveVector.x=-this._moveState.left+this._moveState.right,this._moveVector.y=-this._moveState.down+this._moveState.up,this._moveVector.z=-e+this._moveState.back}_updateRotationVector(){this._rotationVector.x=-this._moveState.pitchDown+this._moveState.pitchUp,this._rotationVector.y=-this._moveState.yawRight+this._moveState.yawLeft,this._rotationVector.z=-this._moveState.rollRight+this._moveState.rollLeft}_getContainerDimensions(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}}}function yA(e){if(!e.altKey&&!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this._moveState.forward=1;break;case"KeyS":this._moveState.back=1;break;case"KeyA":this._moveState.left=1;break;case"KeyD":this._moveState.right=1;break;case"KeyR":this._moveState.up=1;break;case"KeyF":this._moveState.down=1;break;case"ArrowUp":this._moveState.pitchUp=1;break;case"ArrowDown":this._moveState.pitchDown=1;break;case"ArrowLeft":this._moveState.yawLeft=1;break;case"ArrowRight":this._moveState.yawRight=1;break;case"KeyQ":this._moveState.rollLeft=1;break;case"KeyE":this._moveState.rollRight=1}this._updateMovementVector(),this._updateRotationVector()}}function bA(e){if(!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this._moveState.forward=0;break;case"KeyS":this._moveState.back=0;break;case"KeyA":this._moveState.left=0;break;case"KeyD":this._moveState.right=0;break;case"KeyR":this._moveState.up=0;break;case"KeyF":this._moveState.down=0;break;case"ArrowUp":this._moveState.pitchUp=0;break;case"ArrowDown":this._moveState.pitchDown=0;break;case"ArrowLeft":this._moveState.yawLeft=0;break;case"ArrowRight":this._moveState.yawRight=0;break;case"KeyQ":this._moveState.rollLeft=0;break;case"KeyE":this._moveState.rollRight=0}this._updateMovementVector(),this._updateRotationVector()}}function _A(e){if(!1!==this.enabled)if(this.dragToLook)this._status++;else{switch(e.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1}this._updateMovementVector()}}function xA(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),s=t.size[0]/2,i=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-s)/s,this._moveState.pitchDown=(e.pageY-t.offset[1]-i)/i,this._updateRotationVector()}}function vA(e){if(!1!==this.enabled){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(e.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0}this._updateMovementVector()}this._updateRotationVector()}}function TA(){!1!==this.enabled&&(this.dragToLook?(this._status=0,this._moveState.yawLeft=this._moveState.pitchDown=0):(this._moveState.forward=0,this._moveState.back=0,this._updateMovementVector()),this._updateRotationVector())}function SA(e){!1!==this.enabled&&e.preventDefault()}const wA={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n\t\tuniform float opacity;\n\n\t\tuniform sampler2D tDiffuse;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 texel = texture2D( tDiffuse, vUv );\n\t\t\tgl_FragColor = opacity * texel;\n\n\n\t\t}"};class MA{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const NA=new e.OrthographicCamera(-1,1,1,-1,0,1);class AA extends e.BufferGeometry{constructor(){super(),this.setAttribute("position",new e.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new e.Float32BufferAttribute([0,2,0,0,2,0],2))}}const EA=new AA;class RA{constructor(t){this._mesh=new e.Mesh(EA,t)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,NA)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class CA extends MA{constructor(t,s="tDiffuse"){super(),this.textureID=s,this.uniforms=null,this.material=null,t instanceof e.ShaderMaterial?(this.uniforms=t.uniforms,this.material=t):t&&(this.uniforms=e.UniformsUtils.clone(t.uniforms),this.material=new e.ShaderMaterial({name:void 0!==t.name?t.name:"unspecified",defines:Object.assign({},t.defines),uniforms:this.uniforms,vertexShader:t.vertexShader,fragmentShader:t.fragmentShader})),this._fsQuad=new RA(this.material)}render(e,t,s){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=s.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}class PA extends MA{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,s){const i=e.getContext(),r=e.state;let n,a;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(n=0,a=1):(n=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),r.buffers.stencil.setFunc(i.ALWAYS,n,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(s),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(i.EQUAL,1,4294967295),r.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),r.buffers.stencil.setLocked(!0)}}class BA extends MA{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class FA{constructor(t,s){if(this.renderer=t,this._pixelRatio=t.getPixelRatio(),void 0===s){const i=t.getSize(new e.Vector2);this._width=i.width,this._height=i.height,(s=new e.WebGLRenderTarget(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:e.HalfFloatType})).texture.name="EffectComposer.rt1"}else this._width=s.width,this._height=s.height;this.renderTarget1=s,this.renderTarget2=s.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new CA(wA),this.copyPass.material.blending=e.NoBlending,this.timer=new e.Timer}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);-1!==t&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){this.timer.update(),void 0===e&&(e=this.timer.getDelta());const t=this.renderer.getRenderTarget();let s=!1;for(let t=0,i=this.passes.length;t<i;t++){const i=this.passes[t];if(!1!==i.enabled){if(i.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),i.render(this.renderer,this.writeBuffer,this.readBuffer,e,s),i.needsSwap){if(s){const t=this.renderer.getContext(),s=this.renderer.state.buffers.stencil;s.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),s.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==PA&&(i instanceof PA?s=!0:i instanceof BA&&(s=!1))}}this.renderer.setRenderTarget(t)}reset(t){if(void 0===t){const s=this.renderer.getSize(new e.Vector2);this._pixelRatio=this.renderer.getPixelRatio(),this._width=s.width,this._height=s.height,(t=this.renderTarget1.clone()).setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=t,this.renderTarget2=t.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget1.setSize(s,i),this.renderTarget2.setSize(s,i);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class LA extends MA{constructor(t,s,i=null,r=null,n=null){super(),this.scene=t,this.camera=s,this.overrideMaterial=i,this.clearColor=r,this.clearAlpha=n,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new e.Color}render(e,t,s){const i=e.autoClear;let r,n;e.autoClear=!1,null!==this.overrideMaterial&&(n=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),null!==this.clearColor&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),null!==this.clearAlpha&&(r=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:s),!0===this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),null!==this.clearColor&&e.setClearColor(this._oldClearColor),null!==this.clearAlpha&&e.setClearAlpha(r),null!==this.overrideMaterial&&(this.scene.overrideMaterial=n),e.autoClear=i}}function DA(){return DA=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},DA.apply(null,arguments)}function IA(e,t){return IA=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},IA(e,t)}function OA(e){return OA=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},OA(e)}function UA(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(UA=function(){return!!e})()}function kA(e){var t="function"==typeof Map?new Map:void 0;return kA=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,s)}function s(){return function(e,t,s){if(UA())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return s&&IA(r,s.prototype),r}(e,arguments,OA(this).constructor)}return s.prototype=Object.create(e.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),IA(s,e)},kA(e)}var zA={1:"Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).\n\n",2:"Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).\n\n",3:"Passed an incorrect argument to a color function, please pass a string representation of a color.\n\n",4:"Couldn't generate valid rgb string from %s, it returned %s.\n\n",5:"Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.\n\n",6:"Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).\n\n",7:"Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).\n\n",8:"Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.\n\n",9:"Please provide a number of steps to the modularScale helper.\n\n",10:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",11:'Invalid value passed as base to modularScale, expected number or em string but got "%s"\n\n',12:'Expected a string ending in "px" or a number passed as the first argument to %s(), got "%s" instead.\n\n',13:'Expected a string ending in "px" or a number passed as the second argument to %s(), got "%s" instead.\n\n',14:'Passed invalid pixel value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',15:'Passed invalid base value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',16:"You must provide a template to this method.\n\n",17:"You passed an unsupported selector state to this method.\n\n",18:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",19:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",20:"expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",21:"expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\n\n",22:"expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\n\n",23:"fontFace expects a name of a font-family.\n\n",24:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",25:"fontFace expects localFonts to be an array.\n\n",26:"fontFace expects fileFormats to be an array.\n\n",27:"radialGradient requries at least 2 color-stops to properly render.\n\n",28:"Please supply a filename to retinaImage() as the first argument.\n\n",29:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",30:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",31:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation\n\n",32:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')\n\n",33:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation\n\n",34:"borderRadius expects a radius value as a string or number as the second argument.\n\n",35:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',36:"Property must be a string value.\n\n",37:"Syntax Error at %s.\n\n",38:"Formula contains a function that needs parentheses at %s.\n\n",39:"Formula is missing closing parenthesis at %s.\n\n",40:"Formula has too many closing parentheses at %s.\n\n",41:"All values in a formula must have the same unit or be unitless.\n\n",42:"Please provide a number of steps to the modularScale helper.\n\n",43:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",44:"Invalid value passed as base to modularScale, expected number or em/rem string but got %s.\n\n",45:"Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.\n\n",46:"Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.\n\n",47:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",48:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",49:"Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",50:"Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.\n\n",51:"Expects the first argument object to have the properties prop, fromSize, and toSize.\n\n",52:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",53:"fontFace expects localFonts to be an array.\n\n",54:"fontFace expects fileFormats to be an array.\n\n",55:"fontFace expects a name of a font-family.\n\n",56:"linearGradient requries at least 2 color-stops to properly render.\n\n",57:"radialGradient requries at least 2 color-stops to properly render.\n\n",58:"Please supply a filename to retinaImage() as the first argument.\n\n",59:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",60:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",61:"Property must be a string value.\n\n",62:"borderRadius expects a radius value as a string or number as the second argument.\n\n",63:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',64:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.\n\n",65:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').\n\n",66:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.\n\n",67:"You must provide a template to this method.\n\n",68:"You passed an unsupported selector state to this method.\n\n",69:'Expected a string ending in "px" or a number passed as the first argument to %s(), got %s instead.\n\n',70:'Expected a string ending in "px" or a number passed as the second argument to %s(), got %s instead.\n\n',71:'Passed invalid pixel value %s to %s(), please pass a value like "12px" or 12.\n\n',72:'Passed invalid base value %s to %s(), please pass a value like "12px" or 12.\n\n',73:"Please provide a valid CSS variable.\n\n",74:"CSS variable not found and no default was provided.\n\n",75:"important requires a valid style object, got a %s instead.\n\n",76:"fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.\n\n",77:'remToPx expects a value in "rem" but you provided it in "%s".\n\n',78:'base must be set in "px" or "%" but you set it in "%s".\n'};function VA(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];var i,r=t[0],n=[];for(i=1;i<t.length;i+=1)n.push(t[i]);return n.forEach(function(e){r=r.replace(/%[a-z]/,e)}),r}var GA=function(e){function t(t){var s;if("production"===process.env.NODE_ENV)s=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+t+" for more information.")||this;else{for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];s=e.call(this,VA.apply(void 0,[zA[t]].concat(r)))||this}return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(s)}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,IA(e,t)}(t,e),t}(kA(Error));function jA(e){return Math.round(255*e)}function $A(e,t,s){return jA(e)+","+jA(t)+","+jA(s)}function WA(e,t,s,i){if(void 0===i&&(i=$A),0===t)return i(s,s,s);var r=(e%360+360)%360/60,n=(1-Math.abs(2*s-1))*t,a=n*(1-Math.abs(r%2-1)),o=0,h=0,l=0;r>=0&&r<1?(o=n,h=a):r>=1&&r<2?(o=a,h=n):r>=2&&r<3?(h=n,l=a):r>=3&&r<4?(h=a,l=n):r>=4&&r<5?(o=a,l=n):r>=5&&r<6&&(o=n,l=a);var u=s-n/2;return i(o+u,h+u,l+u)}var HA={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};var qA=/^#[a-fA-F0-9]{6}$/,XA=/^#[a-fA-F0-9]{8}$/,YA=/^#[a-fA-F0-9]{3}$/,KA=/^#[a-fA-F0-9]{4}$/,QA=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,ZA=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,JA=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,eE=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function tE(e){if("string"!=typeof e)throw new GA(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return HA[t]?"#"+HA[t]:e}(e);if(t.match(qA))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(XA)){var s=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:s}}if(t.match(YA))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(KA)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var r=QA.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var n=ZA.exec(t.substring(0,50));if(n)return{red:parseInt(""+n[1],10),green:parseInt(""+n[2],10),blue:parseInt(""+n[3],10),alpha:parseFloat(""+n[4])>1?parseFloat(""+n[4])/100:parseFloat(""+n[4])};var a=JA.exec(t);if(a){var o="rgb("+WA(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",h=QA.exec(o);if(!h)throw new GA(4,t,o);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10)}}var l=eE.exec(t.substring(0,50));if(l){var u="rgb("+WA(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",c=QA.exec(u);if(!c)throw new GA(4,t,u);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new GA(5)}function sE(e){return function(e){var t,s=e.red/255,i=e.green/255,r=e.blue/255,n=Math.max(s,i,r),a=Math.min(s,i,r),o=(n+a)/2;if(n===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var h=n-a,l=o>.5?h/(2-n-a):h/(n+a);switch(n){case s:t=(i-r)/h+(i<r?6:0);break;case i:t=(r-s)/h+2;break;default:t=(s-i)/h+4}return t*=60,void 0!==e.alpha?{hue:t,saturation:l,lightness:o,alpha:e.alpha}:{hue:t,saturation:l,lightness:o}}(tE(e))}var iE=function(e){return 7===e.length&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function rE(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function nE(e){return rE(Math.round(255*e))}function aE(e,t,s){return iE("#"+nE(e)+nE(t)+nE(s))}function oE(e,t,s){return WA(e,t,s,aE)}function hE(e,t,s){if("number"==typeof e&&"number"==typeof t&&"number"==typeof s)return iE("#"+rE(e)+rE(t)+rE(s));if("object"==typeof e&&void 0===t&&void 0===s)return iE("#"+rE(e.red)+rE(e.green)+rE(e.blue));throw new GA(6)}function lE(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?hE(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new GA(7)}function uE(e){if("object"!=typeof e)throw new GA(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return lE(e);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return hE(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&"number"==typeof e.alpha}(e))return function(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?oE(e.hue,e.saturation,e.lightness):"rgba("+WA(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new GA(2)}(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return function(e,t,s){if("object"==typeof e&&void 0===t&&void 0===s)return oE(e.hue,e.saturation,e.lightness);throw new GA(1)}(e);throw new GA(8)}function cE(e,t,s){return function(){var i=s.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):cE(e,t,i)}}function dE(e){return cE(e,e.length,[])}function pE(e,t,s){return Math.max(e,Math.min(t,s))}dE(function(e,t){if("transparent"===t)return t;var s=sE(t);return uE(DA({},s,{hue:s.hue+parseFloat(e)}))}),dE(function(e,t){if("transparent"===t)return t;var s=sE(t);return uE(DA({},s,{lightness:pE(0,1,s.lightness-parseFloat(e))}))}),dE(function(e,t){if("transparent"===t)return t;var s=sE(t);return uE(DA({},s,{saturation:pE(0,1,s.saturation-parseFloat(e))}))}),dE(function(e,t){if("transparent"===t)return t;var s=sE(t);return uE(DA({},s,{lightness:pE(0,1,s.lightness+parseFloat(e))}))});var mE=dE(function(e,t,s){if("transparent"===t)return s;if("transparent"===s)return t;if(0===e)return s;var i=tE(t),r=DA({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),n=tE(s),a=DA({},n,{alpha:"number"==typeof n.alpha?n.alpha:1}),o=r.alpha-a.alpha,h=2*parseFloat(e)-1,l=((h*o===-1?h:h+o)/(1+h*o)+1)/2,u=1-l;return lE({red:Math.floor(r.red*l+a.red*u),green:Math.floor(r.green*l+a.green*u),blue:Math.floor(r.blue*l+a.blue*u),alpha:r.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),gE=mE;var fE=dE(function(e,t){if("transparent"===t)return t;var s=tE(t);return lE(DA({},s,{alpha:pE(0,1,(100*("number"==typeof s.alpha?s.alpha:1)+100*parseFloat(e))/100)}))}),yE=fE;dE(function(e,t){if("transparent"===t)return t;var s=sE(t);return uE(DA({},s,{saturation:pE(0,1,s.saturation+parseFloat(e))}))}),dE(function(e,t){return"transparent"===t?t:uE(DA({},sE(t),{hue:parseFloat(e)}))}),dE(function(e,t){return"transparent"===t?t:uE(DA({},sE(t),{lightness:parseFloat(e)}))}),dE(function(e,t){return"transparent"===t?t:uE(DA({},sE(t),{saturation:parseFloat(e)}))}),dE(function(e,t){return"transparent"===t?t:gE(parseFloat(e),"rgb(0, 0, 0)",t)}),dE(function(e,t){return"transparent"===t?t:gE(parseFloat(e),"rgb(255, 255, 255)",t)}),dE(function(e,t){if("transparent"===t)return t;var s=tE(t);return lE(DA({},s,{alpha:pE(0,1,+(100*("number"==typeof s.alpha?s.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var bE=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-bE.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*bE.Bounce.In(2*e):.5*bE.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e<Number.EPSILON?Number.EPSILON:e)>1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),_E=function(){return performance.now()},xE=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._tweens={},this._tweensAddedDuringUpdate={},this.add.apply(this,e)}return e.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},e.prototype.removeAll=function(){this._tweens={}},e.prototype.add=function(){for(var e,t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];for(var i=0,r=t;i<r.length;i++){var n=r[i];null===(e=n._group)||void 0===e||e.remove(n),n._group=this,this._tweens[n.getId()]=n,this._tweensAddedDuringUpdate[n.getId()]=n}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var s=0,i=e;s<i.length;s++){var r=i[s];r._group=void 0,delete this._tweens[r.getId()],delete this._tweensAddedDuringUpdate[r.getId()]}},e.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},e.prototype.update=function(e,t){void 0===e&&(e=_E()),void 0===t&&(t=!0);var s=Object.keys(this._tweens);if(0!==s.length)for(;s.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<s.length;i++){var r=this._tweens[s[i]],n=!t;r&&!1===r.update(e,n)&&!t&&this.remove(r)}s=Object.keys(this._tweensAddedDuringUpdate)}},e}(),vE={Linear:function(e,t){var s=e.length-1,i=s*t,r=Math.floor(i),n=vE.Utils.Linear;return t<0?n(e[0],e[1],i):t>1?n(e[s],e[s-1],s-i):n(e[r],e[r+1>s?s:r+1],i-r)},Utils:{Linear:function(e,t,s){return(t-e)*s+e}}},TE=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),SE=new xE,wE=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=bE.Linear.None,this._interpolationFunction=vE.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=TE.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=SE,SE.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=_E()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var s in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(s),this._valuesStart[s]=this._valuesStartRepeat[s];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var r in this._valuesEnd)i[r]=this._valuesEnd[r];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,s,i,r){for(var n in s){var a=e[n],o=Array.isArray(a),h=o?"array":typeof a,l=!o&&Array.isArray(s[n]);if("undefined"!==h&&"function"!==h){if(l){if(0===(f=s[n]).length)continue;for(var u=[a],c=0,d=f.length;c<d;c+=1){var p=this._handleRelativeValue(a,f[c]);if(isNaN(p)){l=!1,console.warn("Found invalid interpolation list. Skipping.");break}u.push(p)}l&&(s[n]=u)}if("object"!==h&&!o||!a||l)(void 0===t[n]||r)&&(t[n]=a),o||(t[n]*=1),i[n]=l?s[n].slice().reverse():t[n]||0;else{t[n]=o?[]:{};var m=a;for(var g in m)t[n][g]=m[g];i[n]=o?[]:{};var f=s[n];if(!this._isDynamic){var y={};for(var g in f)y[g]=f[g];s[n]=f=y}this._setupProperties(m,t[n],f,i[n],r)}}}},e.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},e.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},e.prototype.pause=function(e){return void 0===e&&(e=_E()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=_E()),this._isPaused&&this._isPlaying?(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this):this},e.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},e.prototype.group=function(e){return e?(e.add(this),this):(console.warn("tween.group() without args has been removed, use group.add(tween) instead."),this)},e.prototype.remove=function(){var e;return null===(e=this._group)||void 0===e||e.remove(this),this},e.prototype.delay=function(e){return void 0===e&&(e=0),this._delayTime=e,this},e.prototype.repeat=function(e){return void 0===e&&(e=0),this._initialRepeat=e,this._repeat=e,this},e.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},e.prototype.yoyo=function(e){return void 0===e&&(e=!1),this._yoyo=e,this},e.prototype.easing=function(e){return void 0===e&&(e=bE.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=vE.Linear),this._interpolationFunction=e,this},e.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},e.prototype.onStart=function(e){return this._onStartCallback=e,this},e.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},e.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},e.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},e.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},e.prototype.onStop=function(e){return this._onStopCallback=e,this},e.prototype.update=function(t,s){var i,r,n=this;if(void 0===t&&(t=_E()),void 0===s&&(s=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!s)return!1;this.start(t,!0)}if(this._goToEnd=!1,t<this._startTime)return!0;!1===this._onStartCallbackFired&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),!1===this._onEveryStartCallbackFired&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=t-this._startTime,o=this._duration+(null!==(i=this._repeatDelayTime)&&void 0!==i?i:this._delayTime),h=this._duration+this._repeat*o,l=function(){if(0===n._duration)return 1;if(a>h)return 1;var e=Math.trunc(a/o),t=a-e*o,s=Math.min(t/n._duration,1);return 0===s&&a===n._duration?1:s}(),u=this._easingFunction(l);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,u),this._onUpdateCallback&&this._onUpdateCallback(this._object,l),0===this._duration||a>=this._duration){if(this._repeat>0){var c=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(r in isFinite(this._repeat)&&(this._repeat-=c),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[r]||(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*c,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d<p;d++)this._chainedTweens[d].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},e.prototype._updateProperties=function(e,t,s,i){for(var r in s)if(void 0!==t[r]){var n=t[r]||0,a=s[r],o=Array.isArray(e[r]),h=Array.isArray(a);!o&&h?e[r]=this._interpolationFunction(a,i):"object"==typeof a&&a?this._updateProperties(e[r],n,a,i):"number"==typeof(a=this._handleRelativeValue(n,a))&&(e[r]=n+(a-n)*i)}},e.prototype._handleRelativeValue=function(e,t){return"string"!=typeof t?t:"+"===t.charAt(0)||"-"===t.charAt(0)?e+parseFloat(t):parseFloat(t)},e.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],s=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof s?this._valuesStartRepeat[e]+parseFloat(s):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();TE.nextId;var ME=SE;ME.getAll.bind(ME),ME.removeAll.bind(ME),ME.add.bind(ME),ME.remove.bind(ME),ME.update.bind(ME);function NE(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var AE="object"==typeof global&&global&&global.Object===Object&&global,EE="object"==typeof self&&self&&self.Object===Object&&self,RE=AE||EE||Function("return this")(),CE=function(){return RE.Date.now()},PE=/\s/;var BE=/^\s+/;function FE(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&PE.test(e.charAt(t)););return t}(e)+1).replace(BE,""):e}var LE=RE.Symbol,DE=Object.prototype,IE=DE.hasOwnProperty,OE=DE.toString,UE=LE?LE.toStringTag:void 0;var kE=Object.prototype.toString;var zE=LE?LE.toStringTag:void 0;function VE(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":zE&&zE in Object(e)?function(e){var t=IE.call(e,UE),s=e[UE];try{e[UE]=void 0;var i=!0}catch(e){}var r=OE.call(e);return i&&(t?e[UE]=s:delete e[UE]),r}(e):function(e){return kE.call(e)}(e)}var GE=/^[-+]0x[0-9a-f]+$/i,jE=/^0b[01]+$/i,$E=/^0o[0-7]+$/i,WE=parseInt;function HE(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return null!=e&&"object"==typeof e}(e)&&"[object Symbol]"==VE(e)}(e))return NaN;if(NE(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=NE(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=FE(e);var s=jE.test(e);return s||$E.test(e)?WE(e.slice(2),s?2:8):GE.test(e)?NaN:+e}var qE=Math.max,XE=Math.min;function YE(e,t,s){var i,r,n,a,o,h,l=0,u=!1,c=!1,d=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function p(t){var s=i,n=r;return i=r=void 0,l=t,a=e.apply(n,s)}function m(e){var s=e-h;return void 0===h||s>=t||s<0||c&&e-l>=n}function g(){var e=CE();if(m(e))return f(e);o=setTimeout(g,function(e){var s=t-(e-h);return c?XE(s,n-(e-l)):s}(e))}function f(e){return o=void 0,d&&i?p(e):(i=r=void 0,a)}function y(){var e=CE(),s=m(e);if(i=arguments,r=this,h=e,s){if(void 0===o)return function(e){return l=e,o=setTimeout(g,t),u?p(e):a}(h);if(c)return clearTimeout(o),o=setTimeout(g,t),p(h)}return void 0===o&&(o=setTimeout(g,t)),a}return t=HE(t)||0,NE(s)&&(u=!!s.leading,n=(c="maxWait"in s)?qE(HE(s.maxWait)||0,t):n,d="trailing"in s?!!s.trailing:d),y.cancel=function(){void 0!==o&&clearTimeout(o),l=0,i=h=r=o=void 0},y.flush=function(){return void 0===o?a:f(CE())},y}function KE(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function QE(e,t,s){return Object.defineProperty(e,"prototype",{writable:!1}),e}function ZE(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],h=!0,l=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);h=!0);}catch(e){l=!0,r=e}finally{try{if(!h&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(l)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return KE(e,t);var s={}.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?KE(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var JE=QE(function e(t,s){var i=s.default,r=void 0===i?null:i,n=s.triggerUpdate,a=void 0===n||n,o=s.onChange,h=void 0===o?function(e,t){}:o;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name=t,this.defaultVal=r,this.triggerUpdate=a,this.onChange=h});function eR(e){var t=e.stateInit,s=void 0===t?function(){return{}}:t,i=e.props,r=void 0===i?{}:i,n=e.methods,a=void 0===n?{}:n,o=e.aliases,h=void 0===o?{}:o,l=e.init,u=void 0===l?function(){}:l,c=e.update,d=void 0===c?function(){}:c,p=Object.keys(r).map(function(e){return new JE(e,r[e])});return function e(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];var n=!!(this instanceof e?this.constructor:void 0),o=n?i.shift():void 0,l=i[0],c=void 0===l?{}:l,m=Object.assign({},s instanceof Function?s(c):s,{initialised:!1}),g={};function f(e){return y(e,c),b(),f}var y=function(e,t){u.call(f,e,m,t),m.initialised=!0},b=YE(function(){m.initialised&&(d.call(f,m,g),g={})},1);return p.forEach(function(e){f[e.name]=function(e){var t=e.name,s=e.triggerUpdate,i=void 0!==s&&s,r=e.onChange,n=void 0===r?function(e,t){}:r,a=e.defaultVal,o=void 0===a?null:a;return function(e){var s=m[t];if(!arguments.length)return s;var r=void 0===e?o:e;return m[t]=r,n.call(f,r,m,s),!g.hasOwnProperty(t)&&(g[t]=s),i&&b(),f}}(e)}),Object.keys(a).forEach(function(e){f[e]=function(){for(var t,s=arguments.length,i=new Array(s),r=0;r<s;r++)i[r]=arguments[r];return(t=a[e]).call.apply(t,[f,m].concat(i))}}),Object.entries(h).forEach(function(e){var t=ZE(e,2),s=t[0],i=t[1];return f[s]=f[i]}),f.resetProps=function(){return p.forEach(function(e){f[e.name](e.defaultVal)}),f},f.resetProps(),m._rerender=b,n&&o&&f(o),f}}var tR="http://www.w3.org/1999/xhtml",sR={svg:"http://www.w3.org/2000/svg",xhtml:tR,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function iR(e){var t=e+="",s=t.indexOf(":");return s>=0&&"xmlns"!==(t=e.slice(0,s))&&(e=e.slice(s+1)),sR.hasOwnProperty(t)?{space:sR[t],local:e}:e}function rR(e){return function(){var t=this.ownerDocument,s=this.namespaceURI;return s===tR&&t.documentElement.namespaceURI===tR?t.createElement(e):t.createElementNS(s,e)}}function nR(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function aR(e){var t=iR(e);return(t.local?nR:rR)(t)}function oR(){}function hR(e){return null==e?oR:function(){return this.querySelector(e)}}function lR(){return[]}function uR(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function cR(e){return function(t){return t.matches(e)}}var dR=Array.prototype.find;function pR(){return this.firstElementChild}var mR=Array.prototype.filter;function gR(){return Array.from(this.children)}function fR(e){return new Array(e.length)}function yR(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function bR(e,t,s,i,r,n){for(var a,o=0,h=t.length,l=n.length;o<l;++o)(a=t[o])?(a.__data__=n[o],i[o]=a):s[o]=new yR(e,n[o]);for(;o<h;++o)(a=t[o])&&(r[o]=a)}function _R(e,t,s,i,r,n,a){var o,h,l,u=new Map,c=t.length,d=n.length,p=new Array(c);for(o=0;o<c;++o)(h=t[o])&&(p[o]=l=a.call(h,h.__data__,o,t)+"",u.has(l)?r[o]=h:u.set(l,h));for(o=0;o<d;++o)l=a.call(e,n[o],o,n)+"",(h=u.get(l))?(i[o]=h,h.__data__=n[o],u.delete(l)):s[o]=new yR(e,n[o]);for(o=0;o<c;++o)(h=t[o])&&u.get(p[o])===h&&(r[o]=h)}function xR(e){return e.__data__}function vR(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function TR(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function SR(e){return function(){this.removeAttribute(e)}}function wR(e){return function(){this.removeAttributeNS(e.space,e.local)}}function MR(e,t){return function(){this.setAttribute(e,t)}}function NR(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function AR(e,t){return function(){var s=t.apply(this,arguments);null==s?this.removeAttribute(e):this.setAttribute(e,s)}}function ER(e,t){return function(){var s=t.apply(this,arguments);null==s?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,s)}}function RR(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function CR(e){return function(){this.style.removeProperty(e)}}function PR(e,t,s){return function(){this.style.setProperty(e,t,s)}}function BR(e,t,s){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,s)}}function FR(e){return function(){delete this[e]}}function LR(e,t){return function(){this[e]=t}}function DR(e,t){return function(){var s=t.apply(this,arguments);null==s?delete this[e]:this[e]=s}}function IR(e){return e.trim().split(/^|\s+/)}function OR(e){return e.classList||new UR(e)}function UR(e){this._node=e,this._names=IR(e.getAttribute("class")||"")}function kR(e,t){for(var s=OR(e),i=-1,r=t.length;++i<r;)s.add(t[i])}function zR(e,t){for(var s=OR(e),i=-1,r=t.length;++i<r;)s.remove(t[i])}function VR(e){return function(){kR(this,e)}}function GR(e){return function(){zR(this,e)}}function jR(e,t){return function(){(t.apply(this,arguments)?kR:zR)(this,e)}}function $R(){this.textContent=""}function WR(e){return function(){this.textContent=e}}function HR(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function qR(){this.innerHTML=""}function XR(e){return function(){this.innerHTML=e}}function YR(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function KR(){this.nextSibling&&this.parentNode.appendChild(this)}function QR(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function ZR(){return null}function JR(){var e=this.parentNode;e&&e.removeChild(this)}function eC(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function tC(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function sC(e){return function(){var t=this.__on;if(t){for(var s,i=0,r=-1,n=t.length;i<n;++i)s=t[i],e.type&&s.type!==e.type||s.name!==e.name?t[++r]=s:this.removeEventListener(s.type,s.listener,s.options);++r?t.length=r:delete this.__on}}}function iC(e,t,s){return function(){var i,r=this.__on,n=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var a=0,o=r.length;a<o;++a)if((i=r[a]).type===e.type&&i.name===e.name)return this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=n,i.options=s),void(i.value=t);this.addEventListener(e.type,n,s),i={type:e.type,name:e.name,value:t,listener:n,options:s},r?r.push(i):this.__on=[i]}}function rC(e,t,s){var i=RR(e),r=i.CustomEvent;"function"==typeof r?r=new r(t,s):(r=i.document.createEvent("Event"),s?(r.initEvent(t,s.bubbles,s.cancelable),r.detail=s.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function nC(e,t){return function(){return rC(this,e,t)}}function aC(e,t){return function(){return rC(this,e,t.apply(this,arguments))}}yR.prototype={constructor:yR,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}},UR.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var oC=[null];function hC(e,t){this._groups=e,this._parents=t}hC.prototype={constructor:hC,select:function(e){"function"!=typeof e&&(e=hR(e));for(var t=this._groups,s=t.length,i=new Array(s),r=0;r<s;++r)for(var n,a,o=t[r],h=o.length,l=i[r]=new Array(h),u=0;u<h;++u)(n=o[u])&&(a=e.call(n,n.__data__,u,o))&&("__data__"in n&&(a.__data__=n.__data__),l[u]=a);return new hC(i,this._parents)},selectAll:function(e){e="function"==typeof e?uR(e):function(e){return null==e?lR:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,s=t.length,i=[],r=[],n=0;n<s;++n)for(var a,o=t[n],h=o.length,l=0;l<h;++l)(a=o[l])&&(i.push(e.call(a,a.__data__,l,o)),r.push(a));return new hC(i,r)},selectChild:function(e){return this.select(null==e?pR:function(e){return function(){return dR.call(this.children,e)}}("function"==typeof e?e:cR(e)))},selectChildren:function(e){return this.selectAll(null==e?gR:function(e){return function(){return mR.call(this.children,e)}}("function"==typeof e?e:cR(e)))},filter:function(e){"function"!=typeof e&&(e=function(e){return function(){return this.matches(e)}}(e));for(var t=this._groups,s=t.length,i=new Array(s),r=0;r<s;++r)for(var n,a=t[r],o=a.length,h=i[r]=[],l=0;l<o;++l)(n=a[l])&&e.call(n,n.__data__,l,a)&&h.push(n);return new hC(i,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,xR);var s=t?_R:bR,i=this._parents,r=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var n=r.length,a=new Array(n),o=new Array(n),h=new Array(n),l=0;l<n;++l){var u=i[l],c=r[l],d=c.length,p=vR(e.call(u,u&&u.__data__,l,i)),m=p.length,g=o[l]=new Array(m),f=a[l]=new Array(m);s(u,c,g,f,h[l]=new Array(d),p,t);for(var y,b,_=0,x=0;_<m;++_)if(y=g[_]){for(_>=x&&(x=_+1);!(b=f[x])&&++x<m;);y._next=b||null}}return(a=new hC(a,i))._enter=o,a._exit=h,a},enter:function(){return new hC(this._enter||this._groups.map(fR),this._parents)},exit:function(){return new hC(this._exit||this._groups.map(fR),this._parents)},join:function(e,t,s){var i=this.enter(),r=this,n=this.exit();return"function"==typeof e?(i=e(i))&&(i=i.selection()):i=i.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==s?n.remove():s(n),i&&r?i.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,s=this._groups,i=t._groups,r=s.length,n=i.length,a=Math.min(r,n),o=new Array(r),h=0;h<a;++h)for(var l,u=s[h],c=i[h],d=u.length,p=o[h]=new Array(d),m=0;m<d;++m)(l=u[m]||c[m])&&(p[m]=l);for(;h<r;++h)o[h]=s[h];return new hC(o,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,s=e.length;++t<s;)for(var i,r=e[t],n=r.length-1,a=r[n];--n>=0;)(i=r[n])&&(a&&4^i.compareDocumentPosition(a)&&a.parentNode.insertBefore(i,a),a=i);return this},sort:function(e){function t(t,s){return t&&s?e(t.__data__,s.__data__):!t-!s}e||(e=TR);for(var s=this._groups,i=s.length,r=new Array(i),n=0;n<i;++n){for(var a,o=s[n],h=o.length,l=r[n]=new Array(h),u=0;u<h;++u)(a=o[u])&&(l[u]=a);l.sort(t)}return new hC(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,s=e.length;t<s;++t)for(var i=e[t],r=0,n=i.length;r<n;++r){var a=i[r];if(a)return a}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,s=0,i=t.length;s<i;++s)for(var r,n=t[s],a=0,o=n.length;a<o;++a)(r=n[a])&&e.call(r,r.__data__,a,n);return this},attr:function(e,t){var s=iR(e);if(arguments.length<2){var i=this.node();return s.local?i.getAttributeNS(s.space,s.local):i.getAttribute(s)}return this.each((null==t?s.local?wR:SR:"function"==typeof t?s.local?ER:AR:s.local?NR:MR)(s,t))},style:function(e,t,s){return arguments.length>1?this.each((null==t?CR:"function"==typeof t?BR:PR)(e,t,null==s?"":s)):function(e,t){return e.style.getPropertyValue(t)||RR(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?FR:"function"==typeof t?DR:LR)(e,t)):this.node()[e]},classed:function(e,t){var s=IR(e+"");if(arguments.length<2){for(var i=OR(this.node()),r=-1,n=s.length;++r<n;)if(!i.contains(s[r]))return!1;return!0}return this.each(("function"==typeof t?jR:t?VR:GR)(s,t))},text:function(e){return arguments.length?this.each(null==e?$R:("function"==typeof e?HR:WR)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?qR:("function"==typeof e?YR:XR)(e)):this.node().innerHTML},raise:function(){return this.each(KR)},lower:function(){return this.each(QR)},append:function(e){var t="function"==typeof e?e:aR(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var s="function"==typeof e?e:aR(e),i=null==t?ZR:"function"==typeof t?t:hR(t);return this.select(function(){return this.insertBefore(s.apply(this,arguments),i.apply(this,arguments)||null)})},remove:function(){return this.each(JR)},clone:function(e){return this.select(e?tC:eC)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,s){var i,r,n=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",s=e.indexOf(".");return s>=0&&(t=e.slice(s+1),e=e.slice(0,s)),{type:e,name:t}})}(e+""),a=n.length;if(!(arguments.length<2)){for(o=t?iC:sC,i=0;i<a;++i)this.each(o(n[i],t,s));return this}var o=this.node().__on;if(o)for(var h,l=0,u=o.length;l<u;++l)for(i=0,h=o[l];i<a;++i)if((r=n[i]).type===h.type&&r.name===h.name)return h.value},dispatch:function(e,t){return this.each(("function"==typeof t?aC:nC)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,s=e.length;t<s;++t)for(var i,r=e[t],n=0,a=r.length;n<a;++n)(i=r[n])&&(yield i)}};var lC,uC,cC,dC,pC,mC,gC,fC,yC,bC,_C,xC,vC,TC,SC,wC={},MC=[],NC=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,AC=Array.isArray;function EC(e,t){for(var s in t)e[s]=t[s];return e}function RC(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function CC(e,t,s,i,r){var n={type:e,props:t,key:s,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++cC:r,__i:-1,__u:0};return null==r&&null!=uC.vnode&&uC.vnode(n),n}function PC(e){return e.children}function BC(e,t){this.props=e,this.context=t}function FC(e,t){if(null==t)return e.__?FC(e.__,e.__i+1):null;for(var s;t<e.__k.length;t++)if(null!=(s=e.__k[t])&&null!=s.__e)return s.__e;return"function"==typeof e.type?FC(e):null}function LC(e){if(e.__P&&e.__d){var t=e.__v,s=t.__e,i=[],r=[],n=EC({},t);n.__v=t.__v+1,uC.vnode&&uC.vnode(n),WC(e.__P,n,t,e.__n,e.__P.namespaceURI,32&t.__u?[s]:null,i,null==s?FC(t):s,!!(32&t.__u),r),n.__v=t.__v,n.__.__k[n.__i]=n,qC(i,n,r),t.__e=t.__=null,n.__e!=s&&DC(n)}}function DC(e){if(null!=(e=e.__)&&null!=e.__c)return e.__e=e.__c.base=null,e.__k.some(function(t){if(null!=t&&null!=t.__e)return e.__e=e.__c.base=t.__e}),DC(e)}function IC(e){(!e.__d&&(e.__d=!0)&&pC.push(e)&&!OC.__r++||mC!=uC.debounceRendering)&&((mC=uC.debounceRendering)||gC)(OC)}function OC(){try{for(var e,t=1;pC.length;)pC.length>t&&pC.sort(fC),e=pC.shift(),t=pC.length,LC(e)}finally{pC.length=OC.__r=0}}function UC(e,t,s,i,r,n,a,o,h,l,u){var c,d,p,m,g,f,y,b=i&&i.__k||MC,_=t.length;for(h=kC(s,t,b,h,_),c=0;c<_;c++)null!=(p=s.__k[c])&&(d=-1!=p.__i&&b[p.__i]||wC,p.__i=c,f=WC(e,p,d,r,n,a,o,h,l,u),m=p.__e,p.ref&&d.ref!=p.ref&&(d.ref&&KC(d.ref,null,p),u.push(p.ref,p.__c||m,p)),null==g&&null!=m&&(g=m),(y=!!(4&p.__u))||d.__k===p.__k?(h=zC(p,h,e,y),y&&d.__e&&(d.__e=null)):"function"==typeof p.type&&void 0!==f?h=f:m&&(h=m.nextSibling),p.__u&=-7);return s.__e=g,h}function kC(e,t,s,i,r){var n,a,o,h,l,u=s.length,c=u,d=0;for(e.__k=new Array(r),n=0;n<r;n++)null!=(a=t[n])&&"boolean"!=typeof a&&"function"!=typeof a?("string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?a=e.__k[n]=CC(null,a,null,null,null):AC(a)?a=e.__k[n]=CC(PC,{children:a},null,null,null):void 0===a.constructor&&a.__b>0?a=e.__k[n]=CC(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[n]=a,h=n+d,a.__=e,a.__b=e.__b+1,o=null,-1!=(l=a.__i=VC(a,s,h,c))&&(c--,(o=s[l])&&(o.__u|=2)),null==o||null==o.__v?(-1==l&&(r>u?d--:r<u&&d++),"function"!=typeof a.type&&(a.__u|=4)):l!=h&&(l==h-1?d--:l==h+1?d++:(l>h?d--:d++,a.__u|=4))):e.__k[n]=null;if(c)for(n=0;n<u;n++)null!=(o=s[n])&&!(2&o.__u)&&(o.__e==i&&(i=FC(o)),QC(o,o));return i}function zC(e,t,s,i){var r,n;if("function"==typeof e.type){for(r=e.__k,n=0;r&&n<r.length;n++)r[n]&&(r[n].__=e,t=zC(r[n],t,s,i));return t}e.__e!=t&&(i&&(t&&e.type&&!t.parentNode&&(t=FC(e)),s.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function VC(e,t,s,i){var r,n,a,o=e.key,h=e.type,l=t[s],u=null!=l&&!(2&l.__u);if(null===l&&null==o||u&&o==l.key&&h==l.type)return s;if(i>(u?1:0))for(r=s-1,n=s+1;r>=0||n<t.length;)if(null!=(l=t[a=r>=0?r--:n++])&&!(2&l.__u)&&o==l.key&&h==l.type)return a;return-1}function GC(e,t,s){"-"==t[0]?e.setProperty(t,null==s?"":s):e[t]=null==s?"":"number"!=typeof s||NC.test(t)?s:s+"px"}function jC(e,t,s,i,r){var n,a;e:if("style"==t)if("string"==typeof s)e.style.cssText=s;else{if("string"==typeof i&&(e.style.cssText=i=""),i)for(t in i)s&&t in s||GC(e.style,t,"");if(s)for(t in s)i&&s[t]==i[t]||GC(e.style,t,s[t])}else if("o"==t[0]&&"n"==t[1])n=t!=(t=t.replace(xC,"$1")),a=t.toLowerCase(),t=a in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+n]=s,s?i?s[_C]=i[_C]:(s[_C]=vC,e.addEventListener(t,n?SC:TC,n)):e.removeEventListener(t,n?SC:TC,n);else{if("http://www.w3.org/2000/svg"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==s?"":s;break e}catch(e){}"function"==typeof s||(null==s||!1===s&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==s?"":s))}}function $C(e){return function(t){if(this.l){var s=this.l[t.type+e];if(null==t[bC])t[bC]=vC++;else if(t[bC]<s[_C])return;return s(uC.event?uC.event(t):t)}}}function WC(e,t,s,i,r,n,a,o,h,l){var u,c,d,p,m,g,f,y,b,_,x,v,T,S,w,M=t.type;if(void 0!==t.constructor)return null;128&s.__u&&(h=!!(32&s.__u),n=[o=t.__e=s.__e]),(u=uC.__b)&&u(t);e:if("function"==typeof M)try{if(y=t.props,b=M.prototype&&M.prototype.render,_=(u=M.contextType)&&i[u.__c],x=u?_?_.props.value:u.__:i,s.__c?f=(c=t.__c=s.__c).__=c.__E:(b?t.__c=c=new M(y,x):(t.__c=c=new BC(y,x),c.constructor=M,c.render=ZC),_&&_.sub(c),c.state||(c.state={}),c.__n=i,d=c.__d=!0,c.__h=[],c._sb=[]),b&&null==c.__s&&(c.__s=c.state),b&&null!=M.getDerivedStateFromProps&&(c.__s==c.state&&(c.__s=EC({},c.__s)),EC(c.__s,M.getDerivedStateFromProps(y,c.__s))),p=c.props,m=c.state,c.__v=t,d)b&&null==M.getDerivedStateFromProps&&null!=c.componentWillMount&&c.componentWillMount(),b&&null!=c.componentDidMount&&c.__h.push(c.componentDidMount);else{if(b&&null==M.getDerivedStateFromProps&&y!==p&&null!=c.componentWillReceiveProps&&c.componentWillReceiveProps(y,x),t.__v==s.__v||!c.__e&&null!=c.shouldComponentUpdate&&!1===c.shouldComponentUpdate(y,c.__s,x)){t.__v!=s.__v&&(c.props=y,c.state=c.__s,c.__d=!1),t.__e=s.__e,t.__k=s.__k,t.__k.some(function(e){e&&(e.__=t)}),MC.push.apply(c.__h,c._sb),c._sb=[],c.__h.length&&a.push(c);break e}null!=c.componentWillUpdate&&c.componentWillUpdate(y,c.__s,x),b&&null!=c.componentDidUpdate&&c.__h.push(function(){c.componentDidUpdate(p,m,g)})}if(c.context=x,c.props=y,c.__P=e,c.__e=!1,v=uC.__r,T=0,b)c.state=c.__s,c.__d=!1,v&&v(t),u=c.render(c.props,c.state,c.context),MC.push.apply(c.__h,c._sb),c._sb=[];else do{c.__d=!1,v&&v(t),u=c.render(c.props,c.state,c.context),c.state=c.__s}while(c.__d&&++T<25);c.state=c.__s,null!=c.getChildContext&&(i=EC(EC({},i),c.getChildContext())),b&&!d&&null!=c.getSnapshotBeforeUpdate&&(g=c.getSnapshotBeforeUpdate(p,m)),S=null!=u&&u.type===PC&&null==u.key?XC(u.props.children):u,o=UC(e,AC(S)?S:[S],t,s,i,r,n,a,o,h,l),c.base=t.__e,t.__u&=-161,c.__h.length&&a.push(c),f&&(c.__E=c.__=null)}catch(e){if(t.__v=null,h||null!=n)if(e.then){for(t.__u|=h?160:128;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;n[n.indexOf(o)]=null,t.__e=o}else{for(w=n.length;w--;)RC(n[w]);HC(t)}else t.__e=s.__e,t.__k=s.__k,e.then||HC(t);uC.__e(e,t,s)}else null==n&&t.__v==s.__v?(t.__k=s.__k,t.__e=s.__e):o=t.__e=YC(s.__e,t,s,i,r,n,a,h,l);return(u=uC.diffed)&&u(t),128&t.__u?void 0:o}function HC(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(HC))}function qC(e,t,s){for(var i=0;i<s.length;i++)KC(s[i],s[++i],s[++i]);uC.__c&&uC.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){uC.__e(e,t.__v)}})}function XC(e){return"object"!=typeof e||null==e||e.__b>0?e:AC(e)?e.map(XC):EC({},e)}function YC(e,t,s,i,r,n,a,o,h){var l,u,c,d,p,m,g,f=s.props||wC,y=t.props,b=t.type;if("svg"==b?r="http://www.w3.org/2000/svg":"math"==b?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=n)for(l=0;l<n.length;l++)if((p=n[l])&&"setAttribute"in p==!!b&&(b?p.localName==b:3==p.nodeType)){e=p,n[l]=null;break}if(null==e){if(null==b)return document.createTextNode(y);e=document.createElementNS(r,b,y.is&&y),o&&(uC.__m&&uC.__m(t,n),o=!1),n=null}if(null==b)f===y||o&&e.data==y||(e.data=y);else{if(n=n&&lC.call(e.childNodes),!o&&null!=n)for(f={},l=0;l<e.attributes.length;l++)f[(p=e.attributes[l]).name]=p.value;for(l in f)p=f[l],"dangerouslySetInnerHTML"==l?c=p:"children"==l||l in y||"value"==l&&"defaultValue"in y||"checked"==l&&"defaultChecked"in y||jC(e,l,null,p,r);for(l in y)p=y[l],"children"==l?d=p:"dangerouslySetInnerHTML"==l?u=p:"value"==l?m=p:"checked"==l?g=p:o&&"function"!=typeof p||f[l]===p||jC(e,l,p,f[l],r);if(u)o||c&&(u.__html==c.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(c&&(e.innerHTML=""),UC("template"==t.type?e.content:e,AC(d)?d:[d],t,s,i,"foreignObject"==b?"http://www.w3.org/1999/xhtml":r,n,a,n?n[0]:s.__k&&FC(s,0),o,h),null!=n)for(l=n.length;l--;)RC(n[l]);o||(l="value","progress"==b&&null==m?e.removeAttribute("value"):null!=m&&(m!==e[l]||"progress"==b&&!m||"option"==b&&m!=f[l])&&jC(e,l,m,f[l],r),l="checked",null!=g&&g!=e[l]&&jC(e,l,g,f[l],r))}return e}function KC(e,t,s){try{if("function"==typeof e){var i="function"==typeof e.__u;i&&e.__u(),i&&null==t||(e.__u=e(t))}else e.current=t}catch(e){uC.__e(e,s)}}function QC(e,t,s){var i,r;if(uC.unmount&&uC.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||KC(i,null,t)),null!=(i=e.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(e){uC.__e(e,t)}i.base=i.__P=null}if(i=e.__k)for(r=0;r<i.length;r++)i[r]&&QC(i[r],t,s||"function"!=typeof e.type);s||RC(e.__e),e.__c=e.__=e.__e=void 0}function ZC(e,t,s){return this.constructor(e,s)}function JC(e,t,s){var i,r,n;t==document&&(t=document.documentElement),uC.__&&uC.__(e,t),i=!1?null:t.__k,r=[],n=[],WC(t,e=t.__k=function(e,t,s){var i,r,n,a={};for(n in t)"key"==n?i=t[n]:"ref"==n?r=t[n]:a[n]=t[n];if(arguments.length>2&&(a.children=arguments.length>3?lC.call(arguments,2):s),"function"==typeof e&&null!=e.defaultProps)for(n in e.defaultProps)void 0===a[n]&&(a[n]=e.defaultProps[n]);return CC(e,a,i,r,null)}(PC,null,[e]),i||wC,wC,t.namespaceURI,i?null:t.firstChild?lC.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,n),qC(r,e,n)}function eP(e,t,s){var i,r,n,a,o=EC({},e.props);for(n in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==n?i=t[n]:"ref"==n?r=t[n]:o[n]=void 0===t[n]&&null!=a?a[n]:t[n];return arguments.length>2&&(o.children=arguments.length>3?lC.call(arguments,2):s),CC(e.type,o,i||e.key,r||e.ref,null)}function tP(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function sP(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function iP(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),s.push.apply(s,i)}return s}function rP(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],h=!0,l=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);h=!0);}catch(e){l=!0,r=e}finally{try{if(!h&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(l)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return tP(e,t);var s={}.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?tP(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function nP(e){return nP="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},nP(e)}lC=MC.slice,uC={__e:function(e,t,s,i){for(var r,n,a;t=t.__;)if((r=t.__c)&&!r.__)try{if((n=r.constructor)&&null!=n.getDerivedStateFromError&&(r.setState(n.getDerivedStateFromError(e)),a=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(e,i||{}),a=r.__d),a)return r.__E=r}catch(t){e=t}throw e}},cC=0,dC=function(e){return null!=e&&void 0===e.constructor},BC.prototype.setState=function(e,t){var s;s=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=EC({},this.state),"function"==typeof e&&(e=e(EC({},s),this.props)),e&&EC(s,e),null!=e&&this.__v&&(t&&this._sb.push(t),IC(this))},BC.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),IC(this))},BC.prototype.render=PC,pC=[],gC="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,fC=function(e,t){return e.__v.__b-t.__v.__b},OC.__r=0,yC=Math.random().toString(8),bC="__d"+yC,_C="__a"+yC,xC=/(PointerCapture)$|Capture$/i,vC=0,TC=$C(!1),SC=$C(!0);var aP=function(e){if("object"!==nP(e))return e;var t,s=eP(e);s.props&&(s.props=function(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?iP(Object(s),!0).forEach(function(t){sP(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):iP(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}({},s.props),null!=s&&null!==(t=s.props)&&void 0!==t&&t.children&&(s.props.children=Array.isArray(s.props.children)?s.props.children.map(aP):aP(s.props.children)));return s};!function(e,t){void 0===t&&(t={});var s=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===s&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".float-tooltip-kap {\n position: absolute;\n width: max-content; /* prevent shrinking near right edge */\n max-width: max(50%, 150px);\n padding: 3px 5px;\n border-radius: 3px;\n font: 12px sans-serif;\n color: #eee;\n background: rgba(0,0,0,0.6);\n pointer-events: none;\n}\n");var oP=eR({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(e,t){var s=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).style,i=void 0===s?{}:s,r=function(e){return"string"==typeof e?new hC([[document.querySelector(e)]],[document.documentElement]):new hC([[e]],oC)}(!!e&&"object"===nP(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===r.style("position")&&r.style("position","relative"),t.tooltipEl=r.append("div").attr("class","float-tooltip-kap"),Object.entries(i).forEach(function(e){var s=rP(e,2),i=s[0],r=s[1];return t.tooltipEl.style(i,r)}),t.tooltipEl.style("left","-10000px").style("display","none");var n="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,r.on("mousemove.".concat(n),function(e){t.mouseInside=!0;var s=function(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var s=t.ownerSVGElement||t;if(s.createSVGPoint){var i=s.createSVGPoint();return i.x=e.clientX,i.y=e.clientY,[(i=i.matrixTransform(t.getScreenCTM().inverse())).x,i.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),i=r.node(),n=i.offsetWidth,a=i.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(s[0]/n*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-s[1]<100?"calc(-100% - 6px)":"21px":"number"==typeof t.offsetY?t.offsetY<0?"calc(-100% - ".concat(Math.abs(t.offsetY),"px)"):"".concat(t.offsetY,"px"):t.offsetY];t.tooltipEl.style("left",s[0]+"px").style("top",s[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseover.".concat(n),function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseout.".concat(n),function(){t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){var t,s;e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append(function(){return e.content})):"string"==typeof e.content?e.tooltipEl.html(e.content):!function(e){return dC(eP(e))}(e.content)?(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):(e.tooltipEl.text(""),t=e.content,delete(s=e.tooltipEl.node()).__k,JC(aP(t),s)):e.tooltipEl.text("")}}),hP=function(e){e instanceof Array?e.forEach(hP):(e.map&&e.map.dispose(),e.dispose())},lP=function(e){e.geometry&&e.geometry.dispose(),e.material&&hP(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(lP)},uP=window.THREE?window.THREE:{WebGLRenderer:e.WebGLRenderer,Scene:e.Scene,PerspectiveCamera:e.PerspectiveCamera,Raycaster:e.Raycaster,SRGBColorSpace:e.SRGBColorSpace,TextureLoader:e.TextureLoader,Vector2:e.Vector2,Vector3:e.Vector3,Box3:e.Box3,Color:e.Color,Mesh:e.Mesh,SphereGeometry:e.SphereGeometry,MeshBasicMaterial:e.MeshBasicMaterial,BackSide:e.BackSide,Timer:e.Timer},cP=eR({props:{width:{default:window.innerWidth,onChange:function(e,t,s){isNaN(e)&&(t.width=s)}},height:{default:window.innerHeight,onChange:function(e,t,s){isNaN(e)&&(t.height=s)}},viewOffset:{default:[0,0]},backgroundColor:{default:"#000011"},backgroundImageUrl:{},onBackgroundImageLoaded:{},showNavInfo:{default:!0},skyRadius:{default:5e4},objects:{default:[]},lights:{default:[]},enablePointerInteraction:{default:!0,onChange:function(e,t){t.hoverObj=null,t.tooltip&&t.tooltip.content(null)},triggerUpdate:!1},pointerRaycasterThrottleMs:{default:50,triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},pointsHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{triggerUpdate:!1},hoverFilter:{default:function(){return!0},triggerUpdate:!1},tooltipContent:{triggerUpdate:!1},hoverDuringDrag:{default:!1,triggerUpdate:!1},clickAfterDrag:{default:!1,triggerUpdate:!1},onHover:{default:function(){},triggerUpdate:!1},onClick:{default:function(){},triggerUpdate:!1},onRightClick:{triggerUpdate:!1}},methods:{tick:function(e){if(e.initialised){e.controls.enabled&&e.controls.update&&e.controls.update(Math.min(1,e.timer.update().getDelta())),e.postProcessingComposer?e.postProcessingComposer.render():e.renderer.render(e.scene,e.camera),e.extraRenderers.forEach(function(t){return t.render(e.scene,e.camera)});var t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;var s=null;if(e.hoverDuringDrag||!e.isPointerDragging){var i=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&i.sort(function(t,s){return e.hoverOrderComparator(t.object,s.object)});var r=i.find(function(t){return e.hoverFilter(t.object)})||null;s=r?r.object:null,e.intersection=r||null}s!==e.hoverObj&&(e.onHover(s,e.hoverObj,e.intersection),e.tooltip.content(s&&function(e){return"function"==typeof e?e:"string"==typeof e?function(t){return t[e]}:function(t){return e}}(e.tooltipContent)(s,e.intersection)||null),e.hoverObj=s)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos;return{x:t.x,y:t.y}},cameraPosition:function(e,t,s,i){var r=e.camera;if(t&&e.initialised){var n,a,o=t,h=s||{x:0,y:0,z:0};if(null===(n=e.povPosTween)||void 0===n||n.end(),null===(a=e.povTgtTween)||void 0===a||a.end(),i){var l=Object.assign({},r.position),u=p();e.tweenGroup.add(e.povPosTween=new wE(l).to(o,i).easing(bE.Quadratic.Out).onUpdate(c).onComplete(function(){e.povPosTween=void 0,e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(e.povTgtTween=new wE(u).to(h,i/3).easing(bE.Quadratic.Out).onUpdate(d).onComplete(function(){e.povTgtTween=void 0,e.tweenGroup.remove(this)}).start())}else c(o),d(h);return this}return Object.assign({},r.position,{lookAt:p()});function c(e){var t=e.x,s=e.y,i=e.z;void 0!==t&&(r.position.x=t),void 0!==s&&(r.position.y=s),void 0!==i&&(r.position.z=i)}function d(t){var s=new uP.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=s:r.lookAt(s)}function p(){return Object.assign(new uP.Vector3(0,0,-1e3).applyQuaternion(r.quaternion).add(r.position))}},zoomToFit:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10,i=arguments.length,r=new Array(i>3?i-3:0),n=3;n<i;n++)r[n-3]=arguments[n];return this.fitToBbox(this.getBbox.apply(this,r),t,s)},fitToBbox:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:10,a=e.camera;if(t){var o=new uP.Vector3(0,0,0),h=2*Math.max.apply(Math,r(Object.entries(t).map(function(e){var t=i(e,2),s=t[0],n=t[1];return Math.max.apply(Math,r(n.map(function(e){return Math.abs(o[s]-e)})))}))),l=(1-2*n/e.height)*a.fov,u=h/Math.atan(l*Math.PI/180),c=u/a.aspect,d=Math.max(u,c);if(d>0){var p=o.clone().sub(a.position).normalize().multiplyScalar(-d);this.cameraPosition(p,o,s)}}return this},getBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0},i=new uP.Box3(new uP.Vector3(0,0,0),new uP.Vector3(0,0,0)),n=e.objects.filter(t);return n.length?(n.forEach(function(e){return i.expandByObject(e)}),Object.assign.apply(Object,r(["x","y","z"].map(function(e){return s({},e,[i.min[e],i.max[e]])})))):null},getScreenCoords:function(e,t,s,i){var r=new uP.Vector3(t,s,i);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,s){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=new uP.Vector2(t/e.width*2-1,-s/e.height*2+1),n=new uP.Raycaster;return n.setFromCamera(r,e.camera),Object.assign({},n.ray.at(i,new uP.Vector3))},intersectingObjects:function(e,t,s){var i=new uP.Vector2(t/e.width*2-1,-s/e.height*2+1),r=new uP.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(i,e.camera),r.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls},_destructor:function(e){var t,s,i;!function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),lP(t)}}(e.scene),null===(t=e.controls)||void 0===t||t.dispose(),null===(s=e.renderer)||void 0===s||s.dispose(),null===(i=e.postProcessingComposer)||void 0===i||i.dispose()}},stateInit:function(){return{scene:new uP.Scene,camera:new uP.PerspectiveCamera,timer:new uP.Timer,tweenGroup:new xE,lastRaycasterCheck:0}},init:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=s.controlType,n=void 0===i?"trackball":i,a=s.useWebGPU,o=void 0!==a&&a,h=s.rendererConfig,l=void 0===h?{}:h,u=s.extraRenderers,c=void 0===u?[]:u,d=s.waitForLoadComplete,p=void 0===d||d;e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[n]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new oP(t.container),t.pointerPos=new uP.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(e){return t.container.addEventListener(e,function(s){if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===s.type&&(s.pressure>0||t.isPointerPressed)&&("mouse"===s.pointerType||void 0===s.movementX||[s.movementX,s.movementY].some(function(e){return Math.abs(e)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var i=(r=t.container,n=r.getBoundingClientRect(),a=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,{top:n.top+o,left:n.left+a});t.pointerPos.x=s.pageX-i.left,t.pointerPos.y=s.pageY-i.top}var r,n,a,o},{passive:!0})}),t.container.addEventListener("pointerup",function(e){t.isPointerPressed&&(t.isPointerPressed=!1,t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag)||requestAnimationFrame(function(){0===e.button&&t.onClick(t.hoverObj||null,e,t.intersection),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",function(e){t.onRightClick&&e.preventDefault()}),t.renderer=new(o?tN:uP.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},l)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=c,t.extraRenderers.forEach(function(e){e.domElement.style.position="absolute",e.domElement.style.top="0px",e.domElement.style.pointerEvents="none",t.container.appendChild(e.domElement)}),t.postProcessingComposer=new FA(t.renderer),t.postProcessingComposer.addPass(new LA(t.scene,t.camera)),t.controls=new{trackball:TN,orbit:eA,fly:fA}[n](t.camera,t.renderer.domElement),"fly"===n&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==n&&"orbit"!==n||(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",function(){t.controlsEngaged=!0}),t.controls.addEventListener("change",function(){t.controlsEngaged&&(t.controlsDragging=!0)}),t.controls.addEventListener("end",function(){t.controlsEngaged=!1,t.controlsDragging=!1})),[t.renderer,t.postProcessingComposer].concat(r(t.extraRenderers)).forEach(function(e){return e.setSize(t.width,t.height)}),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new uP.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!p,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var s,i=e.width,n=e.height;e.container.style.width="".concat(i,"px"),e.container.style.height="".concat(n,"px"),[e.renderer,e.postProcessingComposer].concat(r(e.extraRenderers)).forEach(function(e){return e.setSize(i,n)}),e.camera.aspect=i/n;var a=e.viewOffset.slice(0,2);a.some(function(e){return e})&&(s=e.camera).setViewOffset.apply(s,[i,n].concat(r(a),[i,n])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var o,h=e.width,l=e.height,u=e.viewOffset.slice(0,2);u.some(function(e){return e})?(o=e.camera).setViewOffset.apply(o,[h,l].concat(r(u),[h,l])):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=2.5*e.skyRadius,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new uP.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=tE(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new uP.Color(yE(1,e.backgroundColor)),c)}function d(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new uP.TextureLoader).load(e.backgroundImageUrl,function(t){t.colorSpace=uP.SRGBColorSpace,e.skysphere.material=new uP.MeshBasicMaterial({map:t,side:uP.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&d()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&d())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(function(t){return e.scene.remove(t)}),e.lights.forEach(function(t){return e.scene.add(t)})),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(function(t){return e.scene.remove(t)}),e.objects.forEach(function(t){return e.scene.add(t)}))}});return cP});