three-render-objects 1.40.0 → 1.40.1

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.40.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,o,a=[],h=!0,l=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(a.push(i.value),a.length!==t);h=!0);}catch(e){l=!0,r=e}finally{try{if(!h&&null!=s.return&&(o=s.return(),Object(o)!==o))return}finally{if(l)throw r}}return a}}(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 o="175",a=100,h=101,l=102,u=200,c=201,d=202,p=203,m=204,g=205,f=206,y=207,b=208,x=209,_=210,v=301,T=302,w=303,S=304,M=1e3,N=1001,E=1002,A=1003,C=1004,R=1005,P=1006,F=1007,B=1008,I=1009,L=1010,D=1011,O=1012,k=1013,U=1014,z=1015,V=1016,G=1020,j=1022,H=1023,W=1026,$=1027,q=1028,X=1029,Y=1030,K=1031,Q=1033,Z=33776,J=33777,ee=33778,te=33779,se=37492,ie=37496,re=37808,ne=37809,oe=37810,ae=37811,he=37812,le=37813,ue=37814,ce=37815,de=37816,pe=37817,me=37818,ge=37819,fe=37820,ye=37821,be=36492,xe="",_e="srgb",ve="srgb-linear",Te="linear",we="srgb",Se=7680,Me=512,Ne=513,Ee=514,Ae=515,Ce=516,Re=517,Pe=518,Fe=519,Be=35044,Ie=35048,Le=2e3,De=2001;class Oe{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 ke=["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 Ue=1234567;const ze=Math.PI/180,Ve=180/Math.PI;function Ge(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(ke[255&e]+ke[e>>8&255]+ke[e>>16&255]+ke[e>>24&255]+"-"+ke[255&t]+ke[t>>8&255]+"-"+ke[t>>16&15|64]+ke[t>>24&255]+"-"+ke[63&s|128]+ke[s>>8&255]+"-"+ke[s>>16&255]+ke[s>>24&255]+ke[255&i]+ke[i>>8&255]+ke[i>>16&255]+ke[i>>24&255]).toLowerCase()}function je(e,t,s){return Math.max(t,Math.min(s,e))}function He(e,t){return(e%t+t)%t}function We(e,t,s){return(1-s)*e+s*t}function $e(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 qe(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 Xe={DEG2RAD:ze,RAD2DEG:Ve,generateUUID:Ge,clamp:je,euclideanModulo:He,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:We,damp:function(e,t,s,i){return We(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(He(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&&(Ue=e);let t=Ue+=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*ze},radToDeg:function(e){return e*Ve},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,o=Math.sin,a=n(s/2),h=o(s/2),l=n((t+i)/2),u=o((t+i)/2),c=n((t-i)/2),d=o((t-i)/2),p=n((i-t)/2),m=o((i-t)/2);switch(r){case"XYX":e.set(a*u,h*c,h*d,a*l);break;case"YZY":e.set(h*d,a*u,h*c,a*l);break;case"ZXZ":e.set(h*c,h*d,a*u,a*l);break;case"XZX":e.set(a*u,h*m,h*p,a*l);break;case"YXY":e.set(h*p,a*u,h*m,a*l);break;case"ZYZ":e.set(h*m,h*p,a*u,a*l);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:qe,denormalize:$e};class Ye{constructor(e=0,t=0){Ye.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=je(this.x,e.x,t.x),this.y=je(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=je(this.x,e,t),this.y=je(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(je(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(je(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 Ke{constructor(e,t,s,i,r,n,o,a,h){Ke.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,o,a,h)}set(e,t,s,i,r,n,o,a,h){const l=this.elements;return l[0]=e,l[1]=i,l[2]=o,l[3]=t,l[4]=r,l[5]=a,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],o=s[3],a=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],x=i[7],_=i[2],v=i[5],T=i[8];return r[0]=n*m+o*y+a*_,r[3]=n*g+o*b+a*v,r[6]=n*f+o*x+a*T,r[1]=h*m+l*y+u*_,r[4]=h*g+l*b+u*v,r[7]=h*f+l*x+u*T,r[2]=c*m+d*y+p*_,r[5]=c*g+d*b+p*v,r[8]=c*f+d*x+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],o=e[5],a=e[6],h=e[7],l=e[8];return t*n*l-t*o*h-s*r*l+s*o*a+i*r*h-i*n*a}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],h=e[7],l=e[8],u=l*n-o*h,c=o*a-l*r,d=h*r-n*a,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]=(o*s-i*n)*m,e[3]=c*m,e[4]=(l*t-i*a)*m,e[5]=(i*r-o*t)*m,e[6]=d*m,e[7]=(s*a-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,o){const a=Math.cos(r),h=Math.sin(r);return this.set(s*a,s*h,-s*(a*n+h*o)+n+e,-i*h,i*a,-i*(-h*n+a*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Qe.makeScale(e,t)),this}rotate(e){return this.premultiply(Qe.makeRotation(-e)),this}translate(e,t){return this.premultiply(Qe.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 Qe=new Ke;function Ze(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Je(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const et={};function tt(e){e in et||(et[e]=!0,console.warn(e))}const st=(new Ke).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),it=(new Ke).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function rt(){const e={enabled:!0,workingColorSpace:ve,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===we&&(e.r=ot(e.r),e.g=ot(e.g),e.b=ot(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===we&&(e.r=at(e.r),e.g=at(e.g),e.b=at(e.b)),e):e},fromWorkingColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===xe?Te:this.spaces[e].transfer},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}},t=[.64,.33,.3,.6,.15,.06],s=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[ve]:{primaries:t,whitePoint:i,transfer:Te,toXYZ:st,fromXYZ:it,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:_e},outputColorSpaceConfig:{drawingBufferColorSpace:_e}},[_e]:{primaries:t,whitePoint:i,transfer:we,toXYZ:st,fromXYZ:it,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:_e}}}),e}const nt=rt();function ot(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function at(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let ht;class lt{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=Je("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=Je("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*ot(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*ot(t[e]/255)):t[e]=ot(t[e]);return{data:t,width:e.width,height:e.height}}return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let ut=0;class ct{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:ut++}),this.uuid=Ge(),this.data=e,this.dataReady=!0,this.version=0}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(dt(i[t].image)):e.push(dt(i[t]))}else e=dt(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function dt(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?lt.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let pt=0;class mt extends Oe{constructor(e=mt.DEFAULT_IMAGE,t=mt.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,o=1023,a=1009,h=mt.DEFAULT_ANISOTROPY,l=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:pt++}),this.uuid=Ge(),this.name="",this.source=new ct(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=o,this.internalFormat=null,this.type=a,this.offset=new Ye(0,0),this.repeat=new Ye(1,1),this.center=new Ye(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ke,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=l,this.userData={},this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.pmremVersion=0}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)}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.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}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.6,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 M:e.x=e.x-Math.floor(e.x);break;case N:e.x=e.x<0?0:1;break;case E: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 M:e.y=e.y-Math.floor(e.y);break;case N:e.y=e.y<0?0:1;break;case E: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++}}mt.DEFAULT_IMAGE=null,mt.DEFAULT_MAPPING=300,mt.DEFAULT_ANISOTROPY=1;class gt{constructor(e=0,t=0,s=0,i=1){gt.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,o=.1,a=e.elements,h=a[0],l=a[4],u=a[8],c=a[1],d=a[5],p=a[9],m=a[2],g=a[6],f=a[10];if(Math.abs(l-c)<n&&Math.abs(u-m)<n&&Math.abs(p-g)<n){if(Math.abs(l+c)<o&&Math.abs(u+m)<o&&Math.abs(p+g)<o&&Math.abs(h+d+f-3)<o)return this.set(1,0,0,0),this;t=Math.PI;const e=(h+1)/2,a=(d+1)/2,y=(f+1)/2,b=(l+c)/4,x=(u+m)/4,_=(p+g)/4;return e>a&&e>y?e<n?(s=0,i=.707106781,r=.707106781):(s=Math.sqrt(e),i=b/s,r=x/s):a>y?a<n?(s=.707106781,i=0,r=.707106781):(i=Math.sqrt(a),s=b/i,r=_/i):y<n?(s=.707106781,i=.707106781,r=0):(r=Math.sqrt(y),s=x/r,i=_/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=je(this.x,e.x,t.x),this.y=je(this.y,e.y,t.y),this.z=je(this.z,e.z,t.z),this.w=je(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=je(this.x,e,t),this.y=je(this.y,e,t),this.z=je(this.z,e,t),this.w=je(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(je(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 ft extends Oe{constructor(e=1,t=1,s={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new gt(0,0,e,t),this.scissorTest=!1,this.viewport=new gt(0,0,e,t);const i={width:e,height:t,depth:1};s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:P,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},s);const r=new mt(i,s.mapping,s.wrapS,s.wrapT,s.magFilter,s.minFilter,s.format,s.type,s.anisotropy,s.colorSpace);r.flipY=!1,r.generateMipmaps=s.generateMipmaps,r.internalFormat=s.internalFormat,this.textures=[];const 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.depthBuffer=s.depthBuffer,this.stencilBuffer=s.stencilBuffer,this.resolveDepthBuffer=s.resolveDepthBuffer,this.resolveStencilBuffer=s.resolveStencilBuffer,this._depthTexture=s.depthTexture,this.samples=s.samples}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;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 ct(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 yt extends ft{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}class bt extends mt{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=A,this.minFilter=A,this.wrapR=N,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class xt{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,o){let a=s[i+0],h=s[i+1],l=s[i+2],u=s[i+3];const c=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(0===o)return e[t+0]=a,e[t+1]=h,e[t+2]=l,void(e[t+3]=u);if(1===o)return e[t+0]=c,e[t+1]=d,e[t+2]=p,void(e[t+3]=m);if(u!==m||a!==c||h!==d||l!==p){let e=1-o;const t=a*c+h*d+l*p+u*m,s=t>=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),n=Math.atan2(r,t*s);e=Math.sin(e*n)/r,o=Math.sin(o*n)/r}const r=o*s;if(a=a*e+c*r,h=h*e+d*r,l=l*e+p*r,u=u*e+m*r,e===1-o){const e=1/Math.sqrt(a*a+h*h+l*l+u*u);a*=e,h*=e,l*=e,u*=e}}e[t]=a,e[t+1]=h,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,s,i,r,n){const o=s[i],a=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]=o*p+l*u+a*d-h*c,e[t+1]=a*p+l*c+h*u-o*d,e[t+2]=h*p+l*d+o*c-a*u,e[t+3]=l*p-o*u-a*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,o=Math.cos,a=Math.sin,h=o(s/2),l=o(i/2),u=o(r/2),c=a(s/2),d=a(i/2),p=a(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:console.warn("THREE.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],o=t[5],a=t[9],h=t[2],l=t[6],u=t[10],c=s+o+u;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(l-a)*e,this._y=(r-h)*e,this._z=(n-i)*e}else if(s>o&&s>u){const e=2*Math.sqrt(1+s-o-u);this._w=(l-a)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+h)/e}else if(o>u){const e=2*Math.sqrt(1+o-s-u);this._w=(r-h)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(a+l)/e}else{const e=2*Math.sqrt(1+u-s-o);this._w=(n-i)/e,this._x=(r+h)/e,this._y=(a+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return s<Number.EPSILON?(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(je(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,o=t._x,a=t._y,h=t._z,l=t._w;return this._x=s*l+n*o+i*h-r*a,this._y=i*l+n*a+r*o-s*h,this._z=r*l+n*h+s*a-i*o,this._w=n*l-s*o-i*a-r*h,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const s=this._x,i=this._y,r=this._z,n=this._w;let o=n*e._w+s*e._x+i*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=n,this._x=s,this._y=i,this._z=r,this;const a=1-o*o;if(a<=Number.EPSILON){const e=1-t;return this._w=e*n+t*this._w,this._x=e*s+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const h=Math.sqrt(a),l=Math.atan2(h,o),u=Math.sin((1-t)*l)/h,c=Math.sin(t*l)/h;return this._w=n*u+this._w*c,this._x=s*u+this._x*c,this._y=i*u+this._y*c,this._z=r*u+this._z*c,this._onChangeCallback(),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 _t{constructor(e=0,t=0,s=0){_t.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(Tt.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Tt.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,o=e.z,a=e.w,h=2*(n*i-o*s),l=2*(o*t-r*i),u=2*(r*s-n*t);return this.x=t+a*h+n*u-o*l,this.y=s+a*l+o*h-r*u,this.z=i+a*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=je(this.x,e.x,t.x),this.y=je(this.y,e.y,t.y),this.z=je(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=je(this.x,e,t),this.y=je(this.y,e,t),this.z=je(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(je(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,o=t.y,a=t.z;return this.x=i*a-r*o,this.y=r*n-s*a,this.z=s*o-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 vt.copy(this).projectOnVector(e),this.sub(vt)}reflect(e){return this.sub(vt.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(je(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 vt=new _t,Tt=new xt;class wt{constructor(e=new _t(1/0,1/0,1/0),t=new _t(-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(Mt.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(Mt.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=Mt.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,Mt):Mt.fromBufferAttribute(i,t),Mt.applyMatrix4(e.matrixWorld),this.expandByPoint(Mt);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),Nt.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),Nt.copy(s.boundingBox)),Nt.applyMatrix4(e.matrixWorld),this.union(Nt)}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,Mt),Mt.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(Bt),It.subVectors(this.max,Bt),Et.subVectors(e.a,Bt),At.subVectors(e.b,Bt),Ct.subVectors(e.c,Bt),Rt.subVectors(At,Et),Pt.subVectors(Ct,At),Ft.subVectors(Et,Ct);let t=[0,-Rt.z,Rt.y,0,-Pt.z,Pt.y,0,-Ft.z,Ft.y,Rt.z,0,-Rt.x,Pt.z,0,-Pt.x,Ft.z,0,-Ft.x,-Rt.y,Rt.x,0,-Pt.y,Pt.x,0,-Ft.y,Ft.x,0];return!!Ot(t,Et,At,Ct,It)&&(t=[1,0,0,0,1,0,0,0,1],!!Ot(t,Et,At,Ct,It)&&(Lt.crossVectors(Rt,Pt),t=[Lt.x,Lt.y,Lt.z],Ot(t,Et,At,Ct,It)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Mt).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Mt).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()||(St[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),St[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),St[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),St[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),St[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),St[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),St[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),St[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(St)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const St=[new _t,new _t,new _t,new _t,new _t,new _t,new _t,new _t],Mt=new _t,Nt=new wt,Et=new _t,At=new _t,Ct=new _t,Rt=new _t,Pt=new _t,Ft=new _t,Bt=new _t,It=new _t,Lt=new _t,Dt=new _t;function Ot(e,t,s,i,r){for(let n=0,o=e.length-3;n<=o;n+=3){Dt.fromArray(e,n);const o=r.x*Math.abs(Dt.x)+r.y*Math.abs(Dt.y)+r.z*Math.abs(Dt.z),a=t.dot(Dt),h=s.dot(Dt),l=i.dot(Dt);if(Math.max(-Math.max(a,h,l),Math.min(a,h,l))>o)return!1}return!0}const kt=new wt,Ut=new _t,zt=new _t;class Vt{constructor(e=new _t,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):kt.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;Ut.subVectors(e,this.center);const t=Ut.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Ut,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):(zt.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ut.copy(e.center).add(zt)),this.expandByPoint(Ut.copy(e.center).sub(zt))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Gt=new _t,jt=new _t,Ht=new _t,Wt=new _t,$t=new _t,qt=new _t,Xt=new _t;class Yt{constructor(e=new _t,t=new _t(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,Gt)),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=Gt.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Gt.copy(this.origin).addScaledVector(this.direction,t),Gt.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){jt.copy(e).add(t).multiplyScalar(.5),Ht.copy(t).sub(e).normalize(),Wt.copy(this.origin).sub(jt);const r=.5*e.distanceTo(t),n=-this.direction.dot(Ht),o=Wt.dot(this.direction),a=-Wt.dot(Ht),h=Wt.lengthSq(),l=Math.abs(1-n*n);let u,c,d,p;if(l>0)if(u=n*a-o,c=n*o-a,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*o)+c*(n*u+c+2*a)+h}else c=r,u=Math.max(0,-(n*c+o)),d=-u*u+c*(c+2*a)+h;else c=-r,u=Math.max(0,-(n*c+o)),d=-u*u+c*(c+2*a)+h;else c<=-p?(u=Math.max(0,-(-n*r+o)),c=u>0?-r:Math.min(Math.max(-r,-a),r),d=-u*u+c*(c+2*a)+h):c<=p?(u=0,c=Math.min(Math.max(-r,-a),r),d=c*(c+2*a)+h):(u=Math.max(0,-(n*r+o)),c=u>0?r:Math.min(Math.max(-r,-a),r),d=-u*u+c*(c+2*a)+h);else c=n>0?-r:r,u=Math.max(0,-(n*c+o)),d=-u*u+c*(c+2*a)+h;return s&&s.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(jt).addScaledVector(Ht,c),d}intersectSphere(e,t){Gt.subVectors(e.center,this.origin);const s=Gt.dot(this.direction),i=Gt.dot(Gt)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),o=s-n,a=s+n;return a<0?null:o<0?this.at(a,t):this.at(o,t)}intersectsSphere(e){return 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,o,a;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?(o=(e.min.z-c.z)*u,a=(e.max.z-c.z)*u):(o=(e.max.z-c.z)*u,a=(e.min.z-c.z)*u),s>a||o>i?null:((o>s||s!=s)&&(s=o),(a<i||i!=i)&&(i=a),i<0?null:this.at(s>=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Gt)}intersectTriangle(e,t,s,i,r){$t.subVectors(t,e),qt.subVectors(s,e),Xt.crossVectors($t,qt);let n,o=this.direction.dot(Xt);if(o>0){if(i)return null;n=1}else{if(!(o<0))return null;n=-1,o=-o}Wt.subVectors(this.origin,e);const a=n*this.direction.dot(qt.crossVectors(Wt,qt));if(a<0)return null;const h=n*this.direction.dot($t.cross(Wt));if(h<0)return null;if(a+h>o)return null;const l=-n*Wt.dot(Xt);return l<0?null:this.at(l/o,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 Kt{constructor(e,t,s,i,r,n,o,a,h,l,u,c,d,p,m,g){Kt.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,o,a,h,l,u,c,d,p,m,g)}set(e,t,s,i,r,n,o,a,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]=o,f[13]=a,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 Kt).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 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){const t=this.elements,s=e.elements,i=1/Qt.setFromMatrixColumn(e,0).length(),r=1/Qt.setFromMatrixColumn(e,1).length(),n=1/Qt.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),o=Math.sin(s),a=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=o*l,r=o*u;t[0]=a*l,t[4]=-a*u,t[8]=h,t[1]=s+i*h,t[5]=e-r*h,t[9]=-o*a,t[2]=r-e*h,t[6]=i+s*h,t[10]=n*a}else if("YXZ"===e.order){const e=a*l,s=a*u,i=h*l,r=h*u;t[0]=e+r*o,t[4]=i*o-s,t[8]=n*h,t[1]=n*u,t[5]=n*l,t[9]=-o,t[2]=s*o-i,t[6]=r+e*o,t[10]=n*a}else if("ZXY"===e.order){const e=a*l,s=a*u,i=h*l,r=h*u;t[0]=e-r*o,t[4]=-n*u,t[8]=i+s*o,t[1]=s+i*o,t[5]=n*l,t[9]=r-e*o,t[2]=-n*h,t[6]=o,t[10]=n*a}else if("ZYX"===e.order){const e=n*l,s=n*u,i=o*l,r=o*u;t[0]=a*l,t[4]=i*h-s,t[8]=e*h+r,t[1]=a*u,t[5]=r*h+e,t[9]=s*h-i,t[2]=-h,t[6]=o*a,t[10]=n*a}else if("YZX"===e.order){const e=n*a,s=n*h,i=o*a,r=o*h;t[0]=a*l,t[4]=r-e*u,t[8]=i*u+s,t[1]=u,t[5]=n*l,t[9]=-o*l,t[2]=-h*l,t[6]=s*u+i,t[10]=e-r*u}else if("XZY"===e.order){const e=n*a,s=n*h,i=o*a,r=o*h;t[0]=a*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]=o*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(Jt,e,es)}lookAt(e,t,s){const i=this.elements;return is.subVectors(e,t),0===is.lengthSq()&&(is.z=1),is.normalize(),ts.crossVectors(s,is),0===ts.lengthSq()&&(1===Math.abs(s.z)?is.x+=1e-4:is.z+=1e-4,is.normalize(),ts.crossVectors(s,is)),ts.normalize(),ss.crossVectors(is,ts),i[0]=ts.x,i[4]=ss.x,i[8]=is.x,i[1]=ts.y,i[5]=ss.y,i[9]=is.y,i[2]=ts.z,i[6]=ss.z,i[10]=is.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],o=s[4],a=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],x=s[11],_=s[15],v=i[0],T=i[4],w=i[8],S=i[12],M=i[1],N=i[5],E=i[9],A=i[13],C=i[2],R=i[6],P=i[10],F=i[14],B=i[3],I=i[7],L=i[11],D=i[15];return r[0]=n*v+o*M+a*C+h*B,r[4]=n*T+o*N+a*R+h*I,r[8]=n*w+o*E+a*P+h*L,r[12]=n*S+o*A+a*F+h*D,r[1]=l*v+u*M+c*C+d*B,r[5]=l*T+u*N+c*R+d*I,r[9]=l*w+u*E+c*P+d*L,r[13]=l*S+u*A+c*F+d*D,r[2]=p*v+m*M+g*C+f*B,r[6]=p*T+m*N+g*R+f*I,r[10]=p*w+m*E+g*P+f*L,r[14]=p*S+m*A+g*F+f*D,r[3]=y*v+b*M+x*C+_*B,r[7]=y*T+b*N+x*R+_*I,r[11]=y*w+b*E+x*P+_*L,r[15]=y*S+b*A+x*F+_*D,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],o=e[5],a=e[9],h=e[13],l=e[2],u=e[6],c=e[10],d=e[14];return e[3]*(+r*a*u-i*h*u-r*o*c+s*h*c+i*o*d-s*a*d)+e[7]*(+t*a*d-t*h*c+r*n*c-i*n*d+i*h*l-r*a*l)+e[11]*(+t*h*u-t*o*d-r*n*u+s*n*d+r*o*l-s*h*l)+e[15]*(-i*o*l-t*a*u+t*o*c+i*n*u-s*n*c+s*a*l)}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],o=e[5],a=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=u*g*h-m*c*h+m*a*d-o*g*d-u*a*f+o*c*f,b=p*c*h-l*g*h-p*a*d+n*g*d+l*a*f-n*c*f,x=l*m*h-p*u*h+p*o*d-n*m*d-l*o*f+n*u*f,_=p*u*a-l*m*a-p*o*c+n*m*c+l*o*g-n*u*g,v=t*y+s*b+i*x+r*_;if(0===v)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const T=1/v;return e[0]=y*T,e[1]=(m*c*r-u*g*r-m*i*d+s*g*d+u*i*f-s*c*f)*T,e[2]=(o*g*r-m*a*r+m*i*h-s*g*h-o*i*f+s*a*f)*T,e[3]=(u*a*r-o*c*r-u*i*h+s*c*h+o*i*d-s*a*d)*T,e[4]=b*T,e[5]=(l*g*r-p*c*r+p*i*d-t*g*d-l*i*f+t*c*f)*T,e[6]=(p*a*r-n*g*r-p*i*h+t*g*h+n*i*f-t*a*f)*T,e[7]=(n*c*r-l*a*r+l*i*h-t*c*h-n*i*d+t*a*d)*T,e[8]=x*T,e[9]=(p*u*r-l*m*r-p*s*d+t*m*d+l*s*f-t*u*f)*T,e[10]=(n*m*r-p*o*r+p*s*h-t*m*h-n*s*f+t*o*f)*T,e[11]=(l*o*r-n*u*r-l*s*h+t*u*h+n*s*d-t*o*d)*T,e[12]=_*T,e[13]=(l*m*i-p*u*i+p*s*c-t*m*c-l*s*g+t*u*g)*T,e[14]=(p*o*i-n*m*i-p*s*a+t*m*a+n*s*g-t*o*g)*T,e[15]=(n*u*i-l*o*i+l*s*a-t*u*a-n*s*c+t*o*c)*T,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,o=e.y,a=e.z,h=r*n,l=r*o;return this.set(h*n+s,h*o-i*a,h*a+i*o,0,h*o+i*a,l*o+s,l*a-i*n,0,h*a-i*o,l*a+i*n,r*a*a+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,o=t._z,a=t._w,h=r+r,l=n+n,u=o+o,c=r*h,d=r*l,p=r*u,m=n*l,g=n*u,f=o*u,y=a*h,b=a*l,x=a*u,_=s.x,v=s.y,T=s.z;return i[0]=(1-(m+f))*_,i[1]=(d+x)*_,i[2]=(p-b)*_,i[3]=0,i[4]=(d-x)*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;let r=Qt.set(i[0],i[1],i[2]).length();const n=Qt.set(i[4],i[5],i[6]).length(),o=Qt.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],Zt.copy(this);const a=1/r,h=1/n,l=1/o;return Zt.elements[0]*=a,Zt.elements[1]*=a,Zt.elements[2]*=a,Zt.elements[4]*=h,Zt.elements[5]*=h,Zt.elements[6]*=h,Zt.elements[8]*=l,Zt.elements[9]*=l,Zt.elements[10]*=l,t.setFromRotationMatrix(Zt),s.x=r,s.y=n,s.z=o,this}makePerspective(e,t,s,i,r,n,o=2e3){const a=this.elements,h=2*r/(t-e),l=2*r/(s-i),u=(t+e)/(t-e),c=(s+i)/(s-i);let d,p;if(o===Le)d=-(n+r)/(n-r),p=-2*n*r/(n-r);else{if(o!==De)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);d=-n/(n-r),p=-n*r/(n-r)}return a[0]=h,a[4]=0,a[8]=u,a[12]=0,a[1]=0,a[5]=l,a[9]=c,a[13]=0,a[2]=0,a[6]=0,a[10]=d,a[14]=p,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(e,t,s,i,r,n,o=2e3){const a=this.elements,h=1/(t-e),l=1/(s-i),u=1/(n-r),c=(t+e)*h,d=(s+i)*l;let p,m;if(o===Le)p=(n+r)*u,m=-2*u;else{if(o!==De)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);p=r*u,m=-1*u}return a[0]=2*h,a[4]=0,a[8]=0,a[12]=-c,a[1]=0,a[5]=2*l,a[9]=0,a[13]=-d,a[2]=0,a[6]=0,a[10]=m,a[14]=-p,a[3]=0,a[7]=0,a[11]=0,a[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 Qt=new _t,Zt=new Kt,Jt=new _t(0,0,0),es=new _t(1,1,1),ts=new _t,ss=new _t,is=new _t,rs=new Kt,ns=new xt;class os{constructor(e=0,t=0,s=0,i=os.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],o=i[8],a=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(je(o,-1,1)),Math.abs(o)<.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(-je(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,h)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(je(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(a,r));break;case"ZYX":this._y=Math.asin(-je(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(a,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(je(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-je(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,h),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-l,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return rs.makeRotationFromQuaternion(e),this.setFromRotationMatrix(rs,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ns.setFromEuler(this),this.setFromQuaternion(ns,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}}os.DEFAULT_ORDER="XYZ";class as{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!!(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let hs=0;const ls=new _t,us=new xt,cs=new Kt,ds=new _t,ps=new _t,ms=new _t,gs=new xt,fs=new _t(1,0,0),ys=new _t(0,1,0),bs=new _t(0,0,1),xs={type:"added"},_s={type:"removed"},vs={type:"childadded",child:null},Ts={type:"childremoved",child:null};class ws extends Oe{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:hs++}),this.uuid=Ge(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ws.DEFAULT_UP.clone();const e=new _t,t=new os,s=new xt,i=new _t(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 Kt},normalMatrix:{value:new Ke}}),this.matrix=new Kt,this.matrixWorld=new Kt,this.matrixAutoUpdate=ws.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=ws.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new as,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return us.setFromAxisAngle(e,t),this.quaternion.multiply(us),this}rotateOnWorldAxis(e,t){return us.setFromAxisAngle(e,t),this.quaternion.premultiply(us),this}rotateX(e){return this.rotateOnAxis(fs,e)}rotateY(e){return this.rotateOnAxis(ys,e)}rotateZ(e){return this.rotateOnAxis(bs,e)}translateOnAxis(e,t){return ls.copy(e).applyQuaternion(this.quaternion),this.position.add(ls.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(fs,e)}translateY(e){return this.translateOnAxis(ys,e)}translateZ(e){return this.translateOnAxis(bs,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(cs.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?ds.copy(e):ds.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),ps.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?cs.lookAt(ps,ds,this.up):cs.lookAt(ds,ps,this.up),this.quaternion.setFromRotationMatrix(cs),i&&(cs.extractRotation(i.matrixWorld),us.setFromRotationMatrix(cs),this.quaternion.premultiply(us.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(console.error("THREE.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(xs),vs.child=e,this.dispatchEvent(vs),vs.child=null):console.error("THREE.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(_s),Ts.child=e,this.dispatchEvent(Ts),Ts.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),cs.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),cs.multiply(e.parent.matrixWorld)),e.applyMatrix4(cs),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(xs),vs.child=e,this.dispatchEvent(vs),vs.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(ps,e,ms),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ps,gs,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),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.6,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),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(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),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.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.sphere.center.toArray()}))),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),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),o=n(e.images),a=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),o.length>0&&(s.images=o),a.length>0&&(s.shapes=a),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.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t<e.children.length;t++){const s=e.children[t];this.add(s.clone())}return this}}ws.DEFAULT_UP=new _t(0,1,0),ws.DEFAULT_MATRIX_AUTO_UPDATE=!0,ws.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Ss=new _t,Ms=new _t,Ns=new _t,Es=new _t,As=new _t,Cs=new _t,Rs=new _t,Ps=new _t,Fs=new _t,Bs=new _t,Is=new gt,Ls=new gt,Ds=new gt;class Os{constructor(e=new _t,t=new _t,s=new _t){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),Ss.subVectors(e,t),i.cross(Ss);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){Ss.subVectors(i,t),Ms.subVectors(s,t),Ns.subVectors(e,t);const n=Ss.dot(Ss),o=Ss.dot(Ms),a=Ss.dot(Ns),h=Ms.dot(Ms),l=Ms.dot(Ns),u=n*h-o*o;if(0===u)return r.set(0,0,0),null;const c=1/u,d=(h*a-o*l)*c,p=(n*l-o*a)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,Es)&&(Es.x>=0&&Es.y>=0&&Es.x+Es.y<=1)}static getInterpolation(e,t,s,i,r,n,o,a){return null===this.getBarycoord(e,t,s,i,Es)?(a.x=0,a.y=0,"z"in a&&(a.z=0),"w"in a&&(a.w=0),null):(a.setScalar(0),a.addScaledVector(r,Es.x),a.addScaledVector(n,Es.y),a.addScaledVector(o,Es.z),a)}static getInterpolatedAttribute(e,t,s,i,r,n){return Is.setScalar(0),Ls.setScalar(0),Ds.setScalar(0),Is.fromBufferAttribute(e,t),Ls.fromBufferAttribute(e,s),Ds.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Is,r.x),n.addScaledVector(Ls,r.y),n.addScaledVector(Ds,r.z),n}static isFrontFacing(e,t,s,i){return Ss.subVectors(s,t),Ms.subVectors(e,t),Ss.cross(Ms).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 Ss.subVectors(this.c,this.b),Ms.subVectors(this.a,this.b),.5*Ss.cross(Ms).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Os.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Os.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Os.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Os.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Os.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,o;As.subVectors(i,s),Cs.subVectors(r,s),Ps.subVectors(e,s);const a=As.dot(Ps),h=Cs.dot(Ps);if(a<=0&&h<=0)return t.copy(s);Fs.subVectors(e,i);const l=As.dot(Fs),u=Cs.dot(Fs);if(l>=0&&u<=l)return t.copy(i);const c=a*u-l*h;if(c<=0&&a>=0&&l<=0)return n=a/(a-l),t.copy(s).addScaledVector(As,n);Bs.subVectors(e,r);const d=As.dot(Bs),p=Cs.dot(Bs);if(p>=0&&d<=p)return t.copy(r);const m=d*h-a*p;if(m<=0&&h>=0&&p<=0)return o=h/(h-p),t.copy(s).addScaledVector(Cs,o);const g=l*p-d*u;if(g<=0&&u-l>=0&&d-p>=0)return Rs.subVectors(r,i),o=(u-l)/(u-l+(d-p)),t.copy(i).addScaledVector(Rs,o);const f=1/(g+m+c);return n=m*f,o=c*f,t.copy(s).addScaledVector(As,n).addScaledVector(Cs,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const ks={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},Us={h:0,s:0,l:0},zs={h:0,s:0,l:0};function Vs(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 Gs{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=_e){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,nt.toWorkingColorSpace(this,t),this}setRGB(e,t,s,i=nt.workingColorSpace){return this.r=e,this.g=t,this.b=s,nt.toWorkingColorSpace(this,i),this}setHSL(e,t,s,i=nt.workingColorSpace){if(e=He(e,1),t=je(t,0,1),s=je(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=Vs(r,i,e+1/3),this.g=Vs(r,i,e),this.b=Vs(r,i,e-1/3)}return nt.toWorkingColorSpace(this,i),this}setStyle(e,t=_e){function s(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],o=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))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(o))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(o))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.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);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=_e){const s=ks[e.toLowerCase()];return void 0!==s?this.setHex(s,t):console.warn("THREE.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=ot(e.r),this.g=ot(e.g),this.b=ot(e.b),this}copyLinearToSRGB(e){return this.r=at(e.r),this.g=at(e.g),this.b=at(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=_e){return nt.fromWorkingColorSpace(js.copy(this),e),65536*Math.round(je(255*js.r,0,255))+256*Math.round(je(255*js.g,0,255))+Math.round(je(255*js.b,0,255))}getHexString(e=_e){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=nt.workingColorSpace){nt.fromWorkingColorSpace(js.copy(this),t);const s=js.r,i=js.g,r=js.b,n=Math.max(s,i,r),o=Math.min(s,i,r);let a,h;const l=(o+n)/2;if(o===n)a=0,h=0;else{const e=n-o;switch(h=l<=.5?e/(n+o):e/(2-n-o),n){case s:a=(i-r)/e+(i<r?6:0);break;case i:a=(r-s)/e+2;break;case r:a=(s-i)/e+4}a/=6}return e.h=a,e.s=h,e.l=l,e}getRGB(e,t=nt.workingColorSpace){return nt.fromWorkingColorSpace(js.copy(this),t),e.r=js.r,e.g=js.g,e.b=js.b,e}getStyle(e=_e){nt.fromWorkingColorSpace(js.copy(this),e);const t=js.r,s=js.g,i=js.b;return e!==_e?`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(Us),this.setHSL(Us.h+e,Us.s+t,Us.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(Us),e.getHSL(zs);const s=We(Us.h,zs.h,t),i=We(Us.s,zs.s,t),r=We(Us.l,zs.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 js=new Gs;Gs.NAMES=ks;let Hs=0;class Ws extends Oe{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Hs++}),this.uuid=Ge(),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=m,this.blendDst=g,this.blendEquation=a,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Gs(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=Se,this.stencilZFail=Se,this.stencilZPass=Se,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){console.warn(`THREE.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:console.warn(`THREE.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.6,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()),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!==m&&(s.blendSrc=this.blendSrc),this.blendDst!==g&&(s.blendDst=this.blendDst),this.blendEquation!==a&&(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!==Se&&(s.stencilFail=this.stencilFail),this.stencilZFail!==Se&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==Se&&(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),!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.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++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class $s extends Ws{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Gs(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 os,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 qs=Xs();function Xs(){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),o=new Uint32Array(64),a=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)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(a[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:o,offsetTable:a}}function Ys(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=je(e,-65504,65504),qs.floatView[0]=e;const t=qs.uint32View[0],s=t>>23&511;return qs.baseTable[s]+((8388607&t)>>qs.shiftTable[s])}function Ks(e){const t=e>>10;return qs.uint32View[0]=qs.mantissaTable[qs.offsetTable[t]+(1023&e)]+qs.exponentTable[t],qs.floatView[0]}const Qs=new _t,Zs=new Ye;let Js=0;class ei{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:Js++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Be,this.updateRanges=[],this.gpuType=z,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++)Zs.fromBufferAttribute(this,t),Zs.applyMatrix3(e),this.setXY(t,Zs.x,Zs.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)Qs.fromBufferAttribute(this,t),Qs.applyMatrix3(e),this.setXYZ(t,Qs.x,Qs.y,Qs.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)Qs.fromBufferAttribute(this,t),Qs.applyMatrix4(e),this.setXYZ(t,Qs.x,Qs.y,Qs.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Qs.fromBufferAttribute(this,t),Qs.applyNormalMatrix(e),this.setXYZ(t,Qs.x,Qs.y,Qs.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Qs.fromBufferAttribute(this,t),Qs.transformDirection(e),this.setXYZ(t,Qs.x,Qs.y,Qs.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=$e(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=qe(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=$e(t,this.array)),t}setX(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=$e(t,this.array)),t}setY(e,t){return this.normalized&&(t=qe(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=$e(t,this.array)),t}setZ(e,t){return this.normalized&&(t=qe(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=$e(t,this.array)),t}setW(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=qe(t,this.array),s=qe(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=qe(t,this.array),s=qe(s,this.array),i=qe(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=qe(t,this.array),s=qe(s,this.array),i=qe(i,this.array),r=qe(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!==Be&&(e.usage=this.usage),e}}class ti extends ei{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class si extends ei{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class ii extends ei{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=Ks(this.array[e*this.itemSize]);return this.normalized&&(t=$e(t,this.array)),t}setX(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize]=Ys(t),this}getY(e){let t=Ks(this.array[e*this.itemSize+1]);return this.normalized&&(t=$e(t,this.array)),t}setY(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize+1]=Ys(t),this}getZ(e){let t=Ks(this.array[e*this.itemSize+2]);return this.normalized&&(t=$e(t,this.array)),t}setZ(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize+2]=Ys(t),this}getW(e){let t=Ks(this.array[e*this.itemSize+3]);return this.normalized&&(t=$e(t,this.array)),t}setW(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize+3]=Ys(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=qe(t,this.array),s=qe(s,this.array)),this.array[e+0]=Ys(t),this.array[e+1]=Ys(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=qe(t,this.array),s=qe(s,this.array),i=qe(i,this.array)),this.array[e+0]=Ys(t),this.array[e+1]=Ys(s),this.array[e+2]=Ys(i),this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=qe(t,this.array),s=qe(s,this.array),i=qe(i,this.array),r=qe(r,this.array)),this.array[e+0]=Ys(t),this.array[e+1]=Ys(s),this.array[e+2]=Ys(i),this.array[e+3]=Ys(r),this}}class ri extends ei{constructor(e,t,s){super(new Float32Array(e),t,s)}}let ni=0;const oi=new Kt,ai=new ws,hi=new _t,li=new wt,ui=new wt,ci=new _t;class di extends Oe{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:ni++}),this.uuid=Ge(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Ze(e)?si:ti)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return 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 Ke).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 oi.makeRotationFromQuaternion(e),this.applyMatrix4(oi),this}rotateX(e){return oi.makeRotationX(e),this.applyMatrix4(oi),this}rotateY(e){return oi.makeRotationY(e),this.applyMatrix4(oi),this}rotateZ(e){return oi.makeRotationZ(e),this.applyMatrix4(oi),this}translate(e,t,s){return oi.makeTranslation(e,t,s),this.applyMatrix4(oi),this}scale(e,t,s){return oi.makeScale(e,t,s),this.applyMatrix4(oi),this}lookAt(e){return ai.lookAt(e),ai.updateMatrix(),this.applyMatrix4(ai.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(hi).negate(),this.translate(hi.x,hi.y,hi.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&&console.warn("THREE.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 wt);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new _t(-1/0,-1/0,-1/0),new _t(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?(ci.addVectors(this.boundingBox.min,li.min),this.boundingBox.expandByPoint(ci),ci.addVectors(this.boundingBox.max,li.max),this.boundingBox.expandByPoint(ci)):(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))&&console.error('THREE.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 Vt);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new _t,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];ui.setFromBufferAttribute(s),this.morphTargetsRelative?(ci.addVectors(li.min,ui.min),li.expandByPoint(ci),ci.addVectors(li.max,ui.max),li.expandByPoint(ci)):(li.expandByPoint(ui.min),li.expandByPoint(ui.max))}li.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)ci.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(ci));if(t)for(let r=0,n=t.length;r<n;r++){const n=t[r],o=this.morphTargetsRelative;for(let t=0,r=n.count;t<r;t++)ci.fromBufferAttribute(n,t),o&&(hi.fromBufferAttribute(e,t),ci.add(hi)),i=Math.max(i,s.distanceToSquared(ci))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.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 console.error("THREE.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 ei(new Float32Array(4*s.count),4));const n=this.getAttribute("tangent"),o=[],a=[];for(let e=0;e<s.count;e++)o[e]=new _t,a[e]=new _t;const h=new _t,l=new _t,u=new _t,c=new Ye,d=new Ye,p=new Ye,m=new _t,g=new _t;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),o[e].add(m),o[t].add(m),o[i].add(m),a[e].add(g),a[t].add(g),a[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 _t,x=new _t,_=new _t,v=new _t;function T(e){_.fromBufferAttribute(i,e),v.copy(_);const t=o[e];b.copy(t),b.sub(_.multiplyScalar(_.dot(t))).normalize(),x.crossVectors(v,t);const s=x.dot(a[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 ei(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 _t,r=new _t,n=new _t,o=new _t,a=new _t,h=new _t,l=new _t,u=new _t;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),o.fromBufferAttribute(s,d),a.fromBufferAttribute(s,p),h.fromBufferAttribute(s,m),o.add(l),a.add(l),h.add(l),s.setXYZ(d,o.x,o.y,o.z),s.setXYZ(p,a.x,a.y,a.z),s.setXYZ(m,h.x,h.y,h.z)}else for(let e=0,o=t.count;e<o;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++)ci.fromBufferAttribute(e,t),ci.normalize(),e.setXYZ(t,ci.x,ci.y,ci.z)}toNonIndexed(){function e(e,t){const s=e.array,i=e.itemSize,r=e.normalized,n=new s.constructor(t.length*i);let o=0,a=0;for(let r=0,h=t.length;r<h;r++){o=e.isInterleavedBufferAttribute?t[r]*e.data.stride+e.offset:t[r]*i;for(let e=0;e<i;e++)n[a++]=s[o++]}return new ei(n,i,r)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new di,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=[],o=r[i];for(let t=0,i=o.length;t<i;t++){const i=e(o[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.6,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 o=this.boundingSphere;return null!==o&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),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 o=e.boundingBox;null!==o&&(this.boundingBox=o.clone());const a=e.boundingSphere;return null!==a&&(this.boundingSphere=a.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const pi=new Kt,mi=new Yt,gi=new Vt,fi=new _t,yi=new _t,bi=new _t,xi=new _t,_i=new _t,vi=new _t,Ti=new _t,wi=new _t;class Si extends ws{constructor(e=new di,t=new $s){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,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 o=this.morphTargetInfluences;if(r&&o){vi.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=o[s],a=r[s];0!==i&&(_i.fromBufferAttribute(a,e),n?vi.addScaledVector(_i,i):vi.addScaledVector(_i.sub(t),i))}t.add(vi)}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(),gi.copy(s.boundingSphere),gi.applyMatrix4(r),mi.copy(e.ray).recast(e.near),!1===gi.containsPoint(mi.origin)){if(null===mi.intersectSphere(gi,fi))return;if(mi.origin.distanceToSquared(fi)>(e.far-e.near)**2)return}pi.copy(r).invert(),mi.copy(e.ray).applyMatrix4(pi),null!==s.boundingBox&&!1===mi.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,mi)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,o=r.index,a=r.attributes.position,h=r.attributes.uv,l=r.attributes.uv1,u=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==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=Mi(this,p,e,s,h,l,u,o.getX(r),o.getX(r+1),o.getX(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=Mi(this,n,e,s,h,l,u,o.getX(r),o.getX(r+1),o.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}else if(void 0!==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=Mi(this,p,e,s,h,l,u,r,r+1,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=Mi(this,n,e,s,h,l,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function Mi(e,t,s,i,r,n,o,a,h,l){e.getVertexPosition(a,yi),e.getVertexPosition(h,bi),e.getVertexPosition(l,xi);const u=function(e,t,s,i,r,n,o,a){let h;if(h=1===t.side?i.intersectTriangle(o,n,r,!0,a):i.intersectTriangle(r,n,o,0===t.side,a),null===h)return null;wi.copy(a),wi.applyMatrix4(e.matrixWorld);const l=s.ray.origin.distanceTo(wi);return l<s.near||l>s.far?null:{distance:l,point:wi.clone(),object:e}}(e,t,s,i,yi,bi,xi,Ti);if(u){const e=new _t;Os.getBarycoord(Ti,yi,bi,xi,e),r&&(u.uv=Os.getInterpolatedAttribute(r,a,h,l,e,new Ye)),n&&(u.uv1=Os.getInterpolatedAttribute(n,a,h,l,e,new Ye)),o&&(u.normal=Os.getInterpolatedAttribute(o,a,h,l,e,new _t),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const t={a:a,b:h,c:l,normal:new _t,materialIndex:0};Os.getNormal(yi,bi,xi,t.normal),u.face=t,u.barycoord=e}return u}class Ni extends di{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 o=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const a=[],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,x=p/f,_=n/2,v=p/2,T=m/2,w=g+1,S=f+1;let M=0,N=0;const E=new _t;for(let n=0;n<S;n++){const o=n*x-v;for(let a=0;a<w;a++){const c=a*b-_;E[e]=c*i,E[t]=o*r,E[s]=T,h.push(E.x,E.y,E.z),E[e]=0,E[t]=0,E[s]=m>0?1:-1,l.push(E.x,E.y,E.z),u.push(a/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+w*e,i=c+t+w*(e+1),r=c+(t+1)+w*(e+1),n=c+(t+1)+w*e;a.push(s,i,n),a.push(i,r,n),N+=6}o.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(a),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 Ni(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Ei(e){const t={};for(const s in e){t[s]={};for(const i in e[s]){const r=e[s][i];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?r.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[s][i]=null):t[s][i]=r.clone():Array.isArray(r)?t[s][i]=r.slice():t[s][i]=r}}return t}class Ai extends Ws{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==e&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Ei(e.uniforms),this.uniformsGroups=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].clone());return t}(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const i=this.uniforms[s].value;i&&i.isTexture?t.uniforms[s]={type:"t",value:i.toJSON(e).uuid}:i&&i.isColor?t.uniforms[s]={type:"c",value:i.getHex()}:i&&i.isVector2?t.uniforms[s]={type:"v2",value:i.toArray()}:i&&i.isVector3?t.uniforms[s]={type:"v3",value:i.toArray()}:i&&i.isVector4?t.uniforms[s]={type:"v4",value:i.toArray()}:i&&i.isMatrix3?t.uniforms[s]={type:"m3",value:i.toArray()}:i&&i.isMatrix4?t.uniforms[s]={type:"m4",value:i.toArray()}:t.uniforms[s]={value:i}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const e in this.extensions)!0===this.extensions[e]&&(s[e]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class Ci extends ws{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Kt,this.projectionMatrix=new Kt,this.projectionMatrixInverse=new Kt,this.coordinateSystem=Le}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Ri=new _t,Pi=new Ye,Fi=new Ye;class Bi extends Ci{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*Ve*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*ze*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Ve*Math.atan(Math.tan(.5*ze*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){Ri.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ri.x,Ri.y).multiplyScalar(-e/Ri.z),Ri.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Ri.x,Ri.y).multiplyScalar(-e/Ri.z)}getViewSize(e,t){return this.getViewBounds(e,Pi,Fi),t.subVectors(Fi,Pi)}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*ze*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,o=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/o,i*=n.width/e,s*=n.height/o}const o=this.filmOffset;0!==o&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-s,e,this.far,this.coordinateSystem),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}}const Ii=-90;class Li extends ws{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Bi(Ii,1,e,t);i.layers=this.layers,this.add(i);const r=new Bi(Ii,1,e,t);r.layers=this.layers,this.add(r);const n=new Bi(Ii,1,e,t);n.layers=this.layers,this.add(n);const o=new Bi(Ii,1,e,t);o.layers=this.layers,this.add(o);const a=new Bi(Ii,1,e,t);a.layers=this.layers,this.add(a);const h=new Bi(Ii,1,e,t);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,o,a]=t;for(const e of t)this.remove(e);if(e===Le)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),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else{if(e!==De)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),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.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,o,a,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,e.setRenderTarget(s,0,i),e.render(t,r),e.setRenderTarget(s,1,i),e.render(t,n),e.setRenderTarget(s,2,i),e.render(t,o),e.setRenderTarget(s,3,i),e.render(t,a),e.setRenderTarget(s,4,i),e.render(t,h),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),e.render(t,l),e.setRenderTarget(u,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class Di extends mt{constructor(e=[],t=301,s,i,r,n,o,a,h,l){super(e,t,s,i,r,n,o,a,h,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Oi extends yt{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Di(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:P}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const s={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Ni(5,5,5),r=new Ai({name:"CubemapFromEquirect",uniforms:Ei(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const n=new Si(i,r),o=t.minFilter;t.minFilter===B&&(t.minFilter=P);return new Li(1,10,this).update(e,n),t.minFilter=o,n.geometry.dispose(),n.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)}}let ki=class extends ws{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Ui={type:"move"};class zi{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new ki,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 ki,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new _t,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new _t),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new ki,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new _t,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new _t),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 o=this._targetRay,a=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"],o=i.position.distanceTo(r.position),a=.02,l=.005;h.inputState.pinching&&o>a+l?(h.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!h.inputState.pinching&&o<=a-l&&(h.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==a&&e.gripSpace&&(r=t.getPose(e.gripSpace,s),null!==r&&(a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,r.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(r.linearVelocity)):a.hasLinearVelocity=!1,r.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(r.angularVelocity)):a.hasAngularVelocity=!1));null!==o&&(i=t.getPose(e.targetRaySpace,s),null===i&&null!==r&&(i=r),null!==i&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Ui)))}return null!==o&&(o.visible=null!==i),null!==a&&(a.visible=null!==r),null!==h&&(h.visible=null!==n),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const s=new ki;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}class Vi extends ws{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 os,this.environmentIntensity=1,this.environmentRotation=new os,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}}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=Be,this.updateRanges=[],this.version=0,this.uuid=Ge()}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=Ge()),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=Ge()),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 _t;class Hi{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=$e(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=qe(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=qe(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=qe(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=qe(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=qe(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=$e(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=$e(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=$e(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=$e(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=qe(t,this.array),s=qe(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=qe(t,this.array),s=qe(s,this.array),i=qe(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=qe(t,this.array),s=qe(s,this.array),i=qe(i,this.array),r=qe(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){console.log("THREE.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 ei(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 Hi(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){console.log("THREE.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}}}class Wi extends Ws{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Gs(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}}class $i extends mt{constructor(e=null,t=1,s=1,i,r,n,o,a,h=1003,l=1003,u,c){super(null,n,o,a,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 qi extends ei{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 Xi=new _t,Yi=new _t,Ki=new Ke;class Qi{constructor(e=new _t(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=Xi.subVectors(s,t).cross(Yi.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(Xi),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||Ki.getNormalMatrix(e),i=this.coplanarPoint(Xi).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 Zi=new Vt,Ji=new _t;class er{constructor(e=new Qi,t=new Qi,s=new Qi,i=new Qi,r=new Qi,n=new Qi){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(s),o[3].copy(i),o[4].copy(r),o[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){const s=this.planes,i=e.elements,r=i[0],n=i[1],o=i[2],a=i[3],h=i[4],l=i[5],u=i[6],c=i[7],d=i[8],p=i[9],m=i[10],g=i[11],f=i[12],y=i[13],b=i[14],x=i[15];if(s[0].setComponents(a-r,c-h,g-d,x-f).normalize(),s[1].setComponents(a+r,c+h,g+d,x+f).normalize(),s[2].setComponents(a+n,c+l,g+p,x+y).normalize(),s[3].setComponents(a-n,c-l,g-p,x-y).normalize(),s[4].setComponents(a-o,c-u,g-m,x-b).normalize(),t===Le)s[5].setComponents(a+o,c+u,g+m,x+b).normalize();else{if(t!==De)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);s[5].setComponents(o,u,m,b).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Zi.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Zi.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Zi)}intersectsSprite(e){return Zi.center.set(0,0,0),Zi.radius=.7071067811865476,Zi.applyMatrix4(e.matrixWorld),this.intersectsSphere(Zi)}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(Ji.x=i.normal.x>0?e.max.x:e.min.x,Ji.y=i.normal.y>0?e.max.y:e.min.y,Ji.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Ji)<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)}}class tr extends Ws{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Gs(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 sr extends Ws{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Gs(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 ir extends mt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=A,this.minFilter=A,this.generateMipmaps=!1,this.needsUpdate=!0}}class rr extends mt{constructor(e,t,s=1014,i,r,n,o=1003,a=1003,h,l=1026){if(l!==W&&l!==$)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super(null,i,r,n,o,a,l,s,h),this.isDepthTexture=!0,this.image={width:e,height:t},this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ct(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 nr extends di{constructor(e=1,t=1,s=1,i=32,r=1,n=!1,o=0,a=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:r,openEnded:n,thetaStart:o,thetaLength:a};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 Ye,m=new _t;let y=0;const b=!0===s?e:t,x=!0===s?1:-1;for(let e=1;e<=i;e++)u.push(0,g*x,0),c.push(0,x,0),d.push(.5,.5),p++;const _=p;for(let e=0;e<=i;e++){const t=e/i*a+o,s=Math.cos(t),r=Math.sin(t);m.x=b*r,m.y=g*x,m.z=b*s,u.push(m.x,m.y,m.z),c.push(0,x,0),n.x=.5*s+.5,n.y=.5*r*x+.5,d.push(n.x,n.y),p++}for(let e=0;e<i;e++){const t=r+e,i=_+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 _t,y=new _t;let b=0;const x=(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*a+o,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,x,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],o=m[i+1][s],a=m[i+1][s+1],h=m[i][s+1];(e>0||0!==i)&&(l.push(n,o,h),b+=3),(t>0||i!==r-1)&&(l.push(o,a,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 nr(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class or extends di{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,o=Math.floor(s),a=Math.floor(i),h=o+1,l=a+1,u=e/o,c=t/a,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/o),g.push(1-e/a)}}for(let e=0;e<a;e++)for(let t=0;t<o;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 ar extends di{constructor(e=1,t=32,s=16,i=0,r=2*Math.PI,n=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:r,thetaStart:n,thetaLength:o},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const a=Math.min(n+o,Math.PI);let h=0;const l=[],u=new _t,c=new _t,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&&a===Math.PI&&(b=-.5/t);for(let s=0;s<=t;s++){const a=s/t;u.x=-e*Math.cos(i+a*r)*Math.sin(n+y*o),u.y=e*Math.cos(n+y*o),u.z=e*Math.sin(i+a*r)*Math.sin(n+y*o),p.push(u.x,u.y,u.z),c.copy(u).normalize(),m.push(c.x,c.y,c.z),g.push(a+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],o=l[e+1][i],h=l[e+1][i+1];(0!==e||n>0)&&d.push(t,r,h),(e!==s-1||a<Math.PI)&&d.push(r,o,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 ar(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class hr extends Ws{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Gs(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 lr extends Ws{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Gs(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 Gs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(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 os,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 ur extends lr{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 Ye(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return je(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 Gs(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 Gs(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Gs(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 cr extends Ws{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Gs(16777215),this.specular=new Gs(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Gs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new os,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class dr extends Ws{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Gs(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Gs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(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 pr extends Ws{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(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 mr extends Ws{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Gs(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Gs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new os,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class gr extends Ws{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Gs(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,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.flatShading=e.flatShading,this.fog=e.fog,this}}class fr extends tr{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 yr extends ws{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Gs(e),this.intensity=t}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,void 0!==this.groundColor&&(t.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(t.object.distance=this.distance),void 0!==this.angle&&(t.object.angle=this.angle),void 0!==this.decay&&(t.object.decay=this.decay),void 0!==this.penumbra&&(t.object.penumbra=this.penumbra),void 0!==this.shadow&&(t.object.shadow=this.shadow.toJSON()),void 0!==this.target&&(t.object.target=this.target.uuid),t}}class br extends yr{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(ws.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Gs(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const xr=new Kt,_r=new _t,vr=new _t;class Tr{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Ye(512,512),this.map=null,this.mapPass=null,this.matrix=new Kt,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new er,this._frameExtents=new Ye(1,1),this._viewportCount=1,this._viewports=[new gt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;_r.setFromMatrixPosition(e.matrixWorld),t.position.copy(_r),vr.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(vr),t.updateMatrixWorld(),xr.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(xr),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.mapSize.copy(e.mapSize),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}}class wr extends Tr{constructor(){super(new Bi(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,s=2*Ve*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height,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 Sr extends yr{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(ws.DEFAULT_UP),this.updateMatrix(),this.target=new ws,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new wr}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}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.shadow=e.shadow.clone(),this}}const Mr=new Kt,Nr=new _t,Er=new _t;class Ar extends Tr{constructor(){super(new Bi(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Ye(4,2),this._viewportCount=6,this._viewports=[new gt(2,1,1,1),new gt(0,1,1,1),new gt(3,1,1,1),new gt(1,1,1,1),new gt(3,0,1,1),new gt(1,0,1,1)],this._cubeDirections=[new _t(1,0,0),new _t(-1,0,0),new _t(0,0,1),new _t(0,0,-1),new _t(0,1,0),new _t(0,-1,0)],this._cubeUps=[new _t(0,1,0),new _t(0,1,0),new _t(0,1,0),new _t(0,1,0),new _t(0,0,1),new _t(0,0,-1)]}updateMatrices(e,t=0){const s=this.camera,i=this.matrix,r=e.distance||s.far;r!==s.far&&(s.far=r,s.updateProjectionMatrix()),Nr.setFromMatrixPosition(e.matrixWorld),s.position.copy(Nr),Er.copy(s.position),Er.add(this._cubeDirections[t]),s.up.copy(this._cubeUps[t]),s.lookAt(Er),s.updateMatrixWorld(),i.makeTranslation(-Nr.x,-Nr.y,-Nr.z),Mr.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Mr)}}class Cr extends yr{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 Ar}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}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}}class Rr extends Ci{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,o=i+t,a=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,o-=t*this.view.offsetY,a=o-t*this.view.height}this.projectionMatrix.makeOrthographic(r,n,o,a,this.near,this.far,this.coordinateSystem),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 Pr extends Tr{constructor(){super(new Rr(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Fr extends yr{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ws.DEFAULT_UP),this.updateMatrix(),this.target=new ws,this.shadow=new Pr}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class Br extends yr{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Ir extends yr{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 Lr{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new _t)}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 Dr extends yr{constructor(e=new Lr,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}fromJSON(e){return this.intensity=e.intensity,this.sh.fromArray(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}class Or extends Bi{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e,this.index=0}}class kr 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 Ur{constructor(e,t,s,i){Ur.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}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:o}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=o);const zr=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveMap","envMap","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"];class Vr{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=zr,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}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),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}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={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 null!==e.renderer.nodes.modelViewMatrix||null!==e.renderer.nodes.modelNormalViewMatrix}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){const{object:t,material:s,geometry:i}=e,r=this.getRenderObjectData(e);if(!0!==r.worldMatrix.equals(t.matrixWorld))return r.worldMatrix.copy(t.matrixWorld),!1;const n=r.material;for(const e in n){const t=n[e],i=s[e];if(void 0!==t.equals){if(!1===t.equals(i))return t.copy(i),!1}else if(!0===i.isTexture){if(t.id!==i.id||t.version!==i.version)return t.id=i.id,t.version=i.version,!1}else if(t!==i)return n[e]=i,!1}if(n.transmission>0){const{width:t,height:s}=e.context;if(r.bufferWidth!==t||r.bufferHeight!==s)return r.bufferWidth=t,r.bufferHeight=s,!1}const o=r.geometry,a=i.attributes,h=o.attributes,l=Object.keys(h),u=Object.keys(a);if(o.id!==i.id)return o.id=i.id,!1;if(l.length!==u.length)return r.geometry.attributes=this.getAttributesData(a),!1;for(const e of l){const t=h[e],s=a[e];if(void 0===s)return delete h[e],!1;if(t.version!==s.version)return t.version=s.version,!1}const c=i.index,d=o.indexVersion,p=c?c.version:null;if(d!==p)return o.indexVersion=p,!1;if(o.drawRange.start!==i.drawRange.start||o.drawRange.count!==i.drawRange.count)return o.drawRange.start=i.drawRange.start,o.drawRange.count=i.drawRange.count,!1;if(r.morphTargetInfluences){let e=!1;for(let s=0;s<r.morphTargetInfluences.length;s++)r.morphTargetInfluences[s]!==t.morphTargetInfluences[s]&&(e=!0);if(e)return!0}return r.center&&!1===r.center.equals(t.center)?(r.center.copy(t.center),!0):(null!==e.bundle&&(r.version=e.bundle.version),!0)}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e))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;return!0!==this.equals(e)}}function Gr(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 jr=e=>Gr(e),Hr=(...e)=>Gr(e);function Wr(e,t=!1){const s=[];!0===e.isNode&&(s.push(e.id),e=e.getSelf());for(const{property:i,childNode:r}of $r(e))s.push(Gr(i.slice(0,-4)),r.getCacheKey(t));return Gr(s)}function*$r(e,t=!1){for(const s in e){if(!0===s.startsWith("_"))continue;const i=e[s];if(!0===Array.isArray(i))for(let e=0;e<i.length;e++){const r=i[e];r&&(!0===r.isNode||t&&"function"==typeof r.toJSON)&&(yield{property:s,index:e,childNode:r})}else if(i&&!0===i.isNode)yield{property:s,childNode:i};else if("object"==typeof i)for(const e in i){const r=i[e];r&&(!0===r.isNode||t&&"function"==typeof r.toJSON)&&(yield{property:s,index:e,childNode:r})}}}const qr=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Xr=new WeakMap;function Yr(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 Kr(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 Gs(...t):"vec2"===s?new Ye(...t):"vec3"===s?new _t(...t):"vec4"===s?new gt(...t):"mat2"===s?new Ur(...t):"mat3"===s?new Ke(...t):"mat4"===s?new Kt(...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 Qr(e){let t=Xr.get(e);return void 0===t&&(t={},Xr.set(e,t)),t}const Zr="vertex",Jr="none",en="frame",tn="render",sn="object",rn="readOnly",nn="writeOnly",on="readWrite",an=["setup","analyze","generate"],hn=["fragment","vertex","compute"],ln=["x","y","z","w"];let un=0;class cn extends Oe{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Jr,this.updateBeforeType=Jr,this.updateAfterType=Jr,this.uuid=Xe.generateUUID(),this.version=0,this.global=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:un++})}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.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,en)}onRenderUpdate(e){return this.onUpdate(e,tn)}onObjectUpdate(e){return this.onUpdate(e,sn)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of $r(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Hr(Wr(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}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}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){if(1===e.increaseUsage(this)){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);e.addNode(this),e.addChain(this);let i=null;const r=e.getBuildStage();if("setup"===r){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0;const s=this.setup(e),i=s&&!0===s.isNode;for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e);i&&s.build(e),t.outputNode=s}}else if("analyze"===r)this.analyze(e);else if("generate"===r){if(1===this.generate.length){const s=this.getNodeType(e),r=e.getDataFromNode(this);i=r.snippet,void 0===i?void 0===r.generated?(r.generated=!0,i=this.generate(e)||"",r.snippet=i):(console.warn("THREE.Node: Recursion detected.",this),i=""):void 0!==r.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),i=e.format(i,s,t)}else i=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),i}getSerializeChildren(){return $r(this)}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.6,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}}class dn extends cn{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)}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 pn extends cn{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 mn extends cn{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),o=e.getPropertyName(n);return e.addLineFlowCode(`${o} = ${r}`,this),i.snippet=r,i.propertyName=o,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class gn extends mn{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),o=[];let a=0;for(const t of r){if(a>=i){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${s}()' type.`);break}let r,h=t.getNodeType(e),l=e.getTypeLength(h);a+l>i&&(console.error(`THREE.TSL: Length of '${s}()' data exceeds maximum length of output type.`),l=i-a,h=e.getTypeFromLength(l)),a+=l,r=t.build(e,h);const u=e.getComponentType(h);u!==n&&(r=e.format(r,u,n)),o.push(r)}const h=`${e.getType(s)}( ${o.join(", ")} )`;return e.format(h,s,t)}}const fn=ln.join("");class yn extends cn{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(ln.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))}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 o=s.build(e,n);r=this.components.length===i&&this.components===fn.slice(0,this.components.length)?e.format(o,n,t):e.format(`${o}.${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 bn extends mn{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)),o=e.getTypeFromLength(s.length,n),a=i.build(e,o),h=t.build(e,r),l=e.getTypeLength(r),u=[];for(let e=0;e<l;e++){const t=ln[e];t===s[0]?(u.push(a),e+=s.length-1):u.push(h+"."+t)}return`${e.getType(r)}( ${u.join(", ")} )`}}class xn extends mn{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),o=e.getPropertyName(n);e.addLineFlowCode(o+" = "+r,this);const a=e.getTypeLength(i),h=[];let l=0;for(let e=0;e<a;e++){const s=ln[e];s===t[l]?(h.push("1.0 - "+o+"."+s),l++):h.push(o+"."+s)}return`${e.getType(i)}( ${h.join(", ")} )`}}class _n extends cn{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?Yr(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=Yr(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)?Kr(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){console.warn("Abstract function.")}}const vn=/float|u?int/;class Tn extends _n{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 vn.test(s)&&vn.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class wn extends cn{static get type(){return"MemberNode"}constructor(e,t){super(),this.node=e,this.property=t,this.isMemberNode=!0}getNodeType(e){return this.node.getMemberType(e,this.property)}generate(e){return this.node.build(e)+"."+this.property}}let Sn=null;const Mn=new Map;function Nn(e,t){if(Mn.has(e))console.warn(`THREE.TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);Mn.set(e,t)}}const En=e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),An=e=>En(e).split("").sort().join(""),Cn={setup(e,t){const s=t.shift();return e(Jn(s),...t)},get(e,t,s){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(Sn.assign(s,...e),s);if(Mn.has(t)){const i=Mn.get(t);return e.isStackNode?(...e)=>s.add(i(...e)):(...e)=>i(s,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Mn.has(t.slice(0,t.length-6))){const i=Mn.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>s.assign(e[0],i(...e)):(...e)=>s.assign(i(s,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=En(t),Zn(new yn(s,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=An(t.slice(3).toLowerCase()),s=>Zn(new bn(e,t,s));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=An(t.slice(4).toLowerCase()),()=>Zn(new xn(Zn(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Zn(new yn(e,t));if(!0===/^\d+$/.test(t))return Zn(new dn(s,new Tn(Number(t),"uint")));if(!0===/^get$/.test(t))return e=>Zn(new wn(s,e))}return Reflect.get(e,t,s)},set:(e,t,s,i)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,s,i):(i[t].assign(s),!0)},Rn=new WeakMap,Pn=new WeakMap,Fn=function(e,t=null){for(const s in e)e[s]=Zn(e[s],t);return e},Bn=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=Zn(e[i],t);return e},In=function(e,t=null,s=null,i=null){const r=e=>Zn(null!==i?Object.assign(e,i):e);let n,o,a,h=t;function l(t){let s;return s=h?/[a-z]/i.test(h)?h+"()":h:e.type,void 0!==o&&t.length<o?(console.error(`THREE.TSL: "${s}" parameter length is less than minimum required.`),t.concat(new Array(o-t.length).fill(0))):void 0!==a&&t.length>a?(console.error(`THREE.TSL: "${s}" parameter length exceeds limit.`),t.slice(0,a)):t}return null===t?n=(...t)=>r(new e(...eo(l(t)))):null!==s?(s=Zn(s),n=(...i)=>r(new e(t,...eo(l(i)),s))):n=(...s)=>r(new e(t,...eo(l(s)))),n.setParameterLength=(...e)=>(1===e.length?o=a=e[0]:2===e.length&&([o,a]=e),n),n.setName=e=>(h=e,n),n},Ln=function(e,...t){return Zn(new e(...eo(t)))};class Dn extends cn{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:s}=this,i=e.getNodeProperties(t);if(i.onceOutput)return i.onceOutput;let r=null;if(t.layout){let i=Pn.get(e.constructor);void 0===i&&(i=new WeakMap,Pn.set(e.constructor,i));let n=i.get(t);void 0===n&&(n=Zn(e.buildFunctionNode(t)),i.set(t,n)),e.addInclude(n),r=Zn(n.call(s))}else{const i=t.jsFunc,n=null!==s||i.length>1?i(s||[],e):i(e);r=Zn(n)}return t.once&&(i.onceOutput=r),r}getOutputNode(e){const t=e.getNodeProperties(this);return null===t.outputNode&&(t.outputNode=this.setupOutput(e)),t.outputNode}setup(e){return this.getOutputNode(e)}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){return this.getOutputNode(e).build(e,t)}}class On extends cn{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return Jn(e),Zn(new Dn(this,e))}setup(){return this.call()}}const kn=[!1,!0],Un=[0,1,2,3],zn=[-1,-2],Vn=[.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],Gn=new Map;for(const e of kn)Gn.set(e,new Tn(e));const jn=new Map;for(const e of Un)jn.set(e,new Tn(e,"uint"));const Hn=new Map([...jn].map((e=>new Tn(e.value,"int"))));for(const e of zn)Hn.set(e,new Tn(e,"int"));const Wn=new Map([...Hn].map((e=>new Tn(e.value))));for(const e of Vn)Wn.set(e,new Tn(e));for(const e of Vn)Wn.set(-e,new Tn(-e));const $n={bool:Gn,uint:jn,ints:Hn,float:Wn},qn=new Map([...Gn,...Wn]),Xn=(e,t)=>qn.has(e)?qn.get(e):!0===e.isNode?e:new Tn(e,t),Yn=function(e,t=null){return(...s)=>{if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every((e=>"object"!=typeof e)))&&(s=[Kr(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return Zn(t.get(s[0]));if(1===s.length){const t=Xn(s[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?Zn(t):Zn(new pn(t,e))}const i=s.map((e=>Xn(e)));return Zn(new gn(i,e))}},Kn=e=>"object"==typeof e&&null!==e?e.value:e;function Qn(e,t){return new Proxy(new On(e,t),Cn)}const Zn=(e,t=null)=>function(e,t=null){const s=Yr(e);if("node"===s){let t=Rn.get(e);return void 0===t&&(t=new Proxy(e,Cn),Rn.set(e,t),Rn.set(t,t)),t}return null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?Zn(Xn(e,t)):"shader"===s?ro(e):e}(e,t),Jn=(e,t=null)=>new Fn(e,t),eo=(e,t=null)=>new Bn(e,t),to=(...e)=>new In(...e),so=(...e)=>new Ln(...e);let io=0;const ro=(e,t=null)=>{let s=null;null!==t&&("object"==typeof t?s=t.return:("string"==typeof t?s=t:console.error("THREE.TSL: Invalid layout type."),t=null));const i=new Qn(e,s),r=(...e)=>{let t;return Jn(e),t=e[0]&&e[0].isNode?[...e]:e[0],i.call(t)};if(r.shaderNode=i,r.setLayout=e=>(i.setLayout(e),r),r.once=()=>(i.once=!0,r),null!==t){if("object"!=typeof t.inputs){const e={name:"fn"+io++,type:s,inputs:[]};for(const s in t)"return"!==s&&e.inputs.push({name:s,type:t[s]});t=e}r.setLayout(t)}return r};Nn("toGlobal",(e=>(e.global=!0,e)));const no=e=>{Sn=e},oo=()=>Sn,ao=(...e)=>Sn.If(...e);Nn("append",(function(e){return Sn&&Sn.add(e),e}));const ho=new Yn("color"),lo=new Yn("float",$n.float),uo=new Yn("int",$n.ints),co=new Yn("uint",$n.uint),po=new Yn("bool",$n.bool),mo=new Yn("vec2"),go=new Yn("ivec2"),fo=new Yn("uvec2"),yo=new Yn("bvec2"),bo=new Yn("vec3"),xo=new Yn("ivec3"),_o=new Yn("uvec3"),vo=new Yn("bvec3"),To=new Yn("vec4"),wo=new Yn("ivec4"),So=new Yn("uvec4"),Mo=new Yn("bvec4"),No=new Yn("mat2"),Eo=new Yn("mat3"),Ao=new Yn("mat4");Nn("toColor",ho),Nn("toFloat",lo),Nn("toInt",uo),Nn("toUint",co),Nn("toBool",po),Nn("toVec2",mo),Nn("toIVec2",go),Nn("toUVec2",fo),Nn("toBVec2",yo),Nn("toVec3",bo),Nn("toIVec3",xo),Nn("toUVec3",_o),Nn("toBVec3",vo),Nn("toVec4",To),Nn("toIVec4",wo),Nn("toUVec4",So),Nn("toBVec4",Mo),Nn("toMat2",No),Nn("toMat3",Eo),Nn("toMat4",Ao);Nn("element",to(dn).setParameterLength(2)),Nn("convert",((e,t)=>Zn(new pn(Zn(e),t))));class Co extends mn{static get type(){return"ArrayNode"}constructor(e,t,s=null){super(e),this.count=t,this.values=s,this.isArrayNode=!0}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}Nn("toArray",((e,t)=>((...e)=>{let t;if(1===e.length){const s=e[0];t=new Co(null,s.length,s)}else{const s=e[0],i=e[1];t=new Co(s,i)}return Zn(t)})(Array(t).fill(e))));class Ro extends cn{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 Po=e=>new Ro(e),Fo=(e,t=0)=>new Ro(e,!0,t),Bo=Fo("frame"),Io=Fo("render"),Lo=Po("object");class Do extends _n{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Lo}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const s=this.getSelf();return e=e.bind(s),super.onUpdate((t=>{const i=e(t,s);void 0!==i&&(this.value=i)}),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),o=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.label),a=e.getPropertyName(o);return void 0!==e.context.label&&delete e.context.label,e.format(a,s,t)}}const Oo=(e,t)=>{const s=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e),i=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Zn(new Do(i,s))};class ko extends cn{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}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 Uo=(e,t)=>Zn(new ko(e,t)),zo=(e,t)=>Zn(new ko(e,t,!0)),Vo=so(ko,"vec4","DiffuseColor"),Go=so(ko,"vec3","EmissiveColor"),jo=so(ko,"float","Roughness"),Ho=so(ko,"float","Metalness"),Wo=so(ko,"float","Clearcoat"),$o=so(ko,"float","ClearcoatRoughness"),qo=so(ko,"vec3","Sheen"),Xo=so(ko,"float","SheenRoughness"),Yo=so(ko,"float","Iridescence"),Ko=so(ko,"float","IridescenceIOR"),Qo=so(ko,"float","IridescenceThickness"),Zo=so(ko,"float","AlphaT"),Jo=so(ko,"float","Anisotropy"),ea=so(ko,"vec3","AnisotropyT"),ta=so(ko,"vec3","AnisotropyB"),sa=so(ko,"color","SpecularColor"),ia=so(ko,"float","SpecularF90"),ra=so(ko,"float","Shininess"),na=so(ko,"vec4","Output"),oa=so(ko,"float","dashSize"),aa=so(ko,"float","gapSize"),ha=so(ko,"float","IOR"),la=so(ko,"float","Transmission"),ua=so(ko,"float","Thickness"),ca=so(ko,"float","AttenuationDistance"),da=so(ko,"color","AttenuationColor"),pa=so(ko,"float","Dispersion");class ma extends mn{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}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 ln.join("").slice(0,s)!==t.components}return!1}generate(e,t){const{targetNode:s,sourceNode:i}=this,r=this.needsSplitAssign(e),n=s.getNodeType(e),o=s.context({assign:!0}).build(e),a=i.build(e,n),h=i.getNodeType(e),l=e.getDataFromNode(this);let u;if(!0===l.initialized)"void"!==t&&(u=o);else if(r){const i=e.getVarFromNode(this,null,n),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${a}`,this);const h=s.node.context({assign:!0}).build(e);for(let t=0;t<s.components.length;t++){const i=s.components[t];e.addLineFlowCode(`${h}.${i} = ${r}[ ${t} ]`,this)}"void"!==t&&(u=o)}else u=`${o} = ${a}`,"void"!==t&&"void"!==h||(e.addLineFlowCode(u,this),"void"!==t&&(u=o));return l.initialized=!0,e.format(u,n,t)}}Nn("assign",to(ma).setParameterLength(2));class ga extends mn{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)}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)console.error("THREE.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(console.error("THREE.TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(lo(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)):(console.error(`THREE.TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(n(lo(0),e)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}Nn("call",((e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?eo(t):Jn(t[0]),Zn(new ga(Zn(e),t)))));class fa extends mn{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new fa(e,t,s);for(let t=0;t<i.length-1;t++)r=new fa(e,r,i[t]);t=r,s=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=s,this.isOperatorNode=!0}getNodeType(e,t){const s=this.op,i=this.aNode,r=this.bNode,n=i.getNodeType(e),o=void 0!==r?r.getNodeType(e):null;if("void"===n||"void"===o)return"void";if("%"===s)return n;if("~"===s||"&"===s||"|"===s||"^"===s||">>"===s||"<<"===s)return e.getIntegerType(n);if("!"===s||"=="===s||"!="===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("<"===s||">"===s||"<="===s||">="===s){const s=t?e.getTypeLength(t):Math.max(e.getTypeLength(n),e.getTypeLength(o));return s>1?`bvec${s}`:"bool"}if(e.isMatrix(n)){if("float"===o)return n;if(e.isVector(o))return e.getVectorFromMatrix(n);if(e.isMatrix(o))return n}else if(e.isMatrix(o)){if("float"===n)return o;if(e.isVector(n))return e.getVectorFromMatrix(o)}return e.getTypeLength(o)>e.getTypeLength(n)?o:n}generate(e,t){const s=this.op,i=this.aNode,r=this.bNode,n=this.getNodeType(e,t);let o=null,a=null;"void"!==n?(o=i.getNodeType(e),a=void 0!==r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s||"!="===s?e.isVector(o)?a=o:o!==a&&(o=a="float"):">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):"%"===s?(o=n,a=e.isInteger(o)&&e.isInteger(a)?a:o):e.isMatrix(o)?"float"===a?a="float":e.isVector(a)?a=e.getVectorFromMatrix(o):e.isMatrix(a)||(o=a=n):o=e.isMatrix(a)?"float"===o?"float":e.isVector(o)?e.getVectorFromMatrix(a):a=n:a=n):o=a=n;const h=i.build(e,o),l=void 0!==r?r.build(e,a):null,u=e.getTypeLength(t),c=e.getFunctionOperator(s);if("void"!==t){const i=e.renderer.coordinateSystem===Le;if("=="===s)return i?u>1?e.format(`${e.getMethod("equal",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} ${s} ${l} )`,n,t):u>1||!e.isVector(o)?e.format(`( ${h} == ${l} )`,n,t):e.format(`all( ${h} == ${l} )`,n,t);if("<"===s&&u>1)return i?e.format(`${e.getMethod("lessThan",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} < ${l} )`,n,t);if("<="===s&&u>1)return i?e.format(`${e.getMethod("lessThanEqual",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} <= ${l} )`,n,t);if(">"===s&&u>1)return i?e.format(`${e.getMethod("greaterThan",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} > ${l} )`,n,t);if(">="===s&&u>1)return i?e.format(`${e.getMethod("greaterThanEqual",t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} >= ${l} )`,n,t);if("%"===s)return e.isInteger(a)?e.format(`( ${h} % ${l} )`,n,t):e.format(`${e.getMethod("mod",n)}( ${h}, ${l} )`,n,t);if("!"===s||"~"===s)return e.format(`(${s}${h})`,o,t);if(c)return e.format(`${c}( ${h}, ${l} )`,n,t);if(e.isMatrix(o)&&"float"===a)return e.format(`( ${l} ${s} ${h} )`,n,t);if("float"===o&&e.isMatrix(a))return e.format(`${h} ${s} ${l}`,n,t);{let r=`( ${h} ${s} ${l} )`;return!i&&"bool"===n&&e.isVector(o)&&e.isVector(a)&&(r=`all${r}`),e.format(r,n,t)}}if("void"!==o)return c?e.format(`${c}( ${h}, ${l} )`,n,t):e.isMatrix(o)&&"float"===a?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 ya=to(fa,"+").setParameterLength(2,1/0).setName("add"),ba=to(fa,"-").setParameterLength(2,1/0).setName("sub"),xa=to(fa,"*").setParameterLength(2,1/0).setName("mul"),_a=to(fa,"/").setParameterLength(2,1/0).setName("div"),va=to(fa,"%").setParameterLength(2).setName("mod"),Ta=to(fa,"==").setParameterLength(2).setName("equal"),wa=to(fa,"!=").setParameterLength(2).setName("notEqual"),Sa=to(fa,"<").setParameterLength(2).setName("lessThan"),Ma=to(fa,">").setParameterLength(2).setName("greaterThan"),Na=to(fa,"<=").setParameterLength(2).setName("lessThanEqual"),Ea=to(fa,">=").setParameterLength(2).setName("greaterThanEqual"),Aa=to(fa,"&&").setParameterLength(2,1/0).setName("and"),Ca=to(fa,"||").setParameterLength(2,1/0).setName("or"),Ra=to(fa,"!").setParameterLength(1).setName("not"),Pa=to(fa,"^^").setParameterLength(2).setName("xor"),Fa=to(fa,"&").setParameterLength(2).setName("bitAnd"),Ba=to(fa,"~").setParameterLength(2).setName("bitNot"),Ia=to(fa,"|").setParameterLength(2).setName("bitOr"),La=to(fa,"^").setParameterLength(2).setName("bitXor"),Da=to(fa,"<<").setParameterLength(2).setName("shiftLeft"),Oa=to(fa,">>").setParameterLength(2).setName("shiftRight");Nn("add",ya),Nn("sub",ba),Nn("mul",xa),Nn("div",_a),Nn("mod",va),Nn("equal",Ta),Nn("notEqual",wa),Nn("lessThan",Sa),Nn("greaterThan",Ma),Nn("lessThanEqual",Na),Nn("greaterThanEqual",Ea),Nn("and",Aa),Nn("or",Ca),Nn("not",Ra),Nn("xor",Pa),Nn("bitAnd",Fa),Nn("bitNot",Ba),Nn("bitOr",Ia),Nn("bitXor",La),Nn("shiftLeft",Da),Nn("shiftRight",Oa);Nn("remainder",((e,t)=>(console.warn('THREE.TSL: "remainder()" is deprecated. Use "mod( int( ... ) )" instead.'),va(e,t)))),Nn("modInt",((e,t)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),va(uo(e),uo(t)))));class ka extends mn{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===ka.MAX||e===ka.MIN)&&arguments.length>3){let r=new ka(e,t,s);for(let t=2;t<arguments.length-1;t++)r=new ka(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),o=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>o?t:n>o?s:o>r?i:t}getNodeType(e){const t=this.method;return t===ka.LENGTH||t===ka.DISTANCE||t===ka.DOT?"float":t===ka.CROSS?"vec3":t===ka.ALL||t===ka.ANY?"bool":t===ka.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}generate(e,t){let s=this.method;const i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,o=this.bNode,a=this.cNode,h=e.renderer.coordinateSystem;if(s===ka.TRANSFORM_DIRECTION){let s=n,i=o;e.isMatrix(s.getNodeType(e))?i=To(bo(i),0):s=To(bo(s),0);const r=xa(s,i).xyz;return Ja(r).build(e,t)}if(s===ka.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);if(s===ka.ONE_MINUS)return ba(1,n).build(e,t);if(s===ka.RECIPROCAL)return _a(1,n).build(e,t);if(s===ka.DIFFERENCE)return ah(ba(n,o)).build(e,t);{const l=[];return s===ka.CROSS?l.push(n.build(e,i),o.build(e,i)):h===Le&&s===ka.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),o.build(e,r)):h!==Le||s!==ka.MIN&&s!==ka.MAX?s===ka.REFRACT?l.push(n.build(e,r),o.build(e,r),a.build(e,"float")):s===ka.MIX?l.push(n.build(e,r),o.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):(h===De&&s===ka.ATAN&&null!==o&&(s="atan2"),l.push(n.build(e,r)),null!==o&&l.push(o.build(e,r)),null!==a&&l.push(a.build(e,r))):l.push(n.build(e,r),o.build(e,1===e.getTypeLength(o.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}}ka.ALL="all",ka.ANY="any",ka.RADIANS="radians",ka.DEGREES="degrees",ka.EXP="exp",ka.EXP2="exp2",ka.LOG="log",ka.LOG2="log2",ka.SQRT="sqrt",ka.INVERSE_SQRT="inversesqrt",ka.FLOOR="floor",ka.CEIL="ceil",ka.NORMALIZE="normalize",ka.FRACT="fract",ka.SIN="sin",ka.COS="cos",ka.TAN="tan",ka.ASIN="asin",ka.ACOS="acos",ka.ATAN="atan",ka.ABS="abs",ka.SIGN="sign",ka.LENGTH="length",ka.NEGATE="negate",ka.ONE_MINUS="oneMinus",ka.DFDX="dFdx",ka.DFDY="dFdy",ka.ROUND="round",ka.RECIPROCAL="reciprocal",ka.TRUNC="trunc",ka.FWIDTH="fwidth",ka.TRANSPOSE="transpose",ka.BITCAST="bitcast",ka.EQUALS="equals",ka.MIN="min",ka.MAX="max",ka.STEP="step",ka.REFLECT="reflect",ka.DISTANCE="distance",ka.DIFFERENCE="difference",ka.DOT="dot",ka.CROSS="cross",ka.POW="pow",ka.TRANSFORM_DIRECTION="transformDirection",ka.MIX="mix",ka.CLAMP="clamp",ka.REFRACT="refract",ka.SMOOTHSTEP="smoothstep",ka.FACEFORWARD="faceforward";const Ua=lo(1e-6),za=lo(Math.PI),Va=to(ka,ka.ALL).setParameterLength(1),Ga=to(ka,ka.ANY).setParameterLength(1),ja=to(ka,ka.RADIANS).setParameterLength(1),Ha=to(ka,ka.DEGREES).setParameterLength(1),Wa=to(ka,ka.EXP).setParameterLength(1),$a=to(ka,ka.EXP2).setParameterLength(1),qa=to(ka,ka.LOG).setParameterLength(1),Xa=to(ka,ka.LOG2).setParameterLength(1),Ya=to(ka,ka.SQRT).setParameterLength(1),Ka=to(ka,ka.INVERSE_SQRT).setParameterLength(1),Qa=to(ka,ka.FLOOR).setParameterLength(1),Za=to(ka,ka.CEIL).setParameterLength(1),Ja=to(ka,ka.NORMALIZE).setParameterLength(1),eh=to(ka,ka.FRACT).setParameterLength(1),th=to(ka,ka.SIN).setParameterLength(1),sh=to(ka,ka.COS).setParameterLength(1),ih=to(ka,ka.TAN).setParameterLength(1),rh=to(ka,ka.ASIN).setParameterLength(1),nh=to(ka,ka.ACOS).setParameterLength(1),oh=to(ka,ka.ATAN).setParameterLength(1,2),ah=to(ka,ka.ABS).setParameterLength(1),hh=to(ka,ka.SIGN).setParameterLength(1),lh=to(ka,ka.LENGTH).setParameterLength(1),uh=to(ka,ka.NEGATE).setParameterLength(1),ch=to(ka,ka.ONE_MINUS).setParameterLength(1),dh=to(ka,ka.DFDX).setParameterLength(1),ph=to(ka,ka.DFDY).setParameterLength(1),mh=to(ka,ka.ROUND).setParameterLength(1),gh=to(ka,ka.RECIPROCAL).setParameterLength(1),fh=to(ka,ka.TRUNC).setParameterLength(1),yh=to(ka,ka.FWIDTH).setParameterLength(1),bh=to(ka,ka.TRANSPOSE).setParameterLength(1),xh=to(ka,ka.MIN).setParameterLength(2,1/0),_h=to(ka,ka.MAX).setParameterLength(2,1/0),vh=to(ka,ka.STEP).setParameterLength(2),Th=to(ka,ka.REFLECT).setParameterLength(2),wh=to(ka,ka.DISTANCE).setParameterLength(2),Sh=to(ka,ka.DIFFERENCE).setParameterLength(2),Mh=to(ka,ka.DOT).setParameterLength(2),Nh=to(ka,ka.CROSS).setParameterLength(2),Eh=to(ka,ka.POW).setParameterLength(2),Ah=to(ka,ka.POW,2).setParameterLength(1),Ch=to(ka,ka.POW,3).setParameterLength(1),Rh=to(ka,ka.POW,4).setParameterLength(1),Ph=to(ka,ka.TRANSFORM_DIRECTION).setParameterLength(2),Fh=e=>Mh(e,e),Bh=to(ka,ka.MIX).setParameterLength(3),Ih=(e,t=0,s=1)=>Zn(new ka(ka.CLAMP,Zn(e),Zn(t),Zn(s))),Lh=to(ka,ka.REFRACT).setParameterLength(3),Dh=to(ka,ka.SMOOTHSTEP).setParameterLength(3),Oh=to(ka,ka.FACEFORWARD).setParameterLength(3),kh=ro((([e])=>{const t=Mh(e.xy,mo(12.9898,78.233)),s=va(t,za);return eh(th(s).mul(43758.5453))}));Nn("all",Va),Nn("any",Ga),Nn("equals",((e,t)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),Ta(e,t)))),Nn("radians",ja),Nn("degrees",Ha),Nn("exp",Wa),Nn("exp2",$a),Nn("log",qa),Nn("log2",Xa),Nn("sqrt",Ya),Nn("inverseSqrt",Ka),Nn("floor",Qa),Nn("ceil",Za),Nn("normalize",Ja),Nn("fract",eh),Nn("sin",th),Nn("cos",sh),Nn("tan",ih),Nn("asin",rh),Nn("acos",nh),Nn("atan",oh),Nn("abs",ah),Nn("sign",hh),Nn("length",lh),Nn("lengthSq",Fh),Nn("negate",uh),Nn("oneMinus",ch),Nn("dFdx",dh),Nn("dFdy",ph),Nn("round",mh),Nn("reciprocal",gh),Nn("trunc",fh),Nn("fwidth",yh),Nn("atan2",((e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),oh(e,t)))),Nn("min",xh),Nn("max",_h),Nn("step",vh),Nn("reflect",Th),Nn("distance",wh),Nn("dot",Mh),Nn("cross",Nh),Nn("pow",Eh),Nn("pow2",Ah),Nn("pow3",Ch),Nn("pow4",Rh),Nn("transformDirection",Ph),Nn("mix",((e,t,s)=>Bh(t,s,e))),Nn("clamp",Ih),Nn("refract",Lh),Nn("smoothstep",((e,t,s)=>Dh(t,s,e))),Nn("faceForward",Oh),Nn("difference",Sh),Nn("saturate",(e=>Ih(e))),Nn("cbrt",(e=>xa(hh(e),Eh(ah(e),1/3)))),Nn("transpose",bh),Nn("rand",kh);class Uh extends cn{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 this.setup(e),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.cache(),s=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,r=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const n=e.getNodeProperties(this);n.condNode=t,n.ifNode=s.context({nodeBlock:s}),n.elseNode=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:o}=e.getNodeProperties(this),a=e.currentFunctionNode,h="void"!==t,l=h?Uo(s).build(e):"";i.nodeProperty=l;const u=r.build(e,"bool");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===a&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==o){e.addFlowCode(" else {\n\n").addFlowTab();let t=o.build(e,s);t&&(h?t=l+" = "+t+";":(t="return "+t+";",null===a&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),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 zh=to(Uh).setParameterLength(2,3);Nn("select",zh);Nn("cond",((...e)=>(console.warn("THREE.TSL: cond() has been renamed to select()."),zh(...e))));class Vh extends cn{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){this.node.build(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e);return e.setContext(t),s}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(s),i}}const Gh=to(Vh).setParameterLength(1,2);Nn("context",Gh),Nn("label",((e,t)=>Gh(e,{label:t})));class jh extends cn{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}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:s,readOnly:i}=this,{renderer:r}=e,n=!0===r.backend.isWebGPUBackend;let o=!1,a=!1;i&&(o=e.isDeterministic(t),a=n?i:o);const h=e.getVectorType(this.getNodeType(e)),l=t.build(e,h),u=e.getVarFromNode(this,s,h,void 0,a),c=e.getPropertyName(u);let d=c;if(a)if(n)d=o?`const ${c}`:`let ${c}`;else{const s=e.getArrayCount(t);d=`const ${e.getVar(u.type,c,s)}`}return e.addLineFlowCode(`${d} = ${l}`,this),c}}const Hh=to(jh);Nn("toVar",((e,t=null)=>Hh(e,t).append())),Nn("toConst",((e,t=null)=>Hh(e,t,!0).append()));Nn("temp",(e=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),Hh(e))));class Wh extends cn{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0}isGlobal(){return!0}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);t.varying=s=e.getVaryingFromNode(this,i,r),t.node=this.node}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e)}analyze(e){return this.setupVarying(e),this.node.analyze(e)}generate(e){const t=e.getNodeProperties(this),s=this.setupVarying(e),i="fragment"===e.shaderStage&&!0===t.reassignPosition&&e.context.needsPositionReassign;if(void 0===t.propertyName||i){const r=this.getNodeType(e),n=e.getPropertyName(s,Zr);e.flowNodeFromShaderStage(Zr,this.node,r,n),t.propertyName=n,i?t.reassignPosition=!1:void 0===t.reassignPosition&&e.context.isPositionNodeInput&&(t.reassignPosition=!0)}return e.getPropertyName(s)}}const $h=to(Wh).setParameterLength(1,2);Nn("toVarying",$h),Nn("toVertexStage",(e=>$h(e))),Nn("varying",((...e)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),$h(...e)))),Nn("vertexStage",((...e)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),$h(...e))));const qh=ro((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return Bh(t,s,i)})).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Xh=ro((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return Bh(t,s,i)})).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Yh="WorkingColorSpace",Kh="OutputColorSpace";class Qh extends mn{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===Yh?nt.workingColorSpace:t===Kh?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!==nt.enabled&&s!==i&&s&&i?(nt.getTransfer(s)===we&&(r=To(qh(r.rgb),r.a)),nt.getPrimaries(s)!==nt.getPrimaries(i)&&(r=To(Eo(nt._getMatrix(new Ke,s,i)).mul(r.rgb),r.a)),nt.getTransfer(i)===we&&(r=To(Xh(r.rgb),r.a)),r):r}}const Zh=(e,t)=>Zn(new Qh(Zn(e),t,Yh));Nn("toOutputColorSpace",(e=>Zn(new Qh(Zn(e),Yh,Kh)))),Nn("toWorkingColorSpace",(e=>Zn(new Qh(Zn(e),Kh,Yh)))),Nn("workingToColorSpace",((e,t)=>Zn(new Qh(Zn(e),Yh,t)))),Nn("colorSpaceToWorking",Zh);let Jh=class extends dn{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 el extends cn{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=sn}setGroup(e){return this.group=e,this}element(e){return Zn(new Jh(this,Zn(e)))}setNodeType(e){const t=Oo(null,e).getSelf();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 tl extends el{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(Io)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const sl=(e,t,s=null)=>Zn(new tl(e,t,s));class il extends mn{static get type(){return"ToneMappingNode"}constructor(e,t=rl,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return Hr(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=To(r(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const rl=sl("toneMappingExposure","float");Nn("toneMapping",((e,t,s)=>((e,t,s)=>Zn(new il(e,Zn(t),Zn(s))))(t,s,e)));class nl extends _n{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=Be,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(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=this.value,i=e.getTypeLength(t),r=this.bufferStride||i,n=this.bufferOffset,o=!0===s.isInterleavedBuffer?s:new Gi(s,r),a=new Hi(o,i,n);o.setUsage(this.usage),this.attribute=a,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=$h(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}}const ol=(e,t=null,s=0,i=0)=>Zn(new nl(e,t,s,i)),al=(e,t=null,s=0,i=0)=>ol(e,t,s,i).setInstanced(!0),hl=(e,t=null,s=0,i=0)=>((e,t=null,s=0,i=0)=>ol(e,t,s,i).setUsage(Ie))(e,t,s,i).setInstanced(!0);Nn("toAttribute",(e=>ol(e.value)));class ll extends cn{static get type(){return"ComputeNode"}constructor(e,t,s=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=s,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=sn,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let s=t[0];for(let e=1;e<t.length;e++)s*=t[e];this.dispatchCount=Math.ceil(e/s)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.setup(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)}}}Nn("compute",((e,t,s)=>Zn(new ll(Zn(e),t,s))));class ul extends cn{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!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}}const cl=(e,t)=>Zn(new ul(Zn(e),t));Nn("cache",cl);class dl extends cn{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)}}Nn("bypass",to(dl).setParameterLength(2));class pl extends cn{static get type(){return"RemapNode"}constructor(e,t,s,i=lo(0),r=lo(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 o=e.sub(t).div(s.sub(t));return!0===n&&(o=o.clamp()),o.mul(r.sub(i)).add(i)}}const ml=to(pl,null,null,{doClamp:!1}).setParameterLength(3,5),gl=to(pl).setParameterLength(3,5);Nn("remap",ml),Nn("remapClamp",gl);class fl extends cn{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 yl=to(fl).setParameterLength(1,2);Nn("discard",(e=>(e?zh(e,yl("discard")):yl("discard")).append()));class bl extends mn{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=s,this.isRenderOutputNode=!0}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)||xe;return 0!==s&&(t=t.toneMapping(s)),i!==xe&&i!==nt.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}Nn("renderOutput",((e,t=null,s=null)=>Zn(new bl(Zn(e),t,s))));class xl extends mn{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);let i="";return i+="// #--- TSL Debug ---#\n",i+=e.flow.code.replace(/^\t/gm,"")+"\n",i+="/* ... */ "+s+" /* ... */\n",i+="// #-----------------#\n",null!==t?t(i):console.log(i),s}}Nn("debug",((e,t=null)=>Zn(new xl(Zn(e),t))));class _l extends cn{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 $h(this).build(e,s)}return console.warn(`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 vl=(e,t)=>Zn(new _l(e,t)),Tl=(e=0)=>vl("uv"+(e>0?e:""),"vec2");class wl extends cn{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 Sl=to(wl).setParameterLength(1,2);class Ml extends Do{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=en}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 Nl=to(Ml).setParameterLength(1);class El extends Do{static get type(){return"TextureNode"}constructor(e,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.sampler=!0,this.updateMatrix=!1,this.updateType=Jr,this.referenceNode=null,this._value=e,this._matrixUniform=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===U?"uvec4":this.value.type===k?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Tl(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Oo(this.value.matrix)),this._matrixUniform.mul(bo(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?tn:Jr,this}setupUV(e,t){const s=this.value;return e.isFlipY()&&(s.image instanceof ImageBitmap&&!0===s.flipY||!0===s.isRenderTargetTexture||!0===s.isFramebufferTexture||!0===s.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(uo(Sl(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const s=this.value;if(!s||!0!==s.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let i=this.uvNode;null!==i&&!0!==e.context.forceUVContext||!e.context.getUV||(i=e.context.getUV(this)),i||(i=this.getDefaultUV()),!0===this.updateMatrix&&(i=this.getTransformedUV(i)),i=this.setupUV(e,i);let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,s,i,r,n,o,a){const h=this.value;let l;return l=i?e.generateTextureLevel(h,t,s,i,n):r?e.generateTextureBias(h,t,s,r,n):a?e.generateTextureGrad(h,t,s,a,n):o?e.generateTextureCompare(h,t,s,o,n):!1===this.sampler?e.generateTextureLoad(h,t,s,n):e.generateTexture(h,t,s,n),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);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:s,biasNode:a,compareNode:h,depthNode:l,gradNode:u}=i,c=this.generateUV(e,t),d=s?s.build(e,"float"):null,p=a?a.build(e,"float"):null,m=l?l.build(e,"int"):null,g=h?h.build(e,"float"):null,f=u?[u[0].build(e,"vec2"),u[1].build(e,"vec2")]:null,y=e.getVarFromNode(this);o=e.getPropertyName(y);const b=this.generateSnippet(e,r,c,d,p,m,g,f);e.addLineFlowCode(`${o} = ${b}`,this),n.snippet=b,n.propertyName=o}let a=o;const h=this.getNodeType(e);return e.needsToWorkingColorSpace(s)&&(a=Zh(yl(a,h),s.colorSpace).setup(e).build(e,h)),e.format(a,h,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=Zn(e),t.referenceNode=this.getSelf(),Zn(t)}blur(e){const t=this.clone();t.biasNode=Zn(e).mul(Nl(t)),t.referenceNode=this.getSelf();const s=t.value;return(s&&!1===s.generateMipmaps||s.minFilter===A||s.magFilter===A)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Zn(t)}level(e){const t=this.clone();return t.levelNode=Zn(e),t.referenceNode=this.getSelf(),Zn(t)}size(e){return Sl(this,e)}bias(e){const t=this.clone();return t.biasNode=Zn(e),t.referenceNode=this.getSelf(),Zn(t)}compare(e){const t=this.clone();return t.compareNode=Zn(e),t.referenceNode=this.getSelf(),Zn(t)}grad(e,t){const s=this.clone();return s.gradNode=[Zn(e),Zn(t)],s.referenceNode=this.getSelf(),Zn(s)}depth(e){const t=this.clone();return t.depthNode=Zn(e),t.referenceNode=this.getSelf(),Zn(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()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e}}const Al=to(El).setParameterLength(1,4),Cl=(...e)=>Al(...e).setSampler(!1);class Rl extends Do{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Pl=(e,t,s)=>Zn(new Rl(e,t,s));class Fl extends dn{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 Bl extends Rl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Yr(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=tn,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,super.setup(e)}element(e){return Zn(new Fl(this,Zn(e)))}}const Il=(e,t)=>Zn(new Bl(e,t)),Ll=Oo(0,"uint").setGroup(Fo("cameraIndex")).toVarying("v_cameraIndex"),Dl=Oo("float").label("cameraNear").setGroup(Io).onRenderUpdate((({camera:e})=>e.near)),Ol=Oo("float").label("cameraFar").setGroup(Io).onRenderUpdate((({camera:e})=>e.far)),kl=ro((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrix);t=Il(s).setGroup(Io).label("cameraProjectionMatrices").element(Ll).toVar("cameraProjectionMatrix")}else t=Oo("mat4").label("cameraProjectionMatrix").setGroup(Io).onRenderUpdate((({camera:e})=>e.projectionMatrix));return t})).once()(),Ul=ro((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorldInverse);t=Il(s).setGroup(Io).label("cameraViewMatrices").element(Ll).toVar("cameraViewMatrix")}else t=Oo("mat4").label("cameraViewMatrix").setGroup(Io).onRenderUpdate((({camera:e})=>e.matrixWorldInverse));return t})).once()(),zl=Oo(new _t).label("cameraPosition").setGroup(Io).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),Vl=new Vt;class Gl extends cn{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=sn,this._uniformNode=new Do(null)}getNodeType(){const e=this.scope;return e===Gl.WORLD_MATRIX?"mat4":e===Gl.POSITION||e===Gl.VIEW_POSITION||e===Gl.DIRECTION||e===Gl.SCALE?"vec3":e===Gl.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this._uniformNode,i=this.scope;if(i===Gl.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Gl.POSITION)s.value=s.value||new _t,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Gl.SCALE)s.value=s.value||new _t,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Gl.DIRECTION)s.value=s.value||new _t,t.getWorldDirection(s.value);else if(i===Gl.VIEW_POSITION){const i=e.camera;s.value=s.value||new _t,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Gl.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),Vl.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),s.value=Vl.radius}}generate(e){const t=this.scope;return t===Gl.WORLD_MATRIX?this._uniformNode.nodeType="mat4":t===Gl.POSITION||t===Gl.VIEW_POSITION||t===Gl.DIRECTION||t===Gl.SCALE?this._uniformNode.nodeType="vec3":t===Gl.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}}Gl.WORLD_MATRIX="worldMatrix",Gl.POSITION="position",Gl.SCALE="scale",Gl.VIEW_POSITION="viewPosition",Gl.DIRECTION="direction",Gl.RADIUS="radius";const jl=to(Gl,Gl.POSITION).setParameterLength(1);class Hl extends Gl{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Wl=so(Hl,Hl.WORLD_MATRIX),$l=Oo(new Ke).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),ql=ro((e=>e.renderer.nodes.modelViewMatrix||Xl)).once()().toVar("modelViewMatrix"),Xl=Ul.mul(Wl),Yl=vl("position","vec3"),Kl=Yl.toVarying("positionLocal"),Ql=Yl.toVarying("positionPrevious"),Zl=Wl.mul(Kl).xyz.toVarying("v_positionWorld").context({needsPositionReassign:!0}),Jl=Kl.transformDirection(Wl).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection").context({needsPositionReassign:!0}),eu=ro((e=>e.context.setupPositionView()),"vec3").once()().toVarying("v_positionView").context({needsPositionReassign:!0}),tu=eu.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class su extends cn{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Le&&1===s.side?"false":e.getFrontFacing()}}const iu=lo(so(su)).mul(2).sub(1),ru=vl("normal","vec3"),nu=ro((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),bo(0,1,0)):ru),"vec3").once()().toVar("normalLocal"),ou=eu.dFdx().cross(eu.dFdy()).normalize().toVar("normalFlat"),au=ro((e=>{let t;return t=!0===e.material.flatShading?ou:$h(pu(nu),"v_normalView").normalize(),t}),"vec3").once()().toVar("normalView"),hu=$h(au.transformDirection(Ul),"v_normalWorld").normalize().toVar("normalWorld"),lu=ro((e=>e.context.setupNormal().context({getUV:null})),"vec3").once()().mul(iu).toVar("transformedNormalView"),uu=lu.transformDirection(Ul).toVar("transformedNormalWorld"),cu=ro((e=>e.context.setupClearcoatNormal().context({getUV:null})),"vec3").once()().mul(iu).toVar("transformedClearcoatNormalView"),du=ro((([e,t=Wl])=>{const s=Eo(t),i=e.div(bo(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz})),pu=ro((([e],t)=>{const s=t.renderer.nodes.modelNormalViewMatrix;if(null!==s)return s.transformDirection(e);const i=$l.mul(e);return Ul.transformDirection(i)})),mu=new os,gu=new Kt,fu=Oo(0).onReference((({material:e})=>e)).onObjectUpdate((({material:e})=>e.refractionRatio)),yu=Oo(1).onReference((({material:e})=>e)).onObjectUpdate((function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity})),bu=Oo(new Kt).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?(mu.copy(s),gu.makeRotationFromEuler(mu)):gu.identity(),gu})),xu=tu.negate().reflect(lu),_u=tu.negate().refract(lu,fu),vu=xu.transformDirection(Ul).toVar("reflectVector"),Tu=_u.transformDirection(Ul).toVar("reflectVector");class wu extends El{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===v?vu:e.mapping===T?Tu:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),bo(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.renderer.coordinateSystem!==De&&s.isRenderTargetTexture||(t=bo(t.x.negate(),t.yz)),bu.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const Su=to(wu).setParameterLength(1,4).setName("cubeTexture");class Mu extends dn{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 Nu extends cn{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=sn}element(e){return Zn(new Mu(this,Zn(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Pl(null,e,this.count):Array.isArray(this.getValueFromReference())?Il(null,e):"texture"===e?Al(null):"cubeTexture"===e?Su(null):Oo(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}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 Eu=(e,t,s)=>Zn(new Nu(e,t,s)),Au=(e,t,s,i)=>Zn(new Nu(e,t,i,s));class Cu extends Nu{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 Ru=(e,t,s=null)=>Zn(new Cu(e,t,s)),Pu=ro((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),vl("tangent","vec4"))))(),Fu=Pu.xyz.toVar("tangentLocal"),Bu=ql.mul(To(Fu,0)).xyz.toVarying("v_tangentView").normalize().toVar("tangentView");var Iu;const Lu=Eo(Bu,$h((Iu=au.cross(Bu),Iu.mul(Pu.w).xyz),"v_bitangentView").normalize().toVar("bitangentView"),au),Du=(()=>{let e=ta.cross(tu);return e=e.cross(ta).normalize(),e=Bh(e,lu,Jo.mul(jo.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})(),Ou=ro((e=>{const{eye_pos:t,surf_norm:s,mapN:i,uv:r}=e,n=t.dFdx(),o=t.dFdy(),a=r.dFdx(),h=r.dFdy(),l=s,u=o.cross(l),c=l.cross(n),d=u.mul(a.x).add(c.mul(h.x)),p=u.mul(a.y).add(c.mul(h.y)),m=d.dot(d).max(p.dot(p)),g=iu.mul(m.inverseSqrt());return ya(d.mul(i.x,g),p.mul(i.y,g),l.mul(i.z)).normalize()}));class ku extends mn{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup(e){const{normalMapType:t,scaleNode:s}=this;let i=this.node.mul(2).sub(1);null!==s&&(i=bo(i.xy.mul(s),i.z));let r=null;if(1===t)r=pu(i);else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?Lu.mul(i).normalize():Ou({eye_pos:eu,surf_norm:au,mapN:i,uv:Tl()})}return r}}const Uu=to(ku).setParameterLength(1,2),zu=ro((({textureNode:e,bumpScale:t})=>{const s=t=>e.cache().context({getUV:e=>t(e.uvNode||Tl()),forceUVContext:!0}),i=lo(s((e=>e)));return mo(lo(s((e=>e.add(e.dFdx())))).sub(i),lo(s((e=>e.add(e.dFdy())))).sub(i)).mul(t)})),Vu=ro((e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,o=t.dFdy().normalize().cross(n),a=n.cross(r),h=r.dot(o).mul(iu),l=h.sign().mul(i.x.mul(o).add(i.y.mul(a)));return h.abs().mul(s).sub(l).normalize()}));class Gu extends mn{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=zu({textureNode:this.textureNode,bumpScale:e});return Vu({surf_pos:eu,surf_norm:au,dHdxy:t})}}const ju=to(Gu).setParameterLength(1,2),Hu=new Map;class Wu extends cn{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=Hu.get(e);return void 0===s&&(s=Ru(e,t),Hu.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===Wu.COLOR){const e=void 0!==t.color?this.getColor(s):bo();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===Wu.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===Wu.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:lo(1);else if(s===Wu.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(s).a):e}else if(s===Wu.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===Wu.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===Wu.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===Wu.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===Wu.NORMAL)t.normalMap?(i=Uu(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):i=t.bumpMap?ju(this.getTexture("bump").r,this.getFloat("bumpScale")):au;else if(s===Wu.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Wu.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Wu.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?Uu(this.getTexture(s),this.getCache(s+"Scale","vec2")):au;else if(s===Wu.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===Wu.SHEEN_ROUGHNESS){const e=this.getFloat(s);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,i=i.clamp(.07,1)}else if(s===Wu.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=No(Ac.x,Ac.y,Ac.y.negate(),Ac.x).mul(e.rg.mul(2).sub(mo(1)).normalize().mul(e.b))}else i=Ac;else if(s===Wu.IRIDESCENCE_THICKNESS){const e=Eu("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Eu("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===Wu.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===Wu.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===Wu.IOR)i=this.getFloat(s);else if(s===Wu.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===Wu.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}Wu.ALPHA_TEST="alphaTest",Wu.COLOR="color",Wu.OPACITY="opacity",Wu.SHININESS="shininess",Wu.SPECULAR="specular",Wu.SPECULAR_STRENGTH="specularStrength",Wu.SPECULAR_INTENSITY="specularIntensity",Wu.SPECULAR_COLOR="specularColor",Wu.REFLECTIVITY="reflectivity",Wu.ROUGHNESS="roughness",Wu.METALNESS="metalness",Wu.NORMAL="normal",Wu.CLEARCOAT="clearcoat",Wu.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Wu.CLEARCOAT_NORMAL="clearcoatNormal",Wu.EMISSIVE="emissive",Wu.ROTATION="rotation",Wu.SHEEN="sheen",Wu.SHEEN_ROUGHNESS="sheenRoughness",Wu.ANISOTROPY="anisotropy",Wu.IRIDESCENCE="iridescence",Wu.IRIDESCENCE_IOR="iridescenceIOR",Wu.IRIDESCENCE_THICKNESS="iridescenceThickness",Wu.IOR="ior",Wu.TRANSMISSION="transmission",Wu.THICKNESS="thickness",Wu.ATTENUATION_DISTANCE="attenuationDistance",Wu.ATTENUATION_COLOR="attenuationColor",Wu.LINE_SCALE="scale",Wu.LINE_DASH_SIZE="dashSize",Wu.LINE_GAP_SIZE="gapSize",Wu.LINE_WIDTH="linewidth",Wu.LINE_DASH_OFFSET="dashOffset",Wu.POINT_SIZE="size",Wu.DISPERSION="dispersion",Wu.LIGHT_MAP="light",Wu.AO="ao";const $u=so(Wu,Wu.ALPHA_TEST),qu=so(Wu,Wu.COLOR),Xu=so(Wu,Wu.SHININESS),Yu=so(Wu,Wu.EMISSIVE),Ku=so(Wu,Wu.OPACITY),Qu=so(Wu,Wu.SPECULAR),Zu=so(Wu,Wu.SPECULAR_INTENSITY),Ju=so(Wu,Wu.SPECULAR_COLOR),ec=so(Wu,Wu.SPECULAR_STRENGTH),tc=so(Wu,Wu.REFLECTIVITY),sc=so(Wu,Wu.ROUGHNESS),ic=so(Wu,Wu.METALNESS),rc=so(Wu,Wu.NORMAL),nc=so(Wu,Wu.CLEARCOAT),oc=so(Wu,Wu.CLEARCOAT_ROUGHNESS),ac=so(Wu,Wu.CLEARCOAT_NORMAL),hc=so(Wu,Wu.ROTATION),lc=so(Wu,Wu.SHEEN),uc=so(Wu,Wu.SHEEN_ROUGHNESS),cc=so(Wu,Wu.ANISOTROPY),dc=so(Wu,Wu.IRIDESCENCE),pc=so(Wu,Wu.IRIDESCENCE_IOR),mc=so(Wu,Wu.IRIDESCENCE_THICKNESS),gc=so(Wu,Wu.TRANSMISSION),fc=so(Wu,Wu.THICKNESS),yc=so(Wu,Wu.IOR),bc=so(Wu,Wu.ATTENUATION_DISTANCE),xc=so(Wu,Wu.ATTENUATION_COLOR),_c=so(Wu,Wu.LINE_SCALE),vc=so(Wu,Wu.LINE_DASH_SIZE),Tc=so(Wu,Wu.LINE_GAP_SIZE);Wu.LINE_WIDTH;const wc=so(Wu,Wu.LINE_DASH_OFFSET),Sc=so(Wu,Wu.POINT_SIZE),Mc=so(Wu,Wu.DISPERSION),Nc=so(Wu,Wu.LIGHT_MAP),Ec=so(Wu,Wu.AO),Ac=Oo(new Ye).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))})),Cc=ro((e=>e.context.setupModelViewProjection()),"vec4").once()().toVarying("v_modelViewProjection");class Rc extends cn{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===Rc.VERTEX)i=e.getVertexIndex();else if(s===Rc.INSTANCE)i=e.getInstanceIndex();else if(s===Rc.DRAW)i=e.getDrawIndex();else if(s===Rc.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===Rc.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==Rc.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=$h(this).build(e,t)}return r}}Rc.VERTEX="vertex",Rc.INSTANCE="instance",Rc.SUBGROUP="subgroup",Rc.INVOCATION_LOCAL="invocationLocal",Rc.INVOCATION_SUBGROUP="invocationSubgroup",Rc.DRAW="draw";const Pc=so(Rc,Rc.VERTEX),Fc=so(Rc,Rc.INSTANCE);Rc.SUBGROUP,Rc.INVOCATION_SUBGROUP,Rc.INVOCATION_LOCAL;const Bc=so(Rc,Rc.DRAW);class Ic extends cn{static get type(){return"InstanceNode"}constructor(e,t,s){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=s,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=en,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:s,instanceColor:i}=this;let{instanceMatrixNode:r,instanceColorNode:n}=this;if(null===r){if(t<=1e3)r=Pl(s.array,"mat4",Math.max(t,1)).element(Fc);else{const e=new kr(s.array,16,1);this.buffer=e;const t=s.usage===Ie?hl:al,i=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];r=Ao(...i)}this.instanceMatrixNode=r}if(i&&null===n){const e=new qi(i.array,3),t=i.usage===Ie?hl:al;this.bufferColor=e,n=bo(t(e,"vec3",3,0)),this.instanceColorNode=n}const o=r.mul(Kl).xyz;if(Kl.assign(o),e.hasGeometryAttribute("normal")){const e=du(nu,r);nu.assign(e)}null!==this.instanceColorNode&&zo("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==Ie&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==Ie&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}class Lc extends Ic{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const Dc=to(Lc).setParameterLength(1);class Oc extends cn{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=Fc:this.batchingIdNode=Bc);const t=ro((([e])=>{const t=uo(Sl(Cl(this.batchMesh._indirectTexture),0).x),s=uo(e).mod(t),i=uo(e).div(t);return Cl(this.batchMesh._indirectTexture,go(s,i)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(uo(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=uo(Sl(Cl(i),0).x),n=lo(s).mul(4).toInt().toVar(),o=n.mod(r),a=n.div(r),h=Ao(Cl(i,go(o,a)),Cl(i,go(o.add(1),a)),Cl(i,go(o.add(2),a)),Cl(i,go(o.add(3),a))),l=this.batchMesh._colorsTexture;if(null!==l){const e=ro((([e])=>{const t=uo(Sl(Cl(l),0).x),s=e,i=s.mod(t),r=s.div(t);return Cl(l,go(i,r)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);zo("vec3","vBatchColor").assign(t)}const u=Eo(h);Kl.assign(h.mul(Kl));const c=nu.div(bo(u[0].dot(u[0]),u[1].dot(u[1]),u[2].dot(u[2]))),d=u.mul(c).xyz;nu.assign(d),e.hasGeometryAttribute("tangent")&&Fu.mulAssign(u)}}const kc=to(Oc).setParameterLength(1),Uc=new WeakMap;class zc extends cn{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=sn,this.skinIndexNode=vl("skinIndex","uvec4"),this.skinWeightNode=vl("skinWeight","vec4"),this.bindMatrixNode=Eu("bindMatrix","mat4"),this.bindMatrixInverseNode=Eu("bindMatrixInverse","mat4"),this.boneMatricesNode=Au("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Kl,this.toPositionNode=Kl,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),h=e.element(s.z),l=e.element(s.w),u=r.mul(t),c=ya(o.mul(i.x).mul(u),a.mul(i.y).mul(u),h.mul(i.z).mul(u),l.mul(i.w).mul(u));return n.mul(c).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=nu){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),h=e.element(s.z),l=e.element(s.w);let u=ya(i.x.mul(o),i.y.mul(a),i.z.mul(h),i.w.mul(l));return u=n.mul(u).mul(r),u.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=Au("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Ql)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Qr(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&Ql.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();nu.assign(t),e.hasGeometryAttribute("tangent")&&Fu.assign(t)}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;Uc.get(t)!==e.frameId&&(Uc.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}class Vc extends cn{static get type(){return"LoopNode"}constructor(e=[]){super(),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]=yl(i,r)}const i=e.addStack();return t.returnsNode=this.params[this.params.length-1](s,i,e),t.stackNode=i,e.removeStack(),t}getNodeType(e){const{returnsNode:t}=this.getProperties(e);return t?t.getNodeType(e):"void"}setup(e){this.getProperties(e)}generate(e){const t=this.getProperties(e),s=this.params,i=t.stackNode;for(let t=0,i=s.length-1;t<i;t++){const i=s[t];let r,n=!1,o=null,a=null,h=null,l=null,u=null,c=null;if(i.isNode?"bool"===i.getNodeType(e)?(n=!0,l="bool",a=i.build(e,l)):(l="int",h=this.getVarName(t),o="0",a=i.build(e,l),u="<"):(l=i.type||"int",h=i.name||this.getVarName(t),o=i.start,a=i.end,u=i.condition,c=i.update,"number"==typeof o?o=e.generateConst(l,o):o&&o.isNode&&(o=o.build(e,l)),"number"==typeof a?a=e.generateConst(l,a):a&&a.isNode&&(a=a.build(e,l)),void 0!==o&&void 0===a?(o+=" - 1",a="0",u=">="):void 0!==a&&void 0===o&&(o="0",u="<"),void 0===u&&(u=Number(o)>Number(a)?">=":"<")),n)r=`while ( ${a} )`;else{const t={start:o,end:a},s=t.start,i=t.end;let n="",d="",p="";c||(c="int"===l||"uint"===l?u.includes("<")?"++":"--":u.includes("<")?"+= 1.":"-= 1."),n+=e.getVar(l,h)+" = "+s,d+=h+" "+u+" "+i,p+=h+" "+c,r=`for ( ${n}; ${d}; ${p} )`}e.addFlowCode((0===t?"\n":"")+e.tab+r+" {\n\n").addFlowTab()}const r=i.build(e,"void"),n=t.returnsNode?t.returnsNode.build(e):"";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();return e.addFlowTab(),n}}const Gc=(...e)=>Zn(new Vc(eo(e,"int"))).append(),jc=new WeakMap,Hc=new gt,Wc=ro((({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const o=uo(Pc).mul(s).add(n),a=o.div(i),h=o.sub(a.mul(i));return Cl(e,go(h,a)).depth(r).xyz.mul(t)}));class $c extends cn{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Oo(1),this.updateType=sn}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:o,stride:a,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 o=jc.get(e);if(void 0===o||o.count!==n){void 0!==o&&o.texture.dispose();const a=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 bt(m,c,d,n);g.type=z,g.needsUpdate=!0;const f=4*u;for(let b=0;b<n;b++){const x=a[b],_=h[b],v=l[b],T=c*d*4*b;for(let w=0;w<x.count;w++){const S=w*f;!0===t&&(Hc.fromBufferAttribute(x,w),m[T+S+0]=Hc.x,m[T+S+1]=Hc.y,m[T+S+2]=Hc.z,m[T+S+3]=0),!0===s&&(Hc.fromBufferAttribute(_,w),m[T+S+4]=Hc.x,m[T+S+5]=Hc.y,m[T+S+6]=Hc.z,m[T+S+7]=0),!0===i&&(Hc.fromBufferAttribute(v,w),m[T+S+8]=Hc.x,m[T+S+9]=Hc.y,m[T+S+10]=Hc.z,m[T+S+11]=4===v.itemSize?Hc.w:1)}}function y(){g.dispose(),jc.delete(e),e.removeEventListener("dispose",y)}o={count:n,texture:g,stride:u,size:new Ye(c,d)},jc.set(e,o),e.addEventListener("dispose",y)}return o}(t);!0===s&&Kl.mulAssign(this.morphBaseInfluence),!0===i&&nu.mulAssign(this.morphBaseInfluence);const l=uo(h.width);Gc(n,(({i:e})=>{const t=lo(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Cl(this.mesh.morphTexture,go(uo(e).add(1),uo(Fc))).r):t.assign(Eu("morphTargetInfluences","float").element(e).toVar()),ao(t.notEqual(0),(()=>{!0===s&&Kl.addAssign(Wc({bufferMap:o,influence:t,stride:a,width:l,depth:e,offset:uo(0)})),!0===i&&nu.addAssign(Wc({bufferMap:o,influence:t,stride:a,width:l,depth:e,offset:uo(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 qc=to($c).setParameterLength(1);class Xc extends cn{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Yc extends Xc{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Kc extends Vh{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:bo().toVar("directDiffuse"),directSpecular:bo().toVar("directSpecular"),indirectDiffuse:bo().toVar("indirectDiffuse"),indirectSpecular:bo().toVar("indirectSpecular")};return{radiance:bo().toVar("radiance"),irradiance:bo().toVar("irradiance"),iblIrradiance:bo().toVar("iblIrradiance"),ambientOcclusion:lo(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 Qc=to(Kc);class Zc extends Xc{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Jc,ed;class td extends cn{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===td.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Jr;return this.scope!==td.SIZE&&this.scope!==td.VIEWPORT||(e=tn),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===td.VIEWPORT?null!==t?ed.copy(t.viewport):(e.getViewport(ed),ed.multiplyScalar(e.getPixelRatio())):null!==t?(Jc.width=t.width,Jc.height=t.height):e.getDrawingBufferSize(Jc)}setup(){const e=this.scope;let t=null;return t=e===td.SIZE?Oo(Jc||(Jc=new Ye)):e===td.VIEWPORT?Oo(ed||(ed=new gt)):mo(rd.div(id)),t}generate(e){if(this.scope===td.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(id).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}td.COORDINATE="coordinate",td.VIEWPORT="viewport",td.SIZE="size",td.UV="uv";const sd=so(td,td.UV),id=so(td,td.SIZE),rd=so(td,td.COORDINATE),nd=so(td,td.VIEWPORT);nd.zw,nd.xy;const od=new Ye;class ad extends El{static get type(){return"ViewportTextureNode"}constructor(e=sd,t=null,s=null){null===s&&((s=new ir).minFilter=B),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=en}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(od);const s=this.value;s.image.width===od.width&&s.image.height===od.height||(s.image.width=od.width,s.image.height=od.height,s.needsUpdate=!0);const i=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=i}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const hd=to(ad,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let ld=null;class ud extends ad{static get type(){return"ViewportDepthTextureNode"}constructor(e=sd,t=null){null===ld&&(ld=new rr),super(e,t,ld)}}const cd=to(ud).setParameterLength(0,2);class dd extends cn{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===dd.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===dd.DEPTH_BASE)null!==s&&(i=yd().assign(s));else if(t===dd.DEPTH)i=e.isPerspectiveCamera?md(eu.z,Dl,Ol):pd(eu.z,Dl,Ol);else if(t===dd.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=gd(s,Dl,Ol);i=pd(e,Dl,Ol)}else i=s;else i=pd(eu.z,Dl,Ol);return i}}dd.DEPTH_BASE="depthBase",dd.DEPTH="depth",dd.LINEAR_DEPTH="linearDepth";const pd=(e,t,s)=>e.add(t).div(t.sub(s)),md=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),gd=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),fd=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Xa(e.negate().div(t)),r=Xa(s.div(t));return i.div(r)},yd=to(dd,dd.DEPTH_BASE),bd=so(dd,dd.DEPTH);cd(),bd.assign=e=>yd(e);const xd=to(class extends cn{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);class _d extends cn{static get type(){return"ClippingNode"}constructor(e=_d.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===_d.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===_d.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return ro((()=>{const s=lo().toVar("distanceToPlane"),i=lo().toVar("distanceToGradient"),r=lo(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=Il(t);Gc(n,(({i:t})=>{const n=e.element(t);s.assign(eu.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(Dh(i.negate(),i,s))}))}const o=e.length;if(o>0){const t=Il(e),n=lo(1).toVar("intersectionClipOpacity");Gc(o,(({i:e})=>{const r=t.element(e);s.assign(eu.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(Dh(i.negate(),i,s).oneMinus())})),r.mulAssign(n.oneMinus())}Vo.a.mulAssign(r),Vo.a.equal(0).discard()}))()}setupDefault(e,t){return ro((()=>{const s=t.length;if(!1===this.hardwareClipping&&s>0){const e=Il(t);Gc(s,(({i:t})=>{const s=e.element(t);eu.dot(s.xyz).greaterThan(s.w).discard()}))}const i=e.length;if(i>0){const t=Il(e),s=po(!0).toVar("clipped");Gc(i,(({i:e})=>{const i=t.element(e);s.assign(eu.dot(i.xyz).greaterThan(i.w).and(s))})),s.discard()}}))()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),ro((()=>{const i=Il(e),r=xd(t.getClipDistance());Gc(s,(({i:e})=>{const t=i.element(e),s=eu.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)}))}))()}}_d.ALPHA_TO_COVERAGE="alphaToCoverage",_d.DEFAULT="default",_d.HARDWARE="hardware";const vd=ro((([e])=>eh(xa(1e4,th(xa(17,e.x).add(xa(.1,e.y)))).mul(ya(.1,ah(th(xa(13,e.y).add(e.x)))))))),Td=ro((([e])=>vd(mo(vd(e.xy),e.z)))),wd=ro((([e])=>{const t=_h(lh(dh(e.xyz)),lh(ph(e.xyz))),s=lo(1).div(lo(.05).mul(t)).toVar("pixScale"),i=mo($a(Qa(Xa(s))),$a(Za(Xa(s)))),r=mo(Td(Qa(i.x.mul(e.xyz))),Td(Qa(i.y.mul(e.xyz)))),n=eh(Xa(s)),o=ya(xa(n.oneMinus(),r.x),xa(n,r.y)),a=xh(n,n.oneMinus()),h=bo(o.mul(o).div(xa(2,a).mul(ba(1,a))),o.sub(xa(.5,a)).div(ba(1,a)),ba(1,ba(1,o).mul(ba(1,o)).div(xa(2,a).mul(ba(1,a))))),l=o.lessThan(a.oneMinus()).select(o.lessThan(a).select(h.x,h.y),h.z);return Ih(l,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Sd extends Ws{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.positionNode=null,this.geometryNode=null,this.depthNode=null,this.shadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+Wr(this)}build(e){this.setup(e)}setupObserver(e){return new Vr(e)}setup(e){e.context.setupNormal=()=>this.setupNormal(e),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();e.addStack();const i=this.vertexNode||this.setupVertex(e);let r;e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const n=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!==n&&e.stack.add(n);const o=To(i,Vo.a).max(0);r=this.setupOutput(e,o),na.assign(r);const a=null!==this.outputNode;if(a&&(r=this.outputNode),null!==s){const e=t.getMRT(),s=this.mrtNode;null!==e?(a&&na.assign(r),r=e,null!==s&&(r=e.merge(s))):null!==s&&(r=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=To(t)),r=this.setupOutput(e,t)}e.stack.outputNode=r,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.samples;this.alphaToCoverage&&t>1?i=Zn(new _d(_d.ALPHA_TO_COVERAGE)):e.stack.add(Zn(new _d))}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.add(Zn(new _d(_d.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?fd(eu.z,Dl,Ol):pd(eu.z,Dl,Ol))}null!==i&&bd.assign(i).append()}setupPositionView(){return ql.mul(Kl).xyz}setupModelViewProjection(){return kl.mul(eu)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),Cc}setupPosition(e){const{object:t,geometry:s}=e;var i;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&qc(t).append(),!0===t.isSkinnedMesh&&(i=t,Zn(new zc(i))).append(),this.displacementMap){const e=Ru("displacementMap","texture"),t=Ru("displacementScale","float"),s=Ru("displacementBias","float");Kl.addAssign(nu.normalize().mul(e.x.mul(t).add(s)))}return t.isBatchedMesh&&kc(t).append(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Dc(t).append(),null!==this.positionNode&&Kl.assign(this.positionNode.context({isPositionNodeInput:!0})),Kl}setupDiffuseColor({object:e,geometry:t}){let s=this.colorNode?To(this.colorNode):qu;if(!0===this.vertexColors&&t.hasAttribute("color")&&(s=To(s.xyz.mul(vl("color","vec3")),s.a)),e.instanceColor){s=zo("vec3","vInstanceColor").mul(s)}if(e.isBatchedMesh&&e._colorsTexture){s=zo("vec3","vBatchColor").mul(s)}Vo.assign(s);const i=this.opacityNode?lo(this.opacityNode):Ku;if(Vo.a.assign(Vo.a.mul(i)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?lo(this.alphaTestNode):$u;Vo.a.lessThanEqual(e).discard()}!0===this.alphaHash&&Vo.a.lessThan(wd(Kl)).discard(),!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage&&Vo.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?bo(0):Vo.rgb}setupNormal(){return this.normalNode?bo(this.normalNode):rc}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Ru("envMap","cubeTexture"):Ru("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Zc(Nc)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Ec;t.push(new Yc(e))}let r=this.lightsNode||e.lightsNode;return t.length>0&&(r=e.renderer.lighting.createNode([...r.getLights(),...t])),r}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 o=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;o=Qc(n,t,s,i)}else null!==s&&(o=bo(null!==i?Bh(o,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Go.assign(bo(r||Yu)),o=o.add(Go)),o}setupFog(e,t){const s=e.fogNode;return s&&(na.assign(t),t=To(s)),t}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(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=Ws.prototype.toJSON.call(this,e),i=$r(this);s.inputNodes={};for(const{property:t,childNode:r}of i)s.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(t){const t=r(e.textures),i=r(e.images),n=r(e.nodes);t.length>0&&(s.textures=t),i.length>0&&(s.images=i),n.length>0&&(s.nodes=n)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,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.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.shadowPositionNode=e.shadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const Md=new tr;class Nd extends Sd{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Md),this.setValues(e)}}const Ed=new fr;class Ad extends Sd{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Ed),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?lo(this.offsetNode):wc,t=this.dashScaleNode?lo(this.dashScaleNode):_c,s=this.dashSizeNode?lo(this.dashSizeNode):vc,i=this.gapSizeNode?lo(this.gapSizeNode):Tc;oa.assign(s),aa.assign(i);const r=$h(vl("lineDistance").mul(t));(e?r.add(e):r).mod(oa.add(aa)).greaterThan(oa).discard()}}const Cd=new pr;class Rd extends Sd{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Cd),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?lo(this.opacityNode):Ku;Vo.assign(Zh(To(Zn(lu).mul(.5).add(.5),e),_e))}}class Pd extends mn{static get type(){return"EquirectUVNode"}constructor(e=Jl){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,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 mo(t,s)}}const Fd=to(Pd).setParameterLength(0,1);class Bd extends Oi{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!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 Ni(5,5,5),n=Fd(Jl),o=new Sd;o.colorNode=Al(t,n,0),o.side=1,o.blending=0;const a=new Si(r,o),h=new Vi;h.add(a),t.minFilter===B&&(t.minFilter=P);const l=new Li(1,10,this),u=e.getMRT();return e.setMRT(null),l.update(e,h),e.setMRT(u),t.minFilter=s,t.currentGenerateMipmaps=i,a.geometry.dispose(),a.material.dispose(),this}}const Id=new WeakMap;class Ld extends mn{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Su(null);const t=new Di;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=tn}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(s===w||s===S){if(Id.has(e)){const t=Id.get(e);Od(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new Bd(s.height);i.fromEquirectangularTexture(t,e),Od(i.texture,e.mapping),this._cubeTexture=i.texture,Id.set(e,i.texture),e.addEventListener("dispose",Dd)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Dd(e){const t=e.target;t.removeEventListener("dispose",Dd);const s=Id.get(t);void 0!==s&&(Id.delete(t),s.dispose())}function Od(e,t){t===w?e.mapping=v:t===S&&(e.mapping=T)}const kd=to(Ld).setParameterLength(1);class Ud extends Xc{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=kd(this.envNode)}}class zd extends Xc{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=lo(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Vd{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Gd extends Vd{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(To(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(To(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Vo.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(Bh(i.rgb,i.rgb.mul(r.rgb),ec.mul(tc)));break;case 1:i.rgb.assign(Bh(i.rgb,r.rgb,ec.mul(tc)));break;case 2:i.rgb.addAssign(r.rgb.mul(ec.mul(tc)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const jd=new $s;class Hd extends Sd{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(jd),this.setValues(e)}setupNormal(){return au}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Ud(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new zd(Nc)),t}setupOutgoingLight(){return Vo.rgb}setupLightingModel(){return new Gd}}const Wd=ro((({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))})),$d=ro((e=>e.diffuseColor.mul(1/Math.PI))),qd=ro((({dotNH:e})=>ra.mul(lo(.5)).add(1).mul(lo(1/Math.PI)).mul(e.pow(ra)))),Xd=ro((({lightDirection:e})=>{const t=e.add(tu).normalize(),s=lu.dot(t).clamp(),i=tu.dot(t).clamp(),r=Wd({f0:sa,f90:1,dotVH:i}),n=lo(.25),o=qd({dotNH:s});return r.mul(n).mul(o)}));class Yd extends Gd{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=lu.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul($d({diffuseColor:Vo.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(Xd({lightDirection:e})).mul(ec))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul($d({diffuseColor:Vo}))),i.indirectDiffuse.mulAssign(t)}}const Kd=new mr;class Qd extends Sd{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Kd),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Ud(t):null}setupLightingModel(){return new Yd(!1)}}const Zd=new cr;class Jd extends Sd{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Zd),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Ud(t):null}setupLightingModel(){return new Yd}setupVariants(){const e=(this.shininessNode?lo(this.shininessNode):Xu).max(1e-4);ra.assign(e);const t=this.specularNode||Qu;sa.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const ep=ro((e=>{if(!1===e.geometry.hasAttribute("normal"))return lo(0);const t=au.dFdx().abs().max(au.dFdy().abs());return t.x.max(t.y).max(t.z)})),tp=ro((e=>{const{roughness:t}=e,s=ep();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i})),sp=ro((({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 _a(.5,r.add(n).max(Ua))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),ip=ro((({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:o,dotNL:a})=>{const h=a.mul(bo(e.mul(s),t.mul(i),o).length()),l=o.mul(bo(e.mul(r),t.mul(n),a).length());return _a(.5,h.add(l)).saturate()})).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"}]}),rp=ro((({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"}]}),np=lo(1/Math.PI),op=ro((({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),o=bo(t.mul(i),e.mul(r),n.mul(s)),a=o.dot(o),h=n.div(a);return np.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"}]}),ap=ro((e=>{const{lightDirection:t,f0:s,f90:i,roughness:r,f:n,USE_IRIDESCENCE:o,USE_ANISOTROPY:a}=e,h=e.normalView||lu,l=r.pow2(),u=t.add(tu).normalize(),c=h.dot(t).clamp(),d=h.dot(tu).clamp(),p=h.dot(u).clamp(),m=tu.dot(u).clamp();let g,f,y=Wd({f0:s,f90:i,dotVH:m});if(Kn(o)&&(y=Yo.mix(y,n)),Kn(a)){const e=ea.dot(t),s=ea.dot(tu),i=ea.dot(u),r=ta.dot(t),n=ta.dot(tu),o=ta.dot(u);g=ip({alphaT:Zo,alphaB:l,dotTV:s,dotBV:n,dotTL:e,dotBL:r,dotNV:d,dotNL:c}),f=op({alphaT:Zo,alphaB:l,dotNH:p,dotTH:i,dotBH:o})}else g=sp({alpha:l,dotNL:c,dotNV:d}),f=rp({alpha:l,dotNH:p});return y.mul(g).mul(f)})),hp=ro((({roughness:e,dotNV:t})=>{const s=To(-1,-.0275,-.572,.022),i=To(1,.0425,1.04,-.04),r=e.mul(s).add(i),n=r.x.mul(r.x).min(t.mul(-9.28).exp2()).mul(r.x).add(r.y);return mo(-1.04,1.04).mul(n).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),lp=ro((e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=hp({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))})),up=ro((({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(bo(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"}]}),cp=ro((({roughness:e,dotNH:t})=>{const s=e.pow2(),i=lo(1).div(s),r=t.pow2().oneMinus().max(.0078125);return lo(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"}]}),dp=ro((({dotNV:e,dotNL:t})=>lo(1).div(lo(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),pp=ro((({lightDirection:e})=>{const t=e.add(tu).normalize(),s=lu.dot(e).clamp(),i=lu.dot(tu).clamp(),r=lu.dot(t).clamp(),n=cp({roughness:Xo,dotNH:r}),o=dp({dotNV:i,dotNL:s});return qo.mul(n).mul(o)})),mp=ro((({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=mo(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"}]}),gp=ro((({f:e})=>{const t=e.length();return _h(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),fp=ro((({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(),o=r.div(n),a=s.greaterThan(0).select(o,_h(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return e.cross(t).mul(a)})).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),yp=ro((({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:o,p3:a})=>{const h=n.sub(r).toVar(),l=a.sub(r).toVar(),u=h.cross(l),c=bo().toVar();return ao(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(Eo(h,l,e).transpose()).toVar(),d=u.mul(r.sub(s)).normalize().toVar(),p=u.mul(n.sub(s)).normalize().toVar(),m=u.mul(o.sub(s)).normalize().toVar(),g=u.mul(a.sub(s)).normalize().toVar(),f=bo(0).toVar();f.addAssign(fp({v1:d,v2:p})),f.addAssign(fp({v1:p,v2:m})),f.addAssign(fp({v1:m,v2:g})),f.addAssign(fp({v1:g,v2:d})),c.assign(bo(gp({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"}]}),bp=1/6,xp=e=>xa(bp,xa(e,xa(e,e.negate().add(3)).sub(3)).add(1)),_p=e=>xa(bp,xa(e,xa(e,xa(3,e).sub(6))).add(4)),vp=e=>xa(bp,xa(e,xa(e,xa(-3,e).add(3)).add(3)).add(1)),Tp=e=>xa(bp,Eh(e,3)),wp=e=>xp(e).add(_p(e)),Sp=e=>vp(e).add(Tp(e)),Mp=e=>ya(-1,_p(e).div(xp(e).add(_p(e)))),Np=e=>ya(1,Tp(e).div(vp(e).add(Tp(e)))),Ep=(e,t,s)=>{const i=e.uvNode,r=xa(i,t.zw).add(.5),n=Qa(r),o=eh(r),a=wp(o.x),h=Sp(o.x),l=Mp(o.x),u=Np(o.x),c=Mp(o.y),d=Np(o.y),p=mo(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),m=mo(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),g=mo(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),f=mo(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),y=wp(o.y).mul(ya(a.mul(e.sample(p).level(s)),h.mul(e.sample(m).level(s)))),b=Sp(o.y).mul(ya(a.mul(e.sample(g).level(s)),h.mul(e.sample(f).level(s))));return y.add(b)},Ap=ro((([e,t=lo(3)])=>{const s=mo(e.size(uo(t))),i=mo(e.size(uo(t.add(1)))),r=_a(1,s),n=_a(1,i),o=Ep(e,To(r,s),Qa(t)),a=Ep(e,To(n,i),Za(t));return eh(t).mix(o,a)})),Cp=ro((([e,t,s,i,r])=>{const n=bo(Lh(t.negate(),Ja(e),_a(1,i))),o=bo(lh(r[0].xyz),lh(r[1].xyz),lh(r[2].xyz));return Ja(n).mul(s.mul(o))})).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"}]}),Rp=ro((([e,t])=>e.mul(Ih(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Pp=hd(),Fp=hd(),Bp=ro((([e,t,s],{material:i})=>{const r=(1===i.side?Pp:Fp).sample(e),n=Xa(id.x).mul(Rp(t,s));return Ap(r,n)})),Ip=ro((([e,t,s])=>(ao(s.notEqual(0),(()=>{const i=qa(t).negate().div(s);return Wa(i.negate().mul(e))})),bo(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Lp=ro((([e,t,s,i,r,n,o,a,h,l,u,c,d,p,m])=>{let g,f;if(m){g=To().toVar(),f=bo().toVar();const r=u.sub(1).mul(m.mul(.025)),n=bo(u.sub(r),u,u.add(r));Gc({start:0,end:3},(({i:r})=>{const u=n.element(r),m=Cp(e,t,c,u,a),y=o.add(m),b=l.mul(h.mul(To(y,1))),x=mo(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(mo(x.x,x.y.oneMinus()));const _=Bp(x,s,u);g.element(r).assign(_.element(r)),g.a.addAssign(_.a),f.element(r).assign(i.element(r).mul(Ip(lh(m),d,p).element(r)))})),g.a.divAssign(3)}else{const r=Cp(e,t,c,u,a),n=o.add(r),m=l.mul(h.mul(To(n,1))),y=mo(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(mo(y.x,y.y.oneMinus())),g=Bp(y,s,u),f=i.mul(Ip(lh(r),d,p))}const y=f.rgb.mul(g.rgb),b=e.dot(t).clamp(),x=bo(lp({dotNV:b,specularColor:r,specularF90:n,roughness:s})),_=f.r.add(f.g,f.b).div(3);return To(x.oneMinus().mul(y),g.a.oneMinus().mul(_).oneMinus())})),Dp=Eo(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Op=(e,t)=>e.sub(t).div(e.add(t)).pow2(),kp=ro((({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=Bh(e,t,Dh(0,.03,i)),o=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();ao(o.lessThan(0),(()=>bo(1)));const a=o.sqrt(),h=Op(n,e),l=Wd({f0:h,f90:1,dotVH:s}),u=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=lo(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return bo(1).add(t).div(bo(1).sub(t))})(r.clamp(0,.9999)),m=Op(p,n.toVec3()),g=Wd({f0:m,f90:1,dotVH:a}),f=bo(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,a,2),b=bo(d).add(f),x=l.mul(g).clamp(1e-5,.9999),_=x.sqrt(),v=u.pow2().mul(g).div(bo(1).sub(x)),T=l.add(v).toVar(),w=v.sub(u).toVar();return Gc({start:1,end:2,condition:"<=",name:"m"},(({m:e})=>{w.mulAssign(_);const t=((e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=bo(54856e-17,44201e-17,52481e-17),r=bo(1681e3,1795300,2208400),n=bo(43278e5,93046e5,66121e5),o=lo(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let a=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());return a=bo(a.x.add(o),a.y,a.z).div(1.0685e-7),Dp.mul(a)})(lo(e).mul(y),lo(e).mul(b)).mul(2);T.addAssign(w.mul(t))})),T.max(bo(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"}]}),Up=ro((({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.pow2(),n=zh(s.lessThan(.25),lo(-339.2).mul(r).add(lo(161.4).mul(s)).sub(25.9),lo(-8.48).mul(r).add(lo(14.3).mul(s)).sub(9.95)),o=zh(s.lessThan(.25),lo(44).mul(r).sub(lo(23.7).mul(s)).add(3.26),lo(1.97).mul(r).sub(lo(3.27).mul(s)).add(.72));return zh(s.lessThan(.25),0,lo(.1).mul(s).sub(.025)).add(n.mul(i).add(o).exp()).mul(1/Math.PI).saturate()})),zp=bo(.04),Vp=lo(1);class Gp extends Vd{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}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=bo().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=bo().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=bo().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=bo().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=bo().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=lu.dot(tu).clamp();this.iridescenceFresnel=kp({outsideIOR:lo(1),eta2:Ko,cosTheta1:e,thinFilmThickness:Qo,baseF0:sa}),this.iridescenceF0=up({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=Zl,s=zl.sub(Zl).normalize(),i=uu,r=e.context;r.backdrop=Lp(i,s,jo,Vo,sa,ia,t,Wl,Ul,kl,ha,ua,da,ca,this.dispersion?pa:null),r.backdropAlpha=la,Vo.a.mulAssign(Bh(1,r.backdrop.a,la))}super.start(e)}computeMultiscattering(e,t,s){const i=lu.dot(tu).clamp(),r=hp({roughness:jo,dotNV:i}),n=(this.iridescenceF0?Yo.mix(sa,this.iridescenceF0):sa).mul(r.x).add(s.mul(r.y)),o=r.x.add(r.y).oneMinus(),a=sa.add(sa.oneMinus().mul(.047619)),h=n.mul(a).div(o.mul(a).oneMinus());e.addAssign(n),t.addAssign(h.mul(o))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=lu.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(pp({lightDirection:e}))),!0===this.clearcoat){const s=cu.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(ap({lightDirection:e,f0:zp,f90:Vp,roughness:$o,normalView:cu})))}s.directDiffuse.addAssign(i.mul($d({diffuseColor:Vo.rgb}))),s.directSpecular.addAssign(i.mul(ap({lightDirection:e,f0:sa,f90:1,roughness:jo,iridescence:this.iridescence,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:o}){const a=t.add(s).sub(i),h=t.sub(s).sub(i),l=t.sub(s).add(i),u=t.add(s).add(i),c=lu,d=tu,p=eu.toVar(),m=mp({N:c,V:d,roughness:jo}),g=n.sample(m).toVar(),f=o.sample(m).toVar(),y=Eo(bo(g.x,0,g.y),bo(0,1,0),bo(g.z,0,g.w)).toVar(),b=sa.mul(f.x).add(sa.oneMinus().mul(f.y)).toVar();r.directSpecular.addAssign(e.mul(b).mul(yp({N:c,V:d,P:p,mInv:y,p0:a,p1:h,p2:l,p3:u}))),r.directDiffuse.addAssign(e.mul(Vo).mul(yp({N:c,V:d,P:p,mInv:Eo(1,0,0,0,1,0,0,0,1),p0:a,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;s.indirectDiffuse.addAssign(t.mul($d({diffuseColor:Vo})))}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(s.mul(qo,Up({normal:lu,viewDir:tu,roughness:Xo}))),!0===this.clearcoat){const e=cu.dot(tu).clamp(),t=lp({dotNV:e,specularColor:zp,specularF90:Vp,roughness:$o});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=bo().toVar("singleScattering"),n=bo().toVar("multiScattering"),o=s.mul(1/Math.PI);this.computeMultiscattering(r,n,ia);const a=r.add(n),h=Vo.mul(a.r.max(a.g).max(a.b).oneMinus());i.indirectSpecular.addAssign(t.mul(r)),i.indirectSpecular.addAssign(n.mul(o)),i.indirectDiffuse.addAssign(h.mul(o))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:s}=e.context,i=lu.dot(tu).clamp().add(t),r=jo.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=cu.dot(tu).clamp(),s=Wd({dotVH:e,f0:zp,f90:Vp}),i=t.mul(Wo.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Wo));t.assign(i)}if(!0===this.sheen){const e=qo.r.max(qo.g).max(qo.b).mul(.157).oneMinus(),s=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(s)}}}const jp=lo(1),Hp=lo(-2),Wp=lo(.8),$p=lo(-1),qp=lo(.4),Xp=lo(2),Yp=lo(.305),Kp=lo(3),Qp=lo(.21),Zp=lo(4),Jp=lo(4),em=lo(16),tm=ro((([e])=>{const t=bo(ah(e)).toVar(),s=lo(-1).toVar();return ao(t.x.greaterThan(t.z),(()=>{ao(t.x.greaterThan(t.y),(()=>{s.assign(zh(e.x.greaterThan(0),0,3))})).Else((()=>{s.assign(zh(e.y.greaterThan(0),1,4))}))})).Else((()=>{ao(t.z.greaterThan(t.y),(()=>{s.assign(zh(e.z.greaterThan(0),2,5))})).Else((()=>{s.assign(zh(e.y.greaterThan(0),1,4))}))})),s})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),sm=ro((([e,t])=>{const s=mo().toVar();return ao(t.equal(0),(()=>{s.assign(mo(e.z,e.y).div(ah(e.x)))})).ElseIf(t.equal(1),(()=>{s.assign(mo(e.x.negate(),e.z.negate()).div(ah(e.y)))})).ElseIf(t.equal(2),(()=>{s.assign(mo(e.x.negate(),e.y).div(ah(e.z)))})).ElseIf(t.equal(3),(()=>{s.assign(mo(e.z.negate(),e.y).div(ah(e.x)))})).ElseIf(t.equal(4),(()=>{s.assign(mo(e.x.negate(),e.z).div(ah(e.y)))})).Else((()=>{s.assign(mo(e.x,e.y).div(ah(e.z)))})),xa(.5,s.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),im=ro((([e])=>{const t=lo(0).toVar();return ao(e.greaterThanEqual(Wp),(()=>{t.assign(jp.sub(e).mul($p.sub(Hp)).div(jp.sub(Wp)).add(Hp))})).ElseIf(e.greaterThanEqual(qp),(()=>{t.assign(Wp.sub(e).mul(Xp.sub($p)).div(Wp.sub(qp)).add($p))})).ElseIf(e.greaterThanEqual(Yp),(()=>{t.assign(qp.sub(e).mul(Kp.sub(Xp)).div(qp.sub(Yp)).add(Xp))})).ElseIf(e.greaterThanEqual(Qp),(()=>{t.assign(Yp.sub(e).mul(Zp.sub(Kp)).div(Yp.sub(Qp)).add(Kp))})).Else((()=>{t.assign(lo(-2).mul(Xa(xa(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),rm=ro((([e,t])=>{const s=e.toVar();s.assign(xa(2,s).sub(1));const i=bo(s,1).toVar();return ao(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"}]}),nm=ro((([e,t,s,i,r,n])=>{const o=lo(s),a=bo(t),h=Ih(im(o),Hp,n),l=eh(h),u=Qa(h),c=bo(om(e,a,u,i,r,n)).toVar();return ao(l.notEqual(0),(()=>{const t=bo(om(e,a,u.add(1),i,r,n)).toVar();c.assign(Bh(c,t,l))})),c})),om=ro((([e,t,s,i,r,n])=>{const o=lo(s).toVar(),a=bo(t),h=lo(tm(a)).toVar(),l=lo(_h(Jp.sub(o),0)).toVar();o.assign(_h(o,Jp));const u=lo($a(o)).toVar(),c=mo(sm(a,h).mul(u.sub(2)).add(1)).toVar();return ao(h.greaterThan(2),(()=>{c.y.addAssign(u),h.subAssign(3)})),c.x.addAssign(h.mul(u)),c.x.addAssign(l.mul(xa(3,em))),c.y.addAssign(xa(4,$a(n).sub(u))),c.x.mulAssign(i),c.y.mulAssign(r),e.sample(c).grad(mo(),mo())})),am=ro((({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const h=sh(i),l=s.mul(h).add(r.cross(s).mul(th(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return om(e,l,t,n,o,a)})),hm=ro((({n:e,latitudinal:t,poleAxis:s,outputDirection:i,weights:r,samples:n,dTheta:o,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})=>{const d=bo(zh(t,s,Nh(s,i))).toVar();ao(d.equal(bo(0)),(()=>{d.assign(bo(i.z,0,i.x.negate()))})),d.assign(Ja(d));const p=bo().toVar();return p.addAssign(r.element(0).mul(am({theta:0,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),Gc({start:uo(1),end:e},(({i:e})=>{ao(e.greaterThanEqual(n),(()=>{yl("break").append()}));const t=lo(o.mul(lo(e))).toVar();p.addAssign(r.element(e).mul(am({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),p.addAssign(r.element(e).mul(am({theta:t,axis:d,outputDirection:i,mipInt:a,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})))})),To(p,1)})),lm=[.125,.215,.35,.446,.526,.582],um=20,cm=new Rr(-1,1,1,-1,0,1),dm=new Bi(90,1),pm=new Gs;let mm=null,gm=0,fm=0;const ym=(1+Math.sqrt(5))/2,bm=1/ym,xm=[new _t(-ym,bm,0),new _t(ym,bm,0),new _t(-bm,0,ym),new _t(bm,0,ym),new _t(0,ym,-bm),new _t(0,ym,bm),new _t(-1,1,-1),new _t(1,1,-1),new _t(-1,1,1),new _t(1,1,1)],_m=new _t,vm=new WeakMap,Tm=[3,1,5,0,4,2],wm=rm(Tl(),vl("faceIndex")).normalize(),Sm=bo(wm.x,wm.y,wm.z);class Mm{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=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:o=_m,renderTarget:a=null}=r;if(this._setSize(n),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const n=a||this._allocateTargets();return r.renderTarget=n,this.fromSceneAsync(e,t,s,i,r),n}mm=this._renderer.getRenderTarget(),gm=this._renderer.getActiveCubeFace(),fm=this._renderer.getActiveMipmapLevel();const h=a||this._allocateTargets();return h.depthBuffer=!0,this._sceneToCubeUV(e,s,i,h,o),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!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,s,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTargets();return this.fromEquirectangularAsync(e,s),s}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTargets();return this.fromCubemapAsync(e,t),s}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Cm(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Rm(),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===v||e.mapping===T?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._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(mm,gm,fm),e.scissorTest=!1,Em(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),mm=this._renderer.getRenderTarget(),gm=this._renderer.getActiveCubeFace(),fm=this._renderer.getActiveMipmapLevel();const s=t||this._allocateTargets();return this._textureToCubeUV(e,s),this._applyPMREM(s),this._cleanup(s),s}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,s={magFilter:P,minFilter:P,generateMipmaps:!1,type:V,format:H,colorSpace:ve},i=Nm(e,t,s);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=Nm(e,t,s);const{_lodMax:i}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas,lodMeshes:this._lodMeshes}=function(e){const t=[],s=[],i=[],r=[];let n=e;const o=e-4+1+lm.length;for(let a=0;a<o;a++){const o=Math.pow(2,n);s.push(o);let h=1/o;a>e-4?h=lm[a-e+4-1]:0===a&&(h=0),i.push(h);const l=1/(o-2),u=-l,c=1+l,d=[u,u,c,u,c,c,u,u,c,c,u,c],p=6,m=6,g=3,f=2,y=1,b=new Float32Array(g*m*p),x=new Float32Array(f*m*p),_=new Float32Array(y*m*p);for(let e=0;e<p;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=Tm[e];b.set(i,g*m*r),x.set(d,f*m*r);const n=[r,r,r,r,r,r];_.set(n,y*m*r)}const v=new di;v.setAttribute("position",new ei(b,g)),v.setAttribute("uv",new ei(x,f)),v.setAttribute("faceIndex",new ei(_,y)),t.push(v),r.push(new Si(v,null)),n>4&&n--}return{lodPlanes:t,sizeLods:s,sigmas:i,lodMeshes:r}}(i)),this._blurMaterial=function(e,t,s){const i=Il(new Array(um).fill(0)),r=Oo(new _t(0,1,0)),n=Oo(0),o=lo(um),a=Oo(0),h=Oo(1),l=Al(null),u=Oo(0),c=lo(1/t),d=lo(1/s),p=lo(e),m={n:o,latitudinal:a,weights:i,poleAxis:r,outputDirection:Sm,dTheta:n,samples:h,envMap:l,mipInt:u,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=Am("blur");return g.fragmentNode=hm({...m,latitudinal:a.equal(1)}),vm.set(g,m),g}(i,e,t)}return i}async _compileMaterial(e){const t=new Si(this._lodPlanes[0],e);await this._renderer.compile(t,cm)}_sceneToCubeUV(e,t,s,i,r){const n=dm;n.near=t,n.far=s;const o=[1,1,1,1,-1,1],a=[1,-1,1,-1,1,-1],h=this._renderer,l=h.autoClear;h.getClearColor(pm),h.autoClear=!1;let u=this._backgroundBox;if(null===u){const e=new $s({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1});u=new Si(new Ni,e)}let c=!1;const d=e.background;d?d.isColor&&(u.material.color.copy(d),e.background=null,c=!0):(u.material.color.copy(pm),c=!0),h.setRenderTarget(i),h.clear(),c&&h.render(u,n);for(let t=0;t<6;t++){const s=t%3;0===s?(n.up.set(0,o[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x+a[t],r.y,r.z)):1===s?(n.up.set(0,0,o[t]),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y+a[t],r.z)):(n.up.set(0,o[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y,r.z+a[t]));const l=this._cubeSize;Em(i,s*l,t>2?l:0,l,l),h.render(e,n)}h.autoClear=l,e.background=d}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===v||e.mapping===T;i?null===this._cubemapMaterial&&(this._cubemapMaterial=Cm(e)):null===this._equirectMaterial&&(this._equirectMaterial=Rm(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const o=this._cubeSize;Em(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(n,cm)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let t=1;t<i;t++){const s=Math.sqrt(this._sigmas[t]*this._sigmas[t]-this._sigmas[t-1]*this._sigmas[t-1]),r=xm[(i-t-1)%xm.length];this._blur(e,t-1,t,s,r)}t.autoClear=s}_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,o){const a=this._renderer,h=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&console.error("blur direction must be either latitudinal or longitudinal!");const l=this._lodMeshes[i];l.material=h;const u=vm.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):um;m>um&&console.warn(`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<um;++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,o&&(u.poleAxis.value=o);const{_lodMax:y}=this;u.dTheta.value=d,u.mipInt.value=y-s;const b=this._sizeLods[i];Em(t,3*b*(i>y-4?i-y+4:0),4*(this._cubeSize-b),3*b,2*b),a.setRenderTarget(t),a.render(l,cm)}}function Nm(e,t,s){const i=new ft(e,t,s);return i.texture.mapping=306,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function Em(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function Am(e){const t=new Sd;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function Cm(e){const t=Am("cubemap");return t.fragmentNode=Su(e,Sm),t}function Rm(e){const t=Am("equirect");return t.fragmentNode=Al(e,Fd(Sm),0),t}const Pm=new WeakMap;function Fm(e,t,s){const i=function(e){let t=Pm.get(e);void 0===t&&(t=new WeakMap,Pm.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 Bm extends mn{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 mt;i.isRenderTargetTexture=!0,this._texture=Al(i),this._width=Oo(0),this._height=Oo(0),this._maxMip=Oo(0),this.updateBeforeType=tn}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:Fm(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Mm(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=bu.mul(bo(t.x,t.y.negate(),t.z));let s=this.levelNode;return null===s&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),nm(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const Im=to(Bm).setParameterLength(1,3),Lm=new WeakMap;class Dm extends Xc{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 e=s.isTextureNode?s.value:t[s.property];let i=Lm.get(e);void 0===i&&(i=Im(e),Lm.set(e,i)),s=i}const i=!0===t.useAnisotropy||t.anisotropy>0?Du:lu,r=s.context(Om(jo,i)).mul(yu),n=s.context(km(uu)).mul(Math.PI).mul(yu),o=cl(r),a=cl(n);e.context.radiance.addAssign(o),e.context.iblIrradiance.addAssign(a);const h=e.context.lightingModel.clearcoatRadiance;if(h){const e=s.context(Om($o,cu)).mul(yu),t=cl(e);h.addAssign(t)}}}const Om=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=tu.negate().reflect(t),s=e.mul(e).mix(s,t).normalize(),s=s.transformDirection(Ul)),s),getTextureLevel:()=>e}},km=e=>({getUV:()=>e,getTextureLevel:()=>lo(1)}),Um=new lr;class zm extends Sd{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(Um),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Dm(t):null}setupLightingModel(){return new Gp}setupSpecular(){const e=Bh(bo(.04),Vo.rgb,Ho);sa.assign(e),ia.assign(1)}setupVariants(){const e=this.metalnessNode?lo(this.metalnessNode):ic;Ho.assign(e);let t=this.roughnessNode?lo(this.roughnessNode):sc;t=tp({roughness:t}),jo.assign(t),this.setupSpecular(),Vo.assign(To(Vo.rgb.mul(e.oneMinus()),Vo.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Vm=new ur;class Gm extends zm{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(Vm),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?lo(this.iorNode):yc;ha.assign(e),sa.assign(Bh(xh(Ah(ha.sub(1).div(ha.add(1))).mul(Ju),bo(1)).mul(Zu),Vo.rgb,Ho)),ia.assign(Bh(Zu,1,Ho))}setupLightingModel(){return new Gp(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?lo(this.clearcoatNode):nc,t=this.clearcoatRoughnessNode?lo(this.clearcoatRoughnessNode):oc;Wo.assign(e),$o.assign(tp({roughness:t}))}if(this.useSheen){const e=this.sheenNode?bo(this.sheenNode):lc,t=this.sheenRoughnessNode?lo(this.sheenRoughnessNode):uc;qo.assign(e),Xo.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?lo(this.iridescenceNode):dc,t=this.iridescenceIORNode?lo(this.iridescenceIORNode):pc,s=this.iridescenceThicknessNode?lo(this.iridescenceThicknessNode):mc;Yo.assign(e),Ko.assign(t),Qo.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?mo(this.anisotropyNode):cc).toVar();Jo.assign(e.length()),ao(Jo.equal(0),(()=>{e.assign(mo(1,0))})).Else((()=>{e.divAssign(mo(Jo)),Jo.assign(Jo.saturate())})),Zo.assign(Jo.pow2().mix(jo.pow2(),1)),ea.assign(Lu[0].mul(e.x).add(Lu[1].mul(e.y))),ta.assign(Lu[1].mul(e.x).sub(Lu[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?lo(this.transmissionNode):gc,t=this.thicknessNode?lo(this.thicknessNode):fc,s=this.attenuationDistanceNode?lo(this.attenuationDistanceNode):bc,i=this.attenuationColorNode?bo(this.attenuationColorNode):xc;if(la.assign(e),ua.assign(t),ca.assign(s),da.assign(i),this.useDispersion){const e=this.dispersionNode?lo(this.dispersionNode):Mc;pa.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?bo(this.clearcoatNormalNode):ac}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),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.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 jm=ro((({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=mo(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=Ru("gradientMap","texture").context({getUV:()=>r});return bo(e.r)}{const e=r.fwidth().mul(.5);return Bh(bo(.7),bo(1),Dh(lo(.7).sub(e.x),lo(.7).add(e.x),r.x))}}));class Hm extends Vd{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const r=jm({normal:ru,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(r.mul($d({diffuseColor:Vo.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul($d({diffuseColor:Vo}))),i.indirectDiffuse.mulAssign(t)}}const Wm=new dr;class $m extends Sd{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Wm),this.setValues(e)}setupLightingModel(){return new Hm}}class qm extends mn{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=bo(tu.z,0,tu.x.negate()).normalize(),t=tu.cross(e);return mo(e.dot(lu),t.dot(lu)).mul(.495).add(.5)}}const Xm=so(qm),Ym=new gr;class Km extends Sd{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Ym),this.setValues(e)}setupVariants(e){const t=Xm;let s;s=e.material.matcap?Ru("matcap","texture").context({getUV:()=>t}):bo(Bh(.2,.8,t.y)),Vo.rgb.mulAssign(s.rgb)}}class Qm extends mn{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 No(e,i,i.negate(),e).mul(s)}{const e=t,i=Ao(To(1,0,0,0),To(0,sh(e.x),th(e.x).negate(),0),To(0,th(e.x),sh(e.x),0),To(0,0,0,1)),r=Ao(To(sh(e.y),0,th(e.y),0),To(0,1,0,0),To(th(e.y).negate(),0,sh(e.y),0),To(0,0,0,1)),n=Ao(To(sh(e.z),th(e.z).negate(),0,0),To(th(e.z),sh(e.z),0,0),To(0,0,1,0),To(0,0,0,1));return i.mul(r).mul(n).mul(To(s,1)).xyz}}}const Zm=to(Qm).setParameterLength(2),Jm=new Wi;class eg extends Sd{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(Jm),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,i=this.sizeAttenuation,{positionNode:r,rotationNode:n,scaleNode:o}=this,a=ql.mul(bo(r||0));let h=mo(Wl[0].xyz.length(),Wl[1].xyz.length());if(null!==o&&(h=h.mul(mo(o))),!1===i)if(s.isPerspectiveCamera)h=h.mul(a.z.negate());else{const e=lo(2).div(kl.element(1).element(1));h=h.mul(e.mul(2))}let l=Yl.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,s)=>Zn(new el(e,t,s)))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(h);const u=lo(n||hc),c=Zm(l,u);return To(a.xy.add(c),a.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 tg=new sr;class sg extends eg{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(tg),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return ql.mul(bo(e||Kl)).xyz}setupVertex(e){const t=super.setupVertex(e);if(!0!==e.material.isNodeMaterial)return t;const{rotationNode:s,scaleNode:i,sizeNode:r}=this,n=Yl.xy.toVar(),o=nd.z.div(nd.w);if(s&&s.isNode){const e=lo(s);n.assign(Zm(n,e))}let a=null!==r?mo(r):Sc;return!0===this.sizeAttenuation&&(a=a.mul(a.div(eu.z.negate()))),i&&i.isNode&&(a=a.mul(mo(i))),n.mulAssign(a.mul(2)),n.assign(n.div(nd.z)),n.y.assign(n.y.mul(o)),n.assign(n.mul(t.w)),t.addAssign(To(n,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class ig extends Vd{constructor(){super(),this.shadowNode=lo(1).toVar("shadowMask")}direct({lightNode:e}){this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Vo.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Vo.rgb)}}const rg=new hr;class ng extends Sd{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(rg),this.setValues(e)}setupLightingModel(){return new ig}}Uo("vec3"),Uo("vec3"),Uo("vec3");class og{constructor(e,t){this.nodes=e,this.info=t,this._context=self,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,null!==this._animationLoop&&this._animationLoop(t,s)};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 ag{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;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.weakMap;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.weakMap;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 hg=0;class lg{constructor(e,t,s,i,r,n,o,a,h,l){this.id=hg++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=r,this.scene=n,this.camera=o,this.lightsNode=a,this.context=h,this.geometry=i.geometry,this.version=r.version,this.drawRange=null,this.attributes=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.material.addEventListener("dispose",this.onMaterialDispose)}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)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set;for(const r of e){const e=r.node&&r.node.attribute?r.node.attribute:t.getAttribute(r.name);if(void 0===e)continue;s.push(e);const n=e.isInterleavedBufferAttribute?e.data:e;i.add(n)}return this.attributes=s,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}),o=this.getIndex(),a=null!==o,h=s.isInstancedBufferGeometry?s.instanceCount:e.count>1?e.count:1;if(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;a?p=o.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}=this;let s=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 i=t[e];let r;if(null!==i){const e=typeof i;"number"===e?r=0!==i?"1":"0":"object"===e?(r="{",i.isTexture&&(r+=i.mapping),r+="}"):r=String(i)}else r=String(i);s+=r+","}return s+=this.clippingContextCacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),s+=e.receiveShadow+",",Gr(s)}get needsGeometryUpdate(){return this.geometry.id!==this.object.geometry.id}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=Hr(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Hr(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const ug=[];class cg{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,o,a){const h=this.getChainMap(a);ug[0]=e,ug[1]=t,ug[2]=n,ug[3]=r;let l=h.get(ug);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,o,a),h.set(ug,l)):(l.updateClipping(o),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,o,a)):l.version=t.version)),ug.length=0,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new ag)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,o,a,h,l,u){const c=this.getChainMap(u),d=new lg(e,t,s,i,r,n,o,a,h,l);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.delete(d),this.nodes.delete(d),c.delete(d.getChainArray())},d}}class dg{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 pg=1,mg=2,gg=3,fg=4,yg=16;class bg extends dg{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===pg?this.backend.createAttribute(e):t===mg?this.backend.createIndexAttribute(e):t===gg?this.backend.createStorageAttribute(e):t===fg&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version<t.version||t.usage===Ie)&&(this.backend.updateAttribute(e),s.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function xg(e){return null!==e.index?e.index.version:e.attributes.position.version}function _g(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(Ze(t)?si:ti)(t,1);return r.version=xg(e),r}class vg extends dg{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}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)};t.addEventListener("dispose",s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,gg):this.updateAttribute(e,pg);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,mg);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,fg)}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}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=_g(t),e.set(t,s)):s.version!==xg(t)&&(this.attributes.delete(s),s=_g(t),e.set(t,s)),i=s}return i}}class Tg{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):console.error("THREE.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 wg{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Sg extends wg{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class Mg extends wg{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Ng=0;class Eg{constructor(e,t,s,i=null,r=null){this.id=Ng++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=r,this.usedTimes=0}}class Ag extends dg{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 o=this.programs.compute.get(n.computeShader);void 0===o&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),o=new Eg(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,o),s.createProgram(o));const a=this._getComputeCacheKey(e,o);let h=this.caches.get(a);void 0===h&&(r&&0===r.usedTimes&&this._releasePipeline(r),h=this._getComputePipeline(e,o,a,t)),h.usedTimes++,o.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(),o=e.material?e.material.name:"";let a=this.programs.vertex.get(n.vertexShader);void 0===a&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),a=new Eg(n.vertexShader,"vertex",o),this.programs.vertex.set(n.vertexShader,a),s.createProgram(a));let h=this.programs.fragment.get(n.fragmentShader);void 0===h&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),h=new Eg(n.fragmentShader,"fragment",o),this.programs.fragment.set(n.fragmentShader,h),s.createProgram(h));const l=this._getRenderCacheKey(e,a,h);let u=this.caches.get(l);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,a,h,l,t)):e.pipeline=u,u.usedTimes++,a.usedTimes++,h.usedTimes++,i.pipeline=u}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 Mg(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 Sg(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 Cg extends dg{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))}_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.isStorageBuffer){const e=t.attribute,s=e.isIndirectStorageBufferAttribute?fg:gg;this.attributes.update(e,s)}}_update(e,t){const{backend:s}=this;let i=!1,r=!0,n=0,o=0;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,s=e.isIndirectStorageBufferAttribute?fg:gg;this.attributes.update(e,s)}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){const e=this.textures.get(t.texture);t.needsBindingsUpdate(e.generation)&&(i=!0);const a=t.update(),h=t.texture;a&&this.textures.updateTexture(h);const l=s.get(h);if(void 0!==l.externalTexture||e.isDefaultTexture?r=!1:(n=10*n+h.id,o+=h.version),!0===s.isWebGPUBackend&&void 0===l.texture&&void 0===l.externalTexture&&(console.error("Bindings._update: binding should be available:",t,a,h,t.textureNode.value,i),this.textures.updateTexture(h),i=!0),!0===h.isStorageTexture){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)}}}!0===i&&this.backend.updateBindings(e,t,r?n:0,o)}}function Rg(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function Pg(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 Fg(e){return(e.transmission>0||e.transmissionNode)&&2===e.side&&!1===e.forceSinglePass}class Bg{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,o){let a=this.renderItems[this.renderItemsIndex];return void 0===a?(a={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:r,group:n,clippingContext:o},this.renderItems[this.renderItemsIndex]=a):(a.id=e.id,a.object=e,a.geometry=t,a.material=s,a.groupOrder=i,a.renderOrder=e.renderOrder,a.z=r,a.group=n,a.clippingContext=o),this.renderItemsIndex++,a}push(e,t,s,i,r,n,o){const a=this.getNextRenderItem(e,t,s,i,r,n,o);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===s.transparent||s.transmission>0?(Fg(s)&&this.transparentDoublePass.push(a),this.transparent.push(a)):this.opaque.push(a)}unshift(e,t,s,i,r,n,o){const a=this.getNextRenderItem(e,t,s,i,r,n,o);!0===s.transparent||s.transmission>0?(Fg(s)&&this.transparentDoublePass.unshift(a),this.transparent.unshift(a)):this.opaque.unshift(a)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||Rg),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Pg),this.transparent.length>1&&this.transparent.sort(t||Pg)}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 Ig=[];class Lg{constructor(e){this.lighting=e,this.lists=new ag}get(e,t){const s=this.lists;Ig[0]=e,Ig[1]=t;let i=s.get(Ig);return void 0===i&&(i=new Bg(this.lighting,e,t),s.set(Ig,i)),Ig.length=0,i}dispose(){this.lists=new ag}}let Dg=0;class Og{constructor(){this.id=Dg++,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 gt,this.scissor=!1,this.scissorValue=new gt,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.isRenderContext=!0}getCacheKey(){return kg(this)}}function kg(e){const{textures:t,activeCubeFace:s}=e,i=[s];for(const e of t)i.push(e.id);return jr(i)}const Ug=[],zg=new Vi,Vg=new Ci;class Gg{constructor(){this.chainMaps={}}get(e,t,s=null){let i;if(Ug[0]=e,Ug[1]=t,null===s)i="default";else{const e=s.texture.format;i=`${s.textures.length}:${e}:${s.samples}:${s.depthBuffer}:${s.stencilBuffer}`}const r=this._getChainMap(i);let n=r.get(Ug);return void 0===n&&(n=new Og,r.set(Ug,n)),Ug.length=0,null!==s&&(n.sampleCount=0===s.samples?1:s.samples),n}getForClear(e=null){return this.get(zg,Vg,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new ag)}dispose(){this.chainMaps={}}}const jg=new _t;class Hg extends dg{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,o=this.getSize(n[0]),a=o.width>>t,h=o.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 rr,l.format=e.stencilBuffer?$:W,l.type=e.stencilBuffer?G:U,l.image.width=a,l.image.height=h,r[t]=l),s.width===o.width&&o.height===s.height||(c=!0,l&&(l.needsUpdate=!0,l.image.width=a,l.image.height=h)),s.width=o.width,s.height=o.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)}if(!0!==s.initialized){s.initialized=!0;const t=()=>{e.removeEventListener("dispose",t);for(let e=0;e<n.length;e++)this._destroyTexture(n[e]);l&&this._destroyTexture(l),this.delete(e)};e.addEventListener("dispose",t)}}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.destroySampler(e),r.destroyTexture(e)),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:I}const{width:n,height:o,depth:a}=this.getSize(e);if(t.width=n,t.height=o,t.depth=a,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,o):1,i||!0===e.isStorageTexture)r.createSampler(e),r.createTexture(e,t),s.generation=e.version;else{if(!0!==s.initialized&&r.createSampler(e),e.version>0){const i=e.image;if(void 0===i)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)console.warn("THREE.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),t.needsMipmaps&&0===e.mipmaps.length&&r.generateMipmaps(e)}}else r.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version}if(!0!==s.initialized){s.initialized=!0,s.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}s.version=e.version}getSize(e,t=jg){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),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.isCompressedTexture?e.mipmaps?e.mipmaps.length:1:Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return this.isEnvironmentTexture(e)||!0===e.isCompressedTexture||e.generateMipmaps}isEnvironmentTexture(e){const t=e.mapping;return t===w||t===S||t===v||t===T}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class Wg extends Gs{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 $g extends ko{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class qg extends cn{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const s=new Qn(t);return this._currentCond=zh(e,s),this.add(this._currentCond)}ElseIf(e,t){const s=new Qn(t),i=zh(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new Qn(e),this}build(e,...t){const s=oo();no(this);for(const t of this.nodes)t.build(e,"void");return no(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("THREE.TSL: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("THREE.TSL: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const Xg=to(qg).setParameterLength(0,1);new Qi,new _t,new _t,new _t,new Kt,new _t(0,0,-1),new gt,new _t,new _t,new gt,new Ye;const Yg=new ft;sd.flipX(),Yg.depthTexture=new rr(1,1);const Kg=new Rr(-1,1,1,-1,0,1);class Qg extends di{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 Zg=new Qg;class Jg extends Si{constructor(e=null){super(Zg,e),this.camera=Kg,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,Kg)}render(e){e.render(this,Kg)}}const ef=new os,tf=new Kt;class sf extends cn{static get type(){return"SceneNode"}constructor(e=sf.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=null!==this.scene?this.scene:e.scene;let i;return t===sf.BACKGROUND_BLURRINESS?i=Eu("backgroundBlurriness","float",s):t===sf.BACKGROUND_INTENSITY?i=Eu("backgroundIntensity","float",s):t===sf.BACKGROUND_ROTATION?i=Oo("mat4").label("backgroundRotation").setGroup(Io).onRenderUpdate((()=>{const e=s.background;return null!==e&&e.isTexture&&300!==e.mapping?(ef.copy(s.backgroundRotation),ef.x*=-1,ef.y*=-1,ef.z*=-1,tf.makeRotationFromEuler(ef)):tf.identity(),tf})):console.error("THREE.SceneNode: Unknown scope:",t),i}}sf.BACKGROUND_BLURRINESS="backgroundBlurriness",sf.BACKGROUND_INTENSITY="backgroundIntensity",sf.BACKGROUND_ROTATION="backgroundRotation";const rf=so(sf,sf.BACKGROUND_BLURRINESS),nf=so(sf,sf.BACKGROUND_INTENSITY),of=so(sf,sf.BACKGROUND_ROTATION);ro((({texture:e,uv:t})=>{const s=1e-4,i=bo().toVar();return ao(t.x.lessThan(s),(()=>{i.assign(bo(1,0,0))})).ElseIf(t.y.lessThan(s),(()=>{i.assign(bo(0,1,0))})).ElseIf(t.z.lessThan(s),(()=>{i.assign(bo(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{i.assign(bo(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{i.assign(bo(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{i.assign(bo(0,0,-1))})).Else((()=>{const s=.01,r=e.sample(t.add(bo(-.01,0,0))).r.sub(e.sample(t.add(bo(s,0,0))).r),n=e.sample(t.add(bo(0,-.01,0))).r.sub(e.sample(t.add(bo(0,s,0))).r),o=e.sample(t.add(bo(0,0,-.01))).r.sub(e.sample(t.add(bo(0,0,s))).r);i.assign(bo(r,n,o))})),i.normalize()}));const af=new Ye;class hf extends El{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class lf extends hf{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class uf extends mn{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 rr;r.isRenderTargetTexture=!0,r.name="depth";const n=new ft(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:V,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Oo(0),this._cameraFar=Oo(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=en}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}isGlobal(){return!0}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=Zn(new lf(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=Zn(new lf(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=gd(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=pd(r,s,i)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,!0===e.backend.isWebGLBackend&&(this.renderTarget.samples=0),this.renderTarget.texture.type=e.getColorBufferType(),this.scope===uf.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),af.set(n.width,n.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(af)),this._pixelRatio=r,this.setSize(af.width,af.height);const o=t.getRenderTarget(),a=t.getMRT(),h=i.layers.mask;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);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(o),t.setMRT(a),i.layers.mask=h}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio*this._resolution,i=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}uf.COLOR="color",uf.DEPTH="depth";const cf=ro((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),df=ro((([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"}]}),pf=ro((([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"}]}),mf=ro((([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)})),gf=ro((([e,t])=>{const s=Eo(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Eo(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=mf(e),(e=i.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),ff=Eo(bo(1.6605,-.1246,-.0182),bo(-.5876,1.1329,-.1006),bo(-.0728,-.0083,1.1187)),yf=Eo(bo(.6274,.0691,.0164),bo(.3293,.9195,.088),bo(.0433,.0113,.8956)),bf=ro((([e])=>{const t=bo(e).toVar(),s=bo(t.mul(t)).toVar(),i=bo(s.mul(s)).toVar();return lo(15.5).mul(i.mul(s)).sub(xa(40.14,i.mul(t))).add(xa(31.96,i).sub(xa(6.868,s.mul(t))).add(xa(.4298,s).add(xa(.1191,t).sub(.00232))))})),xf=ro((([e,t])=>{const s=bo(e).toVar(),i=Eo(bo(.856627153315983,.137318972929847,.11189821299995),bo(.0951212405381588,.761241990602591,.0767994186031903),bo(.0482516061458583,.101439036467562,.811302368396859)),r=Eo(bo(1.1271005818144368,-.1413297634984383,-.14132976349843826),bo(-.11060664309660323,1.157823702216272,-.11060664309660294),bo(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=lo(-12.47393),o=lo(4.026069);return s.mulAssign(t),s.assign(yf.mul(s)),s.assign(i.mul(s)),s.assign(_h(s,1e-10)),s.assign(Xa(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(Ih(s,0,1)),s.assign(bf(s)),s.assign(r.mul(s)),s.assign(Eh(_h(bo(0),s),bo(2.2))),s.assign(ff.mul(s)),s.assign(Ih(s,0,1)),s})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),_f=ro((([e,t])=>{const s=lo(.76),i=lo(.15);e=e.mul(t);const r=xh(e.r,xh(e.g,e.b)),n=zh(r.lessThan(.08),r.sub(xa(6.25,r.mul(r))),.04);e.subAssign(n);const o=_h(e.r,_h(e.g,e.b));ao(o.lessThan(s),(()=>e));const a=ba(1,s),h=ba(1,a.mul(a).div(o.add(a.sub(s))));e.mulAssign(h.div(o));const l=ba(1,_a(1,i.mul(o.sub(h)).add(1)));return Bh(e,bo(h),l)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class vf extends cn{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.code=e,this.includes=t,this.language=s}isGlobal(){return!0}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 Tf extends vf{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}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 o=e.getPropertyName(n),a=this.getNodeFunction(e).getCode(o);return n.code=a+"\n","property"===t?o:e.format(`${o}()`,r,t)}}function wf(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||eu.z).negate()}const Sf=ro((([e,t],s)=>{const i=wf(s);return Dh(e,t,i)})),Mf=ro((([e],t)=>{const s=wf(t);return e.mul(e,s,s).negate().exp().oneMinus()})),Nf=ro((([e,t])=>To(t.toFloat().mix(na.rgb,e.toVec3()),na.a)));to(class extends cn{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 Ef extends mn{static get type(){return"AtomicFunctionNode"}constructor(e,t,s){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=this.method,s=this.getNodeType(e),i=this.getInputType(e),r=this.pointerNode,n=this.valueNode,o=[];o.push(`&${r.build(e,i)}`),null!==n&&o.push(n.build(e,i));const a=`${e.getMethod(t,s)}( ${o.join(", ")} )`;return null!==n&&e.addLineFlowCode(a,this),a}}let Af;function Cf(e){Af=Af||new WeakMap;let t=Af.get(e);return void 0===t&&Af.set(e,t={}),t}function Rf(e){const t=Cf(e);return t.shadowMatrix||(t.shadowMatrix=Oo("mat4").setGroup(Io).onRenderUpdate((()=>(!0!==e.castShadow&&e.shadow.updateMatrices(e),e.shadow.matrix))))}function Pf(e){const t=Cf(e);return t.position||(t.position=Oo(new _t).setGroup(Io).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld))))}function Ff(e){const t=Cf(e);return t.viewPosition||(t.viewPosition=Oo(new _t).setGroup(Io).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new _t,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}Ef.ATOMIC_LOAD="atomicLoad",Ef.ATOMIC_STORE="atomicStore",Ef.ATOMIC_ADD="atomicAdd",Ef.ATOMIC_SUB="atomicSub",Ef.ATOMIC_MAX="atomicMax",Ef.ATOMIC_MIN="atomicMin",Ef.ATOMIC_AND="atomicAnd",Ef.ATOMIC_OR="atomicOr",Ef.ATOMIC_XOR="atomicXor",to(Ef);const Bf=e=>Ul.transformDirection(Pf(e).sub(function(e){const t=Cf(e);return t.targetPosition||(t.targetPosition=Oo(new _t).setGroup(Io).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld))))}(e))),If=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},Lf=new WeakMap;class Df extends cn{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=bo().toVar(),this.totalSpecularNode=bo().toVar(),this.outgoingLightNode=bo().toVar(),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=[],t=this._lights;for(let s=0;s<t.length;s++)e.push(t[s].id);return jr(e)}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getSelf().getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getDataFromNode(this);for(const s of t.nodes)s.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(Zn(e));else{let i=null;if(null!==s&&(i=If(e.id,s)),null===i){const s=r.getLightNodeClass(e.constructor);if(null===s){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;Lf.has(e)?i=Lf.get(e):(i=Zn(new s(e)),Lf.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.getDataFromNode(this);if(r){const{totalDiffuseNode:t,totalSpecularNode:o}=this;i.outgoingLight=s;const a=e.addStack();n.nodes=a.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=bo(null!==l?l.mix(m,h):h),i.material.transparent=!0),t.assign(m),o.assign(c.add(p)),s.assign(t.add(o)),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 Of extends cn{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=tn,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){kf.assign(t.shadowPositionNode||e.shadowPositionWorld||Zl)}dispose(){this.updateBeforeType=Jr}}const kf=Uo("vec3","shadowPositionWorld");function Uf(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 Gs),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 zf=new WeakMap,Vf=ro((([e,t,s])=>{let i=Zl.sub(e).length();return i=i.sub(t).div(s.sub(t)),i=i.saturate(),i})),Gf=e=>{let t=zf.get(e);if(void 0===t){const s=e.isPointLight?(e=>{const t=e.shadow.camera,s=Eu("near","float",t).setGroup(Io),i=Eu("far","float",t).setGroup(Io),r=jl(e);return Vf(r,s,i)})(e):null;t=new Sd,t.colorNode=To(0,0,0,1),t.depthNode=s,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,zf.set(e,t)}return t},jf=ro((({depthTexture:e,shadowCoord:t})=>Al(e,t.xy).compare(t.z))),Hf=ro((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>Al(e,t).compare(s),r=Eu("mapSize","vec2",s).setGroup(Io),n=Eu("radius","float",s).setGroup(Io),o=mo(1).div(r),a=o.x.negate().mul(n),h=o.y.negate().mul(n),l=o.x.mul(n),u=o.y.mul(n),c=a.div(2),d=h.div(2),p=l.div(2),m=u.div(2);return ya(i(t.xy.add(mo(a,h)),t.z),i(t.xy.add(mo(0,h)),t.z),i(t.xy.add(mo(l,h)),t.z),i(t.xy.add(mo(c,d)),t.z),i(t.xy.add(mo(0,d)),t.z),i(t.xy.add(mo(p,d)),t.z),i(t.xy.add(mo(a,0)),t.z),i(t.xy.add(mo(c,0)),t.z),i(t.xy,t.z),i(t.xy.add(mo(p,0)),t.z),i(t.xy.add(mo(l,0)),t.z),i(t.xy.add(mo(c,m)),t.z),i(t.xy.add(mo(0,m)),t.z),i(t.xy.add(mo(p,m)),t.z),i(t.xy.add(mo(a,u)),t.z),i(t.xy.add(mo(0,u)),t.z),i(t.xy.add(mo(l,u)),t.z)).mul(1/17)})),Wf=ro((({depthTexture:e,shadowCoord:t,shadow:s})=>{const i=(t,s)=>Al(e,t).compare(s),r=Eu("mapSize","vec2",s).setGroup(Io),n=mo(1).div(r),o=n.x,a=n.y,h=t.xy,l=eh(h.mul(r).add(.5));return h.subAssign(l.mul(n)),ya(i(h,t.z),i(h.add(mo(o,0)),t.z),i(h.add(mo(0,a)),t.z),i(h.add(n),t.z),Bh(i(h.add(mo(o.negate(),0)),t.z),i(h.add(mo(o.mul(2),0)),t.z),l.x),Bh(i(h.add(mo(o.negate(),a)),t.z),i(h.add(mo(o.mul(2),a)),t.z),l.x),Bh(i(h.add(mo(0,a.negate())),t.z),i(h.add(mo(0,a.mul(2))),t.z),l.y),Bh(i(h.add(mo(o,a.negate())),t.z),i(h.add(mo(o,a.mul(2))),t.z),l.y),Bh(Bh(i(h.add(mo(o.negate(),a.negate())),t.z),i(h.add(mo(o.mul(2),a.negate())),t.z),l.x),Bh(i(h.add(mo(o.negate(),a.mul(2))),t.z),i(h.add(mo(o.mul(2),a.mul(2))),t.z),l.x),l.y)).mul(1/9)})),$f=ro((({depthTexture:e,shadowCoord:t})=>{const s=lo(1).toVar(),i=Al(e).sample(t.xy).rg,r=vh(t.z,i.x);return ao(r.notEqual(lo(1)),(()=>{const e=t.z.sub(i.x),n=_h(0,i.y.mul(i.y));let o=n.div(n.add(e.mul(e)));o=Ih(ba(o,.3).div(.95-.3)),s.assign(Ih(_h(r,o)))})),s})),qf=ro((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=lo(0).toVar(),n=lo(0).toVar(),o=e.lessThanEqual(lo(1)).select(lo(0),lo(2).div(e.sub(1))),a=e.lessThanEqual(lo(1)).select(lo(0),lo(-1));Gc({start:uo(0),end:uo(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(lo(e).mul(o)),l=i.sample(ya(rd.xy,mo(0,h).mul(t)).div(s)).x;r.addAssign(l),n.addAssign(l.mul(l))})),r.divAssign(e),n.divAssign(e);const h=Ya(n.sub(r.mul(r)));return mo(r,h)})),Xf=ro((({samples:e,radius:t,size:s,shadowPass:i})=>{const r=lo(0).toVar(),n=lo(0).toVar(),o=e.lessThanEqual(lo(1)).select(lo(0),lo(2).div(e.sub(1))),a=e.lessThanEqual(lo(1)).select(lo(0),lo(-1));Gc({start:uo(0),end:uo(e),type:"int",condition:"<"},(({i:e})=>{const h=a.add(lo(e).mul(o)),l=i.sample(ya(rd.xy,mo(h,0).mul(t)).div(s));r.addAssign(l.x),n.addAssign(ya(l.y.mul(l.y),l.x.mul(l.x)))})),r.divAssign(e),n.divAssign(e);const h=Ya(n.sub(r.mul(r)));return mo(r,h)})),Yf=[jf,Hf,Wf,$f];let Kf;const Qf=new Jg;class Zf extends Of{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._cameraFrameId=new WeakMap,this.isShadowNode=!0}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r}){const n=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});return n.select(o,lo(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=Eu("bias","float",s).setGroup(Io);let n,o=t;if(s.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)o=o.xyz.div(o.w),n=o.z,i.coordinateSystem===De&&(n=n.mul(2).sub(1));else{const e=o.w;o=o.xy.div(e);const t=Eu("near","float",s.camera).setGroup(Io),i=Eu("far","float",s.camera).setGroup(Io);n=fd(e.negate(),t,i)}return o=bo(o.x,o.y.oneMinus(),n.add(r)),o}getShadowFilterFn(e){return Yf[e]}setupShadow(e){const{renderer:t}=e,{light:s,shadow:i}=this,r=t.shadowMap.type,n=new rr(i.mapSize.width,i.mapSize.height);n.compareFunction=513;const o=e.createRenderTarget(i.mapSize.width,i.mapSize.height);if(o.depthTexture=n,i.camera.updateProjectionMatrix(),3===r){n.compareFunction=null,this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:Y,type:V}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:Y,type:V});const t=Al(n),s=Al(this.vsmShadowMapVertical.texture),r=Eu("blurSamples","float",i).setGroup(Io),o=Eu("radius","float",i).setGroup(Io),a=Eu("mapSize","vec2",i).setGroup(Io);let h=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Sd);h.fragmentNode=qf({samples:r,radius:o,size:a,shadowPass:t}).context(e.getSharedContext()),h.name="VSMVertical",h=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Sd),h.fragmentNode=Xf({samples:r,radius:o,size:a,shadowPass:s}).context(e.getSharedContext()),h.name="VSMHorizontal"}const a=Eu("intensity","float",i).setGroup(Io),h=Eu("normalBias","float",i).setGroup(Io),l=Rf(s).mul(kf.add(uu.mul(h))),u=this.setupShadowCoord(e,l),c=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===c)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const d=3===r?this.vsmShadowMapHorizontal.texture:n,p=this.setupShadowFilter(e,{filterFn:c,shadowTexture:o.texture,depthTexture:d,shadowCoord:u,shadow:i}),m=Al(o.texture,u),g=Bh(1,p.rgb.mix(m,1),a.mul(m.a)).toVar();return this.shadowMap=o,this.shadow.map=o,g}setup(e){if(!1!==e.renderer.shadowMap.enabled)return ro((()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t}))()}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),r.render(n,t.camera)}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:r,scene:n,camera:o}=e,a=r.shadowMap.type,h=t.depthTexture.version;this._depthVersionCached=h,i.camera.layers.mask=o.layers.mask;const l=r.getRenderObjectFunction(),u=r.getMRT(),c=!!u&&u.has("velocity");Kf=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=Uf(e,s)),s}(r,n,Kf),n.overrideMaterial=Gf(s),r.setRenderObjectFunction(((e,t,s,n,h,l,...u)=>{(!0===e.castShadow||e.receiveShadow&&3===a)&&(c&&(Qr(e).useVelocity=!0),e.onBeforeShadow(r,e,o,i.camera,n,t.overrideMaterial,l),r.renderObject(e,t,s,n,h,l,...u),e.onAfterShadow(r,e,o,i.camera,n,t.overrideMaterial,l))})),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(l),!0!==s.isPointLight&&3===a&&this.vsmPass(r),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,Kf)}vsmPass(e){const{shadow:t}=this;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height),e.setRenderTarget(this.vsmShadowMapVertical),Qf.material=this.vsmMaterialVertical,Qf.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),Qf.material=this.vsmMaterialHorizontal,Qf.render(e)}dispose(){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),super.dispose()}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 Jf=new Gs,ey=ro((([e,t])=>{const s=e.toVar(),i=ah(s),r=_a(1,_h(i.x,_h(i.y,i.z)));i.mulAssign(r),s.mulAssign(r.mul(t.mul(2).oneMinus()));const n=mo(s.xy).toVar(),o=t.mul(1.5).oneMinus();return ao(i.z.greaterThanEqual(o),(()=>{ao(s.z.greaterThan(0),(()=>{n.x.assign(ba(4,s.x))}))})).ElseIf(i.x.greaterThanEqual(o),(()=>{const e=hh(s.x);n.x.assign(s.z.mul(e).add(e.mul(2)))})).ElseIf(i.y.greaterThanEqual(o),(()=>{const e=hh(s.y);n.x.assign(s.x.add(e.mul(2)).add(2)),n.y.assign(s.z.mul(e).sub(2))})),mo(.125,.25).mul(n).add(mo(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),ty=ro((({depthTexture:e,bd3D:t,dp:s,texelSize:i})=>Al(e,ey(t,i.y)).compare(s))),sy=ro((({depthTexture:e,bd3D:t,dp:s,texelSize:i,shadow:r})=>{const n=Eu("radius","float",r).setGroup(Io),o=mo(-1,1).mul(n).mul(i.y);return Al(e,ey(t.add(o.xyy),i.y)).compare(s).add(Al(e,ey(t.add(o.yyy),i.y)).compare(s)).add(Al(e,ey(t.add(o.xyx),i.y)).compare(s)).add(Al(e,ey(t.add(o.yyx),i.y)).compare(s)).add(Al(e,ey(t,i.y)).compare(s)).add(Al(e,ey(t.add(o.xxy),i.y)).compare(s)).add(Al(e,ey(t.add(o.yxy),i.y)).compare(s)).add(Al(e,ey(t.add(o.xxx),i.y)).compare(s)).add(Al(e,ey(t.add(o.yxx),i.y)).compare(s)).mul(1/9)})),iy=ro((({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i})=>{const r=s.xyz.toVar(),n=r.length(),o=Oo("float").setGroup(Io).onRenderUpdate((()=>i.camera.near)),a=Oo("float").setGroup(Io).onRenderUpdate((()=>i.camera.far)),h=Eu("bias","float",i).setGroup(Io),l=Oo(i.mapSize).setGroup(Io),u=lo(1).toVar();return ao(n.sub(a).lessThanEqual(0).and(n.sub(o).greaterThanEqual(0)),(()=>{const s=n.sub(o).div(a.sub(o)).toVar();s.addAssign(h);const c=r.normalize(),d=mo(1).div(l.mul(mo(4,2)));u.assign(e({depthTexture:t,bd3D:c,dp:s,texelSize:d,shadow:i}))})),u})),ry=new gt,ny=new Ye,oy=new Ye;class ay extends Zf{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?ty:sy}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:r,shadow:n}){return iy({filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:r,shadow:n})}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:r,scene:n}=e,o=t.getFrameExtents();oy.copy(t.mapSize),oy.multiply(o),s.setSize(oy.width,oy.height),ny.copy(t.mapSize);const a=r.autoClear,h=r.getClearColor(Jf),l=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha),r.clear();const u=t.getViewportCount();for(let e=0;e<u;e++){const o=t.getViewport(e),a=ny.x*o.x,h=oy.y-ny.y-ny.y*o.y;ry.set(a,h,ny.x*o.z,ny.y*o.w),s.viewport.copy(ry),t.updateMatrices(i,e),r.render(n,t.camera)}r.autoClear=a,r.setClearColor(h,l)}}class hy extends Xc{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Gs,this.colorNode=e&&e.colorNode||Oo(this.color).setGroup(Io),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=en}customCacheKey(){return Hr(this.light.id,this.light.castShadow?1:0)}getHash(){return this.light.uuid}getLightVector(e){return Ff(this.light).sub(e.context.positionView||eu)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>Zn(new Zf(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?Zn(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=s=this.colorNode.mul(t),this.baseColorNode=this.colorNode}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 ly=ro((({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 uy extends hy{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Oo(0).setGroup(Io),this.decayExponentNode=Oo(2).setGroup(Io)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>Zn(new ay(e,t)))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:s,decayExponent:i})=>{const r=t.normalize(),n=t.length(),o=ly({lightDistance:n,cutoffDistance:s,decayExponent:i});return{lightDirection:r,lightColor:e.mul(o)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}ro((([e=Tl()],{renderer:t,material:s})=>{const i=lo(1).toVar(),r=Fh(e.mul(2).sub(1));if(s.alphaToCoverage&&t.samples>1){const e=lo(r.fwidth()).toVar();i.assign(Dh(e.oneMinus(),e.add(1),r).oneMinus())}else r.greaterThan(1).discard();return i}));const cy=ro((([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(xa(s,s).sub(xa(i,i)))),n})),dy=new Wg;class py extends dg{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(dy),dy.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(dy),dy.a=1,n=!0;else if(!0===r.isNode){const s=this.get(e),n=r;dy.copy(i._clearColor);let o=s.backgroundMesh;if(void 0===o){const e=Gh(To(n).mul(nf),{getUV:()=>of.mul(hu),getTextureLevel:()=>rf});let t=Cc;t=t.setZ(t.w);const i=new Sd;i.name="Background.material",i.side=1,i.depthTest=!1,i.depthWrite=!1,i.allowOverride=!1,i.fog=!1,i.lights=!1,i.vertexNode=t,i.colorNode=e,s.backgroundMeshNode=e,s.backgroundMesh=o=new Si(new ar(1,32,32),i),o.frustumCulled=!1,o.name="Background.mesh",o.onBeforeRender=function(e,t,s){this.matrixWorld.copyPosition(s.matrixWorld)}}const a=n.getCacheKey();s.backgroundCacheKey!==a&&(s.backgroundMeshNode.node=To(n).mul(nf),s.backgroundMeshNode.needsUpdate=!0,o.material.needsUpdate=!0,s.backgroundCacheKey=a),t.unshift(o,o.geometry,o.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",r);const o=i.xr.getEnvironmentBlendMode();if("additive"===o?dy.set(0,0,0,1):"alpha-blend"===o&&dy.set(0,0,0,0),!0===i.autoClear||!0===n){const e=s.clearColorValue;e.r=dy.r,e.g=dy.g,e.b=dy.b,e.a=dy.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(e.r*=e.a,e.g*=e.a,e.b*=e.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,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 my=0;class gy{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=my++}}class fy{constructor(e,t,s,i,r,n,o,a,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=o,this.updateAfterNodes=a,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 gy(t.name,[],t.index,t);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}class yy{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class by{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf()}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 xy{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class _y extends xy{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class vy{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let Ty=0;class wy{constructor(e=null){this.id=Ty++,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 Sy{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class My{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class Ny extends My{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class Ey extends My{constructor(e,t=new Ye){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class Ay extends My{constructor(e,t=new _t){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class Cy extends My{constructor(e,t=new gt){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class Ry extends My{constructor(e,t=new Gs){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class Py extends My{constructor(e,t=new Ur){super(e,t),this.isMatrix2Uniform=!0,this.boundary=16,this.itemSize=4}}class Fy extends My{constructor(e,t=new Ke){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class By extends My{constructor(e,t=new Kt){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Iy extends Ny{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Ly extends Ey{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Dy extends Ay{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Oy extends Cy{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ky extends Ry{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Uy extends Py{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class zy extends Fy{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Vy extends By{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const Gy=new WeakMap,jy=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Hy=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class Wy{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.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=Xg(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new wy,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null}getBindGroupsCache(){let e=Gy.get(this.renderer);return void 0===e&&(e=new ag,Gy.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new ft(e,t,s)}createCubeRenderTarget(e,t){return new Bd(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let r,n=!0;for(const e of t)i.push(e),n=n&&!0!==e.groupNode.shared;return n?(r=s.get(i),void 0===r&&(r=new gy(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new gy(e,i,this.bindingsIndexes[e].group,i),r}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 hn)for(const i in s[e]){const r=s[e][i];(t[i]||(t[i]=[])).push(...r)}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){!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==Jr&&this.updateNodes.push(e.getSelf())}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==Jr&&this.updateBeforeNodes.push(e.getSelf()),s!==Jr&&this.updateAfterNodes.push(e.getSelf())}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===P||e.magFilter===F||e.magFilter===R||e.magFilter===B||e.minFilter===P||e.minFilter===F||e.minFilter===R||e.minFilter===B}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}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}getSharedContext(){return this.context,this.context}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 wy(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){console.warn("Abstract function.")}getInstanceIndex(){console.warn("Abstract function.")}getDrawIndex(){console.warn("Abstract function.")}getFrontFacing(){console.warn("Abstract function.")}getFragCoord(){console.warn("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(){console.warn("Abstract function.")}generateTextureLod(){console.warn("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 Gs:"vec2"===e?t=new Ye:"vec3"===e?t=new _t:"vec4"===e&&(t=new gt)),"float"===e)return Hy(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")}( ${Hy(t.r)}, ${Hy(t.g)}, ${Hy(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 yy(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===k)return"int";if(t===U)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=function(e){return qr.get(e)}(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return jy.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 ii||!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")}addStack(){return this.stack=Xg(this.stack),this.stacks.push(oo()||this.stack),no(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,no(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);return void 0===i&&(i={},s.setData(e,i)),void 0===i[t]&&(i[t]={}),i[t]}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);let i=s.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new yy("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}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 e=this.structs.index++;null===s&&(s="StructType"+e),n=new Sy(s,t),this.structs[i].push(n),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 o=this.uniforms.index++;n=new by(i||"nodeUniform"+o,t,e),this.uniforms[s].push(n),this.registerDeclaration(n),r.uniform=n}return n}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage,r=!1){const n=this.getDataFromNode(e,i);let o=n.variable;if(void 0===o){const a=r?"_const":"_var",h=this.vars[i]||(this.vars[i]=[]),l=this.vars[a]||(this.vars[a]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+l,this.vars[a]++);const u=this.getArrayCount(e);o=new xy(t,s,r,u),r||h.push(o),this.registerDeclaration(o),n.variable=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)){const i=this.getDataFromNode(e,"any");let r=i.varying;if(void 0===r){const e=this.varyings,n=e.length;null===t&&(t="nodeVarying"+n),r=new _y(t,s),e.push(r),this.registerDeclaration(r),i.varying=r}return r}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++;s[n]=e,r>1&&(e.name=n,console.warn(`THREE.TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${n}'.`))}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 vy("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 Tf,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 $g(e.type,e.name);e.layout=null;const i=e.call(s),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,r=this.declarations,n=this.cache,o=this.buildStage,a=this.stack,h={code:""};this.flow=h,this.vars={},this.declarations={},this.cache=new wy,this.stack=Xg();for(const s of an)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=a,this.setBuildStage(o),h}getFunctionOperator(){return null}buildFunctionCode(){console.warn("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.shaderStage;this.setShaderStage(e);const n=this.flowChildNode(t,s);return null!==i&&(n.code+=`${this.tab+i} = ${n.result};\n`),this.flowCode[e]=this.flowCode[e]+n.code,this.setShaderStage(r),n}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("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(){console.warn("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(){console.warn("Abstract function.")}build(){const{object:e,material:t,renderer:s}=this;if(null!==t){let e=s.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new Sd),e.build(this)}else this.addFlow("compute",e);for(const e of an){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of hn){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}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new Iy(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new Ly(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new Dy(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new Oy(e);if("color"===t)return new ky(e);if("mat2"===t)return new Uy(e);if("mat3"===t)return new zy(e);if("mat4"===t)return new Vy(e);throw new Error(`Uniform "${t}" not declared.`)}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?this.format(`${e}.${"xyz".slice(0,r)}`,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${o} - Node System\n`}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}}class $y{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={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===en){const{frameMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(s,this.frameId)}else if(t===tn){const{renderMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(s,this.renderId)}else t===sn&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===en){const{frameMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(s,this.frameId)}else if(t===tn){const{renderMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(s,this.renderId)}else t===sn&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===en){const{frameMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.frameId&&!1!==e.update(this)&&t.set(s,this.frameId)}else if(t===tn){const{renderMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.renderId&&!1!==e.update(this)&&t.set(s,this.renderId)}else t===sn&&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 qy{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}qy.isNodeFunctionInput=!0;class Xy extends hy{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:Bf(this.light),lightColor:e}}}const Yy=new Kt,Ky=new Kt;let Qy=null;class Zy extends hy{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Oo(new _t).setGroup(Io),this.halfWidth=Oo(new _t).setGroup(Io),this.updateType=tn}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;Ky.identity(),Yy.copy(t.matrixWorld),Yy.premultiply(s),Ky.extractRotation(Yy),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(Ky),this.halfHeight.value.applyMatrix4(Ky)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=Al(Qy.LTC_FLOAT_1),s=Al(Qy.LTC_FLOAT_2)):(t=Al(Qy.LTC_HALF_1),s=Al(Qy.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:Ff(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){Qy=e}}class Jy extends hy{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Oo(0).setGroup(Io),this.penumbraCosNode=Oo(0).setGroup(Io),this.cutoffDistanceNode=Oo(0).setGroup(Io),this.decayExponentNode=Oo(0).setGroup(Io)}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){const{coneCosNode:t,penumbraCosNode:s}=this;return Dh(t,s,e)}setupDirect(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:r}=this,n=this.getLightVector(e),o=n.normalize(),a=o.dot(Bf(r)),h=this.getSpotAttenuation(a),l=n.length(),u=ly({lightDistance:l,cutoffDistance:s,decayExponent:i});let c=t.mul(h).mul(u);if(r.map){const t=function(e,t=Zl){const s=Rf(e).mul(t);return s.xyz.div(s.w)}(r,e.context.positionWorld),s=Al(r.map,t.xy).onRenderUpdate((()=>r.map));c=t.mul(2).sub(1).abs().lessThan(1).all().select(c.mul(s),c)}return{lightColor:c,lightDirection:o}}}class eb extends Jy{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e){const t=this.light.iesMap;let s=null;if(t&&!0===t.isTexture){const i=e.acos().mul(1/Math.PI);s=Al(t,mo(i,0),0).r}else s=super.getSpotAttenuation(e);return s}}class tb extends hy{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class sb extends hy{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Pf(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Oo(new Gs).setGroup(Io)}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=au.dot(i).mul(.5).add(.5),n=Bh(s,t,r);e.context.irradiance.addAssign(n)}}class ib extends hy{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new _t);this.lightProbe=Il(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=cy(hu,this.lightProbe);e.context.irradiance.addAssign(t)}}class rb{parseFunction(){console.warn("Abstract function.")}}class nb{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}nb.isNodeFunction=!0;const ob=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,ab=/[a-z_0-9]+/gi,hb="#pragma main";class lb extends nb{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:o,headerCode:a}=(e=>{const t=(e=e.trim()).indexOf(hb),s=-1!==t?e.slice(t+12):e,i=s.match(ob);if(null!==i&&5===i.length){const r=i[4],n=[];let o=null;for(;null!==(o=ab.exec(r));)n.push(o);const a=[];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];a.push(new qy(s,r,i,t,e))}const l=s.substring(i[0].length),u=void 0!==i[3]?i[3]:"";return{type:i[2],inputs:a,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=o,this.headerCode=a}getCode(e=this.name){let t;const s=this.blockCode;if(""!==s){const{type:i,inputsCode:r,headerCode:n,precision:o}=this;let a=`${i} ${e} ( ${r.trim()} )`;""!==o&&(a=`${o} ${a}`),t=n+a+s}else t="";return t}}class ub extends rb{parseFunction(e){return new lb(e)}}const cb=new WeakMap,db=[],pb=[];class mb extends dg{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new $y,this.nodeBuilderCache=new Map,this.callHashCache=new ag,this.groupsData=new ag,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===Lo.name)return!0;if(s===Io.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===Bo.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}db[0]=t,db[1]=e;let i=this.groupsData.get(db);return void 0===i&&this.groupsData.set(db,i={}),db.length=0,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=this.backend.createNodeBuilder(e.object,this.renderer);t.scene=e.scene,t.material=e.material,t.camera=e.camera,t.context.material=e.material,t.lightsNode=e.lightsNode,t.environmentNode=this.getEnvironmentNode(e.scene),t.fogNode=this.getFogNode(e.scene),t.clippingContext=e.clippingContext,t.build(),s=this._createNodeBuilderState(t),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 fy(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){db[0]=e,db[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(db)||{};if(i.callId!==s){const r=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&pb.push(t.getCacheKey(!0)),r&&pb.push(r.getCacheKey()),n&&pb.push(n.getCacheKey()),pb.push(this.renderer.shadowMap.enabled?1:0),i.callId=s,i.cacheKey=jr(pb),this.callHashCache.set(db,i),pb.length=0}return db.length=0,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||s.mapping===w||s.mapping===S||306===s.mapping){if(e.backgroundBlurriness>0||306===s.mapping)return Im(s);{let e;return e=!0===s.isCubeTexture?Su(s):Al(s),kd(e)}}if(!0===s.isTexture)return Al(s,sd.flipY()).setUpdateMatrix(!0);!0!==s.isColor&&console.error("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=Eu("color","color",s).setGroup(Io),t=Eu("density","float",s).setGroup(Io);return Nf(e,Mf(t))}if(s.isFog){const e=Eu("color","color",s).setGroup(Io),t=Eu("near","float",s).setGroup(Io),i=Eu("far","float",s).setGroup(Io);return Nf(e,Sf(t,i))}console.error("THREE.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?Su(s):!0===s.isTexture?Al(s):void console.error("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}hasOutputChange(e){return cb.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=Al(e,sd).renderOutput(t.toneMapping,t.currentColorSpace);return cb.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 $y,this.nodeBuilderCache=new Map,this.cacheLib={}}}const gb=new Qi;class fb{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Ke,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++){gb.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=gb.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=gb.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,o;if(this.clipIntersection?(n=this.intersectionPlanes,o=e.intersectionPlanes.length):(n=this.unionPlanes,o=e.unionPlanes.length),n.length!==o+r){n.length=o+r;for(let e=0;e<r;e++)n[o+e]=new gt;s=!0}this.projectPlanes(i,n,o),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 fb(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class yb{constructor(e,t){this.bundleGroup=e,this.camera=t}}const bb=[];class xb{constructor(){this.bundles=new ag}get(e,t){const s=this.bundles;bb[0]=e,bb[1]=t;let i=s.get(bb);return void 0===i&&(i=new yb(e,t),s.set(bb,i)),bb.length=0,i}dispose(){this.bundles=new ag}}class _b{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))console.warn(`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))console.warn(`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 vb=new Df,Tb=[];class wb extends ag{constructor(){super()}createNode(e=[]){return(new Df).setLights(e)}getNode(e,t){if(e.isQuadMesh)return vb;Tb[0]=e,Tb[1]=t;let s=this.get(Tb);return void 0===s&&(s=this.createNode(),this.set(Tb,s)),Tb.length=0,s}}class Sb extends ft{constructor(e=1,t=1,s={}){super(e,t,s),this.isXRRenderTarget=!0,this.hasExternalTextures=!1,this.autoAllocateDepthBuffer=!0}copy(e){return super.copy(e),this.hasExternalTextures=e.hasExternalTextures,this.autoAllocateDepthBuffer=e.autoAllocateDepthBuffer,this}}const Mb=new _t,Nb=new _t;class Eb extends Oe{constructor(e){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Bi,this._cameraL.viewport=new gt,this._cameraR=new Bi,this._cameraR.viewport=new gt,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Or,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._supportsLayers=!1,this._createXRLayer=Fb.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new Ye,this._onSessionEvent=Cb.bind(this),this._onSessionEnd=Rb.bind(this),this._onInputSourcesChange=Pb.bind(this),this._onAnimationFrame=Bb.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._useLayers="undefined"!=typeof XRWebGLBinding&&"createProjectionLayer"in XRWebGLBinding.prototype}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&&console.warn("THREE.XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&console.warn("THREE.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}getFrame(){return this._xrFrame}createQuadLayer(e,t,s,i,r,n,o,h=[]){const l=new or(e,t),c=new Sb(r,n,{format:H,type:I,depthTexture:new rr(r,n,h.stencil?G:U,void 0,void 0,void 0,void 0,void 0,void 0,h.stencil?$:W),stencilBuffer:h.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),d=new $s({color:16777215,side:0});d.map=c.texture,d.map.offset.y=1,d.map.repeat.y=-1;const p=new Si(l,d);p.position.copy(s),p.quaternion.copy(i);const m={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:r,pixelheight:n,plane:p,material:d,rendercall:o,renderTarget:c};if(this._layers.push(m),null!==this._session){m.plane.material=new $s({color:16777215,side:0}),m.plane.material.blending=5,m.plane.material.blendEquation=a,m.plane.material.blendSrc=u,m.plane.material.blendDst=u,m.xrlayer=this._createXRLayer(m);const e=this._session.renderState.layers;e.unshift(m.xrlayer),this._session.updateRenderState({layers:e})}else c.isXRRenderTarget=!1;return p}createCylinderLayer(e,t,s,i,r,n,o,h,l=[]){const c=new nr(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),d=new Sb(n,o,{format:H,type:I,depthTexture:new rr(n,o,l.stencil?G:U,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?$:W),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),p=new $s({color:16777215,side:1});p.map=d.texture,p.map.offset.y=1,p.map.repeat.y=-1;const m=new Si(c,p);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:o,plane:m,material:p,rendercall:h,renderTarget:d};if(this._layers.push(g),null!==this._session){g.plane.material=new $s({color:16777215,side:1}),g.plane.material.blending=5,g.plane.material.blendEquation=a,g.plane.material.blendSrc=u,g.plane.material.blendDst=u,g.xrlayer=this._createXRLayer(g);const e=this._session.renderState.layers;e.unshift(g.xrlayer),this._session.updateRenderState({layers:e})}else d.isXRRenderTarget=!1;return m}renderLayers(){const e=new _t,t=new xt,s=this.isPresenting;this.isPresenting=!1;for(const s of this._layers){if(s.renderTarget.isXRRenderTarget=null!==this._session,s.renderTarget.hasExternalTextures=s.renderTarget.isXRRenderTarget,s.renderTarget.autoAllocateDepthBuffer=!s.renderTarget.isXRRenderTarget,s.renderTarget.isXRRenderTarget&&this._supportsLayers){s.xrlayer.transform=new XRRigidTransform(s.plane.getWorldPosition(e),s.plane.getWorldQuaternion(t));const i=this._glBinding.getSubImage(s.xrlayer,this._xrFrame);this._renderer.backend.setXRRenderTargetTextures(s.renderTarget,i.colorTexture,i.depthStencilTexture)}this._renderer.setRenderTarget(s.renderTarget),s.rendercall()}this.isPresenting=s,this._renderer.setRenderTarget(null)}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._useLayers){let s=null,n=null,o=null;t.depth&&(o=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,s=t.stencil?$:W,n=t.stencil?G:U);const h={colorFormat:i.RGBA8,depthFormat:o,scaleFactor:this._framebufferScaleFactor},l=new XRWebGLBinding(e,i),c=l.createProjectionLayer(h),d=[c];if(this._glBinding=l,this._glProjLayer=c,t.setPixelRatio(1),t.setSize(c.textureWidth,c.textureHeight,!1),this._xrRenderTarget=new Sb(c.textureWidth,c.textureHeight,{format:H,type:I,colorSpace:t.outputColorSpace,depthTexture:new rr(c.textureWidth,c.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,s),stencilBuffer:t.stencil,samples:r.antialias?4:0,resolveDepthBuffer:!1===c.ignoreDepthValues,resolveStencilBuffer:!1===c.ignoreDepthValues}),this._xrRenderTarget.hasExternalTextures=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._supportsLayers=e.enabledFeatures.includes("layers"),this._supportsLayers)for(const e of this._layers)e.plane.material=new $s({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=a,e.plane.material.blendSrc=u,e.plane.material.blendDst=u,e.xrlayer=this._createXRLayer(e),d.unshift(e.xrlayer);e.updateRenderState({layers:d})}else{const s={antialias:t.samples>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.setSize(r.framebufferWidth,r.framebufferHeight,!1),this._xrRenderTarget=new Sb(r.framebufferWidth,r.framebufferHeight,{format:H,type:I,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===r.ignoreDepthValues,resolveStencilBuffer:!1===r.ignoreDepthValues})}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,o=this._cameraR;r.near=o.near=n.near=s,r.far=o.far=n.far=i,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),n.layers.mask=2|e.layers.mask,o.layers.mask=4|e.layers.mask,r.layers.mask=n.layers.mask|o.layers.mask;const a=e.parent,h=r.cameras;Ab(r,a);for(let e=0;e<h.length;e++)Ab(h[e],a);2===h.length?function(e,t,s){Mb.setFromMatrixPosition(t.matrixWorld),Nb.setFromMatrixPosition(s.matrixWorld);const i=Mb.distanceTo(Nb),r=t.projectionMatrix.elements,n=s.projectionMatrix.elements,o=r[14]/(r[10]-1),a=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=o*u,p=o*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=o+m,s=a+m,r=d-g,n=p+(i-g),u=h*a/s*t,c=l*a/s*t;e.projectionMatrix.makePerspective(r,n,u,c,t,s),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(r,n,o):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*Ve*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,r,a)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new zi,this._controllers[e]=t),t}}function Ab(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function Cb(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 Rb(){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.backend.setXRTarget(null),t.setOutputRenderTarget(null),t.setRenderTarget(null),this._session=null,this._xrRenderTarget=null,!0===this._supportsLayers)for(const e of this._layers)e.renderTarget=new Sb(e.pixelwidth,e.pixelheight,{format:H,type:I,depthTexture:new rr(e.pixelwidth,e.pixelheight,e.stencilBuffer?G:U,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?$:W),stencilBuffer:e.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,delete e.xrlayer;this.isPresenting=!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 Pb(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 o=t[n];o&&o.connect(r)}}function Fb(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),depthFormat:this._gl.DEPTH_COMPONENT,width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),depthFormat:this._gl.DEPTH_COMPONENT,radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight})}function Bb(e,t){if(void 0===t)return;const s=this._cameraXR,i=this._renderer,r=i.backend,n=this._glBaseLayer,o=this.getReferenceSpace(),a=t.getViewerPose(o);if(this._xrFrame=t,null!==a){const e=a.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 o=e[i];let a;if(!0===this._useLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,o);a=e.viewport,0===i&&r.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues?void 0:e.depthStencilTexture)}else a=n.getViewport(o);let h=this._cameras[i];void 0===h&&(h=new Bi,h.layers.enable(i),h.viewport=new gt,this._cameras[i]=h),h.matrix.fromArray(o.transform.matrix),h.matrix.decompose(h.position,h.quaternion,h.scale),h.projectionMatrix.fromArray(o.projectionMatrix),h.projectionMatrixInverse.copy(h.projectionMatrix).invert(),h.viewport.set(a.x,a.y,a.width,a.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,o)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}const Ib=new Vi,Lb=new Ye,Db=new gt,Ob=new er,kb=new Kt,Ub=new gt;class zb{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:r=!0,stencil:n=!1,antialias:o=!1,samples:a=0,getFallback:h=null,colorBufferType:l=V}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=a||!0===o?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=_e,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=r,this.stencil=n,this.info=new Tg,this.nodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new _b,this.lighting=new wb,this._getFallback=h,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new gt(0,0,this._width,this._height),this._scissor=new gt(0,0,this._width,this._height),this._scissorTest=!1,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 Jg(new Sd),this._quad.material.name="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const u=!0===this.alpha?0:1;this._clearColor=new Wg(0,0,0,u),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._colorBufferType=l,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr=new Eb(this),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(e,t,this._renderTarget),n=e.overrideMaterial||s.material,o=this._objects.get(s,n,e,t,i.lightsNode,r,r.clippingContext),{fragmentShader:a,vertexShader:h}=o.getNodeBuilderState();return{fragmentShader:a,vertexShader:h}}}}async init(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");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 mb(this,s),this._animation=new og(this._nodes,this.info),this._attributes=new bg(s),this._background=new py(this,this._nodes),this._geometries=new vg(this._attributes,this.info),this._textures=new Hg(this,s,this.info),this._pipelines=new Ag(s,this._nodes),this._bindings=new Cg(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new cg(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Lg(this.lighting),this._bundles=new xb,this._renderContexts=new Gg,this._animation.start(),this._initialized=!0,e(this)}))),this._initPromise}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,o=this._currentRenderObjectFunction,a=this._compilationPromises,h=!0===e.isScene?e:Ib;null===s&&(s=e);const l=this._renderTarget,u=this._renderContexts.get(s,t,l),c=this._activeMipmapLevel,d=[];this._currentRenderContext=u,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),u.depth=this.depth,u.stencil=this.stencil,u.clippingContext||(u.clippingContext=new fb),u.clippingContext.updateGlobal(h,t),h.onBeforeRender(this,e,t,l);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,u.clippingContext),s!==e&&s.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==l){this._textures.updateRenderTarget(l,c);const e=this._textures.get(l);u.textures=e.textures,u.depthTexture=e.depthTexture}else u.textures=null,u.depthTexture=null;this._background.update(h,p,u);const m=p.opaque,g=p.transparent,f=p.transparentDoublePass,y=p.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,h,y),!0===this.transparent&&g.length>0&&this._renderTransparents(g,f,t,h,y),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=o,this._compilationPromises=a,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,o=this._currentRenderContext,a=this._bundles.get(i,r),h=this.backend.get(a);void 0===h.renderContexts&&(h.renderContexts=new Set);const l=i.version!==h.version,u=!1===h.renderContexts.has(o)||l;if(h.renderContexts.add(o),u){this.backend.beginBundle(o),(void 0===h.renderObjects||l)&&(h.renderObjects=[]),this._currentRenderBundle=a;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(o,a),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(o,a)}render(e,t){if(!1===this._initialized)return console.warn("THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead."),this.renderAsync(e,t);this._renderScene(e,t)}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this;if(!1===(0!==e)&&!1===(t!==ve))return null;const{width:s,height:i}=this.getDrawingBufferSize(Lb),{depth:r,stencil:n}=this;let o=this._frameBufferTarget;return null===o&&(o=new ft(s,i,{depthBuffer:r,stencilBuffer:n,type:this._colorBufferType,format:H,colorSpace:ve,generateMipmaps:!1,minFilter:P,magFilter:P,samples:this.samples}),o.isPostProcessingRenderTarget=!0,this._frameBufferTarget=o),o.depthBuffer=r,o.stencilBuffer=n,o.setSize(s,i),o.viewport.copy(this._viewport),o.scissor.copy(this._scissor),o.viewport.multiplyScalar(this._pixelRatio),o.scissor.multiplyScalar(this._pixelRatio),o.scissorTest=this._scissorTest,o}_renderScene(e,t,s=!0){if(!0===this._isDeviceLost)return;const i=s?this._getFrameBufferTarget():null,r=this._nodes.nodeFrame,n=r.renderId,o=this._currentRenderContext,a=this._currentRenderObjectFunction,h=!0===e.isScene?e:Ib,l=this._renderTarget||this._outputRenderTarget,u=this._activeCubeFace,c=this._activeMipmapLevel;let d;null!==i?(d=i,this.setRenderTarget(d)):d=l;const p=this._renderContexts.get(e,t,d);this._currentRenderContext=p,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls;const m=this.coordinateSystem,g=this.xr;if(t.coordinateSystem!==m&&!1===g.isPresenting&&(t.coordinateSystem=m,t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.coordinateSystem=m,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());let f=this._viewport,y=this._scissor,b=this._pixelRatio;null!==d&&(f=d.viewport,y=d.scissor,b=1),this.getDrawingBufferSize(Lb),Db.set(0,0,Lb.width,Lb.height);const x=void 0===f.minDepth?0:f.minDepth,_=void 0===f.maxDepth?1:f.maxDepth;p.viewportValue.copy(f).multiplyScalar(b).floor(),p.viewportValue.width>>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=_,p.viewport=!1===p.viewportValue.equals(Db),p.scissorValue.copy(y).multiplyScalar(b).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(Db),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new fb),p.clippingContext.updateGlobal(h,t),h.onBeforeRender(this,e,t,d),kb.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),Ob.setFromProjectionMatrix(kb,m);const v=this._renderLists.get(e,t);if(v.begin(),this._projectObject(e,t,0,v,p.clippingContext),v.finish(),!0===this.sortObjects&&v.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,c);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=u,p.activeMipmapLevel=c,p.occlusionQueryCount=v.occlusionQueryCount,this._background.update(h,v,p),this.backend.beginRender(p);const{bundles:T,lightsNode:w,transparentDoublePass:S,transparent:M,opaque:N}=v;return T.length>0&&this._renderBundles(T,h,w),!0===this.opaque&&N.length>0&&this._renderObjects(N,t,h,w),!0===this.transparent&&M.length>0&&this._renderTransparents(M,S,t,h,w),this.backend.finishRender(p),r.renderId=n,this._currentRenderContext=o,this._currentRenderObjectFunction=a,null!==i&&(this.setRenderTarget(l,u,c),this._renderOutput(d)),h.onAfterRender(this,e,t,d),p}_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)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}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._initialized&&this.backend.updateSize())}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._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}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,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,r=0,n=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,i),o.minDepth=r,o.maxDepth=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 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)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,s);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.getForClear(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,r.clearColorValue=this.backend.getClearColor(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){!1===this._initialized&&await this.init(),this.clear(e,t,s)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:ve}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.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}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,r=this._pipelines,n=this._bindings,o=this._nodes,a=Array.isArray(e)?e:[e];if(void 0===a[0]||!0!==a[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const t of a){if(!1===r.has(t)){const e=()=>{t.removeEventListener("dispose",e),r.delete(t),n.delete(t),o.delete(t)};t.addEventListener("dispose",e);const s=t.onInitFunction;null!==s&&s.call(t,{renderer:this})}o.updateForCompute(t),n.updateForCompute(t);const s=n.getForCompute(t),a=r.getForCompute(t,s);i.compute(e,t,s,a)}i.finishCompute(e),t.renderId=s}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=Ub.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=Ub.copy(t).floor()}else t=Ub.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)}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)}async readRenderTargetPixelsAsync(e,t,s,i,r,n=0,o=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,o)}_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){if(!e.frustumCulled||Ob.intersectsSprite(e)){!0===this.sortObjects&&Ub.setFromMatrixPosition(e.matrixWorld).applyMatrix4(kb);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,Ub.z,null,r)}}else if(e.isLineLoop)console.error("THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||Ob.intersectsObject(e))){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),Ub.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(kb)),Array.isArray(n)){const o=t.groups;for(let a=0,h=o.length;a<h;a++){const h=o[a],l=n[h.materialIndex];l&&l.visible&&i.push(e,t,l,s,Ub.z,h,r)}}else n.visible&&i.push(e,t,n,s,Ub.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,o=n.length;e<o;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,o=e.length;n<o;n++){const{object:o,geometry:a,material:h,group:l,clippingContext:u}=e[n];this._currentRenderObjectFunction(o,s,t,a,h,l,i,u,r)}}renderObject(e,t,s,i,r,n,o,a=null,h=null){let l,u,c;if(e.onBeforeRender(this,t,s,i,r,n),!0===r.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;r.positionNode&&r.positionNode.isNode&&(l=e.positionNode,e.positionNode=r.positionNode),e.alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.transparent=r.transparent||r.transmission>0,e.isShadowPassMaterial&&(e.side=null===r.shadowSide?r.side:r.shadowSide,r.depthNode&&r.depthNode.isNode&&(c=e.depthNode,e.depthNode=r.depthNode),r.castShadowNode&&r.castShadowNode.isNode&&(u=e.colorNode,e.colorNode=r.castShadowNode)),r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,s,o,n,a,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,s,o,n,a,h),r.side=2):this._handleObjectFunction(e,r,t,s,o,n,a,h),void 0!==l&&(t.overrideMaterial.positionNode=l),void 0!==c&&(t.overrideMaterial.depthNode=c),void 0!==u&&(t.overrideMaterial.colorNode=u),e.onAfterRender(this,t,s,i,r,n)}_renderObjectDirect(e,t,s,i,r,n,o,a){const h=this._objects.get(e,t,s,i,r,this._currentRenderContext,o,a);h.drawRange=e.geometry.drawRange,h.group=n;const l=this._nodes.needsRefresh(h);if(l&&(this._nodes.updateBefore(h),this._geometries.updateForRender(h),this._nodes.updateForRender(h),this._bindings.updateForRender(h)),this._pipelines.updateForRender(h),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(h),h.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(h,this.info),l&&this._nodes.updateAfter(h)}_createObjectPipeline(e,t,s,i,r,n,o,a){const h=this._objects.get(e,t,s,i,r,this._currentRenderContext,o,a);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)}get compile(){return this.compileAsync}}class Vb{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class Gb extends Vb{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(yg-e%yg)%yg;var e}get buffer(){return this._buffer}update(){return!0}}class jb extends Gb{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let Hb=0;class Wb extends jb{constructor(e,t){super("UniformBuffer_"+Hb++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class $b extends jb{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}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(){let e=0;for(let t=0,s=this.uniforms.length;t<s;t++){const s=this.uniforms[t],{boundary:i,itemSize:r}=s,n=e%yg;0!==n&&yg-n-i<0?e+=yg-n:n%i!=0&&(e+=n%i),s.offset=e/this.bytesPerElement,e+=r*this.bytesPerElement}return Math.ceil(e/yg)*yg}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 console.error("THREE.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}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 e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,t=!0}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 e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,e[r+2]=s[r+2]=i.z,t=!0}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 e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,e[r+2]=s[r+2]=i.z,e[r+3]=s[r+3]=i.w,t=!0}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 e=this.buffer;e[r+0]=s[r+0]=i.r,e[r+1]=s[r+1]=i.g,e[r+2]=s[r+2]=i.b,t=!0}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 e=this.buffer;e[r+0]=s[r+0]=i[0],e[r+1]=s[r+1]=i[1],e[r+2]=s[r+2]=i[2],e[r+4]=s[r+4]=i[3],e[r+5]=s[r+5]=i[4],e[r+6]=s[r+6]=i[5],e[r+8]=s[r+8]=i[6],e[r+9]=s[r+9]=i[7],e[r+10]=s[r+10]=i[8],t=!0}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}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 qb=0;class Xb extends $b{constructor(e,t){super(e),this.id=qb++,this.groupNode=t,this.isNodeUniformsGroup=!0}}let Yb=0;class Kb extends Vb{constructor(e,t){super(e),this.id=Yb++,this.texture=t,this.version=t?t.version:0,this.store=!1,this.generation=null,this.isSampledTexture=!0}needsBindingsUpdate(e){const{texture:t}=this;return e!==this.generation?(this.generation=e,!0):t.isVideoTexture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}}class Qb extends Kb{constructor(e,t,s,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s,this.access=i}needsBindingsUpdate(e){return this.textureNode.value!==this.texture||super.needsBindingsUpdate(e)}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class Zb extends Qb{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class Jb extends Qb{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const ex={textureDimensions:"textureSize",equals:"equal"},tx={low:"lowp",medium:"mediump",high:"highp"},sx={swizzleAssign:!0,storageBuffer:!1},ix="\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 lowp sampler2DShadow;\n";class rx extends Wy{constructor(e,t){super(e,t,new ub),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==xe}getMethod(e){return ex[e]||e}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?X:q;2===i?n=r?K:Y:3===i?n=r?1032:j:4===i&&(n=r?Q:H);const o={Float32Array:z,Uint8Array:I,Uint16Array:O,Uint32Array:U,Int8Array:L,Int16Array:D,Int32Array:k,Uint8ClampedArray:I},a=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(s/i))));let h=Math.ceil(s/i/a);a*h*i<s&&h++;const l=a*h*i,u=new e.constructor(l);u.set(e,0),t.array=u;const c=new $i(t.array,a,h,n,o[t.array.constructor.name]||z);c.needsUpdate=!0,c.isPBOTexture=!0;const d=new El(c,null,null);d.setPrecision("high"),t.pboNode=d,t.pbo=d.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.label)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?t.charAt(0)+"_"+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.label),n=this.getPropertyName(r);this.increaseUsage(s);const o=s.build(this,"uint"),a=this.getDataFromNode(e);let h=a.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="."+ln.join("").slice(0,u),d=`ivec2(${o} % ${l}, ${o} / ${l})`,p=this.generateTextureLoad(null,n,d,null,"0");let m="vec4";i.pbo.type===U?m="uvec4":i.pbo.type===k&&(m="ivec4"),this.addLineFlowCode(`${h} = ${m}(${p})${c}`,e),a.propertyName=h}return h}generateTextureLoad(e,t,s,i,r="0"){return i?`texelFetch( ${t}, ivec3( ${s}, ${i} ), ${r} )`:`texelFetch( ${t}, ${s}, ${r} )`}generateTexture(e,t,s,i){return e.isDepthTexture?`texture( ${t}, ${s} ).x`:(i&&(s=`vec3( ${s}, ${i} )`),`texture( ${t}, ${s} )`)}generateTextureLevel(e,t,s,i){return`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i){return`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i){return`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`texture( ${t}, vec3( ${s}, ${i} ) )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} 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 r of t){let t=null,n=!1;if("texture"===r.type||"texture3D"===r.type){const e=r.node.value;let s="";!0!==e.isDataTexture&&!0!==e.isData3DTexture||(e.type===U?s="u":e.type===k&&(s="i")),t="texture3D"===r.type?`${s}sampler3D ${r.name};`:e.compareFunction?`sampler2DShadow ${r.name};`:!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?`${s}sampler2DArray ${r.name};`:`${s}sampler2D ${r.name};`}else if("cubeTexture"===r.type)t=`samplerCube ${r.name};`;else if("buffer"===r.type){const e=r.node,s=this.getType(e.bufferType),i=e.bufferCount,n=i>0?i:"";t=`${e.name} {\n\t${s} ${r.name}[${n}];\n};\n`}else{t=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,n=!0}const o=r.node.precision;if(null!==o&&(t=tx[o]+" "+t),n){t="\t"+t;const e=r.groupNode.name;(i[e]||(i[e]=[])).push(t)}else t="uniform "+t,s.push(t)}let r="";for(const t in i){const s=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,s.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==k){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){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);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`}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=sx[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)}sx[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} ]`)}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${ix}\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// precision\n${ix}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\n// structs\n${e.structs}\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 o=n.uniformGPU;if(void 0===o){const i=e.groupNode,a=i.name,h=this.getBindGroupArray(a,s);if("texture"===t)o=new Qb(r.name,r.node,i),h.push(o);else if("cubeTexture"===t)o=new Zb(r.name,r.node,i),h.push(o);else if("texture3D"===t)o=new Jb(r.name,r.node,i),h.push(o);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,r.name=`buffer${e.id}`;const t=new Wb(e,i);t.name=e.name,h.push(t),o=t}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new Xb(s+"_"+a,i),e[a]=n,h.push(n)),o=this.getNodeUniform(r,t),n.addUniform(o)}n.uniformGPU=o}return r}}let nx=null,ox=null;class ax{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute: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(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void tt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void tt(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const s=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=s,s}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return nx=nx||new Ye,this.renderer.getDrawingBufferSize(nx)}setScissorTest(){}getClearColor(){const e=this.renderer;return ox=ox||new Wg,e.getClearColor(ox),ox.getRGB(ox),ox}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=Je("canvas");return e.style.display="block",e}(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${o} webgpu`),this.domElement=e),e}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)}dispose(){}}let hx,lx,ux=0;class cx{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 dx{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,a=s.get(o);let h,l=a.bufferGPU;if(void 0===l&&(l=this._createBuffer(i,t,r,n),a.bufferGPU=l,a.bufferType=t,a.version=o.version),r instanceof Float32Array)h=i.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===k,id:ux++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);u=new cx(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),o=n.bufferType,a=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,n.bufferGPU),0===a.length)s.bufferSubData(o,0,i);else{for(let e=0,t=a.length;e<t;e++){const t=a[e];s.bufferSubData(o,t.start*i.BYTES_PER_ELEMENT,i,t.start,t.count)}r.clearUpdateRanges()}s.bindBuffer(o,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,o=n.byteLength;s.bindBuffer(s.COPY_READ_BUFFER,r);const a=s.createBuffer();s.bindBuffer(s.COPY_WRITE_BUFFER,a),s.bufferData(s.COPY_WRITE_BUFFER,o,s.STREAM_READ),s.copyBufferSubData(s.COPY_READ_BUFFER,s.COPY_WRITE_BUFFER,0,0,o),await t.utils._clientWaitAsync();const h=new e.array.constructor(n.length);return s.bindBuffer(s.COPY_WRITE_BUFFER,a),s.getBufferSubData(s.COPY_WRITE_BUFFER,0,h),s.deleteBuffer(a),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 px{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.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;hx={[a]:e.FUNC_ADD,[h]:e.FUNC_SUBTRACT,[l]:e.FUNC_REVERSE_SUBTRACT},lx={[u]:e.ZERO,[c]:e.ONE,[d]:e.SRC_COLOR,[m]:e.SRC_ALPHA,[_]:e.SRC_ALPHA_SATURATE,[b]:e.DST_COLOR,[f]:e.DST_ALPHA,[p]:e.ONE_MINUS_SRC_COLOR,[g]:e.ONE_MINUS_SRC_ALPHA,[x]:e.ONE_MINUS_DST_COLOR,[y]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=(new gt).fromArray(t),this.currentViewport=(new gt).fromArray(s),this._tempVec4=new gt}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)}setBlending(e,t,s,i,r,n,o,h){const{gl:l}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,n=n||s,o=o||i,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(l.blendEquationSeparate(hx[t],hx[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&o===this.currentBlendDstAlpha||(l.blendFuncSeparate(lx[s],lx[i],lx[n],lx[o]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=n,this.currentBlendDstAlpha=o),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||h!==this.currentPremultipledAlpha){if(this.currentBlendEquation===a&&this.currentBlendEquationAlpha===a||(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=a,this.currentBlendEquationAlpha=a),h)switch(e){case 1:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFunc(l.ONE,l.ONE);break;case 3:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case 4:l.blendFuncSeparate(l.ZERO,l.SRC_COLOR,l.ZERO,l.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}else switch(e){case 1:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFunc(l.SRC_ALPHA,l.ONE);break;case 3:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case 4:l.blendFunc(l.ZERO,l.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=h}}else!0===this.currentBlendingEnabled&&(this.disable(l.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)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(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?t.enable(t.SCISSOR_TEST):t.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.samples>1?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:o}=this;void 0===s&&(s=null===r?i.TEXTURE0+o-1:r);let a=n[s];void 0===a&&(a={type:void 0,texture:void 0},n[s]=a),a.type===e&&a.texture===t||(r!==s&&(i.activeTexture(s),this.currentTextureSlot=s),i.bindTexture(e,t),a.type=e,a.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 mx{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;if(e===I)return s.UNSIGNED_BYTE;if(1017===e)return s.UNSIGNED_SHORT_4_4_4_4;if(1018===e)return s.UNSIGNED_SHORT_5_5_5_1;if(35902===e)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===L)return s.BYTE;if(e===D)return s.SHORT;if(e===O)return s.UNSIGNED_SHORT;if(e===k)return s.INT;if(e===U)return s.UNSIGNED_INT;if(e===z)return s.FLOAT;if(e===V)return s.HALF_FLOAT;if(1021===e)return s.ALPHA;if(e===j)return s.RGB;if(e===H)return s.RGBA;if(1024===e)return s.LUMINANCE;if(1025===e)return s.LUMINANCE_ALPHA;if(e===W)return s.DEPTH_COMPONENT;if(e===$)return s.DEPTH_STENCIL;if(e===q)return s.RED;if(e===X)return s.RED_INTEGER;if(e===Y)return s.RG;if(e===K)return s.RG_INTEGER;if(e===Q)return s.RGBA_INTEGER;if(e===Z||e===J||e===ee||e===te)if(t===_e){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===Z)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===J)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===ee)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===te)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===Z)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===J)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===ee)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===te)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===e||35841===e||35842===e||35843===e){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(35840===e)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===e)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===e)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===e)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===e||e===se||e===ie){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(36196===e||e===se)return t===_e?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===ie)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}if(e===re||e===ne||e===oe||e===ae||e===he||e===le||e===ue||e===ce||e===de||e===pe||e===me||e===ge||e===fe||e===ye){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===re)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===ne)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===oe)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===ae)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===he)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===le)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===ue)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===ce)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===de)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===pe)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===me)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===ge)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===fe)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===ye)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===be){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===be)return t===_e?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(36283===e||36284===e||36285===e||36286===e){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===be)return r.COMPRESSED_RED_RGTC1_EXT;if(36284===e)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(36285===e)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(36286===e)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===G?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 gx,fx,yx,bx=!1;class xx{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===bx&&(this._init(),bx=!0)}_init(){const e=this.gl;gx={[M]:e.REPEAT,[N]:e.CLAMP_TO_EDGE,[E]:e.MIRRORED_REPEAT},fx={[A]:e.NEAREST,[C]:e.NEAREST_MIPMAP_NEAREST,[R]:e.NEAREST_MIPMAP_LINEAR,[P]:e.LINEAR,[F]:e.LINEAR_MIPMAP_NEAREST,[B]:e.LINEAR_MIPMAP_LINEAR},yx={[Me]:e.NEVER,[Fe]:e.ALWAYS,[Ne]:e.LESS,[Ae]:e.LEQUAL,[Ee]:e.EQUAL,[Pe]:e.GEQUAL,[Ce]:e.GREATER,[Re]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!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:o}=this;if(null!==e){if(void 0!==n[e])return n[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let a=t;return t===n.RED&&(s===n.FLOAT&&(a=n.R32F),s===n.HALF_FLOAT&&(a=n.R16F),s===n.UNSIGNED_BYTE&&(a=n.R8),s===n.UNSIGNED_SHORT&&(a=n.R16),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RED_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.R8UI),s===n.UNSIGNED_SHORT&&(a=n.R16UI),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RG&&(s===n.FLOAT&&(a=n.RG32F),s===n.HALF_FLOAT&&(a=n.RG16F),s===n.UNSIGNED_BYTE&&(a=n.RG8),s===n.UNSIGNED_SHORT&&(a=n.RG16),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RG_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RG8UI),s===n.UNSIGNED_SHORT&&(a=n.RG16UI),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RGB&&(s===n.FLOAT&&(a=n.RGB32F),s===n.HALF_FLOAT&&(a=n.RGB16F),s===n.UNSIGNED_BYTE&&(a=n.RGB8),s===n.UNSIGNED_SHORT&&(a=n.RGB16),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I),s===n.UNSIGNED_BYTE&&(a=i===_e&&!1===r?n.SRGB8:n.RGB8),s===n.UNSIGNED_SHORT_5_6_5&&(a=n.RGB565),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGB4),s===n.UNSIGNED_INT_5_9_9_9_REV&&(a=n.RGB9_E5)),t===n.RGB_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGB8UI),s===n.UNSIGNED_SHORT&&(a=n.RGB16UI),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I)),t===n.RGBA&&(s===n.FLOAT&&(a=n.RGBA32F),s===n.HALF_FLOAT&&(a=n.RGBA16F),s===n.UNSIGNED_BYTE&&(a=n.RGBA8),s===n.UNSIGNED_SHORT&&(a=n.RGBA16),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I),s===n.UNSIGNED_BYTE&&(a=i===_e&&!1===r?n.SRGB8_ALPHA8:n.RGBA8),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGBA4),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1)),t===n.RGBA_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGBA8UI),s===n.UNSIGNED_SHORT&&(a=n.RGBA16UI),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(s===n.UNSIGNED_SHORT&&(a=n.DEPTH_COMPONENT16),s===n.UNSIGNED_INT&&(a=n.DEPTH_COMPONENT24),s===n.FLOAT&&(a=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&s===n.UNSIGNED_INT_24_8&&(a=n.DEPTH24_STENCIL8),a!==n.R16F&&a!==n.R32F&&a!==n.RG16F&&a!==n.RG32F&&a!==n.RGBA16F&&a!==n.RGBA32F||o.get("EXT_color_buffer_float"),a}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this;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,s.NONE),s.texParameteri(e,s.TEXTURE_WRAP_S,gx[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,gx[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||s.texParameteri(e,s.TEXTURE_WRAP_R,gx[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,fx[t.magFilter]);const n=void 0!==t.mipmaps&&t.mipmaps.length>0,o=t.minFilter===P&&n?B:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,fx[o]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,yx[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===A)return;if(t.minFilter!==R&&t.minFilter!==B)return;if(t.type===z&&!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,isDefault:!0})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:r,width:n,height:o,depth:a}=t,h=i.utils.convert(e.format,e.colorSpace),l=i.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,h,l,e.colorSpace,e.isVideoTexture),c=s.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,c),this.setTextureParameters(d,e),e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,r,u,n,o,a):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,r,u,n,o,a):e.isVideoTexture||s.texStorage2D(d,r,u,n,o),i.set(e,{textureGPU:c,glTextureType:d,glFormat:h,glType:l,glInternalFormat:u})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:r,glTextureType:n,glFormat:o,glType:a}=i.get(t),{width:h,height:l}=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,l,o,a,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:o,glFormat:a,glType:h,glInternalFormat:l}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===n)return;const u=e=>e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||e instanceof OffscreenCanvas?e:e.data;if(this.backend.state.bindTexture(o,n),this.setTextureParameters(o,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!==a?s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,a,n.data):console.warn("THREE.WebGLRenderer: 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,a,h,n.data):null!==a?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,a,n.data):console.warn("Unsupported compressed texture format")}}else if(e.isCubeTexture){const e=t.images;for(let t=0;t<6;t++){const n=u(e[t]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,i,r,a,h,n)}}else if(e.isDataArrayTexture){const e=t.image;s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,e.width,e.height,e.depth,a,h,e.data)}else if(e.isData3DTexture){const e=t.image;s.texSubImage3D(s.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,a,h,e.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(o,0,l,a,h,t.image);else{const e=u(t.image);s.texSubImage2D(o,0,0,0,i,r,a,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){const{gl:t,backend:s}=this,{textureGPU:i,renderTarget:r}=s.get(e);this.deallocateRenderBuffers(r),t.deleteTexture(i),s.delete(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){const{gl:o,backend:a}=this,{state:h}=this.backend,{textureGPU:l,glTextureType:u,glType:c,glFormat:d}=a.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?T.depth:e.isData3DTexture?Math.floor(T.depth*t):1,f=0,y=0,b=0}null!==i?(x=i.x,_=i.y,v=i.z):(x=0,_=0,v=0),o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,t.flipY),o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),o.pixelStorei(o.UNPACK_ALIGNMENT,t.unpackAlignment);const w=o.getParameter(o.UNPACK_ROW_LENGTH),S=o.getParameter(o.UNPACK_IMAGE_HEIGHT),M=o.getParameter(o.UNPACK_SKIP_PIXELS),N=o.getParameter(o.UNPACK_SKIP_ROWS),E=o.getParameter(o.UNPACK_SKIP_IMAGES);o.pixelStorei(o.UNPACK_ROW_LENGTH,T.width),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,T.height),o.pixelStorei(o.UNPACK_SKIP_PIXELS,f),o.pixelStorei(o.UNPACK_SKIP_ROWS,y),o.pixelStorei(o.UNPACK_SKIP_IMAGES,b);const A=t.isDataArrayTexture||t.isData3DTexture;if(e.isRenderTargetTexture||e.isDepthTexture){const s=a.get(e),i=a.get(t),r=a.get(s.renderTarget),n=a.get(i.renderTarget),l=r.framebuffers[s.cacheKey],u=n.framebuffers[i.cacheKey];h.bindFramebuffer(o.READ_FRAMEBUFFER,l),h.bindFramebuffer(o.DRAW_FRAMEBUFFER,u);let c=o.COLOR_BUFFER_BIT;e.isDepthTexture&&(c=o.DEPTH_BUFFER_BIT),o.blitFramebuffer(f,y,p,m,x,_,p,m,c,o.NEAREST),h.bindFramebuffer(o.READ_FRAMEBUFFER,null),h.bindFramebuffer(o.DRAW_FRAMEBUFFER,null)}else A?e.isDataTexture||e.isData3DTexture?o.texSubImage3D(u,n,x,_,v,p,m,g,d,c,T.data):t.isCompressedArrayTexture?o.compressedTexSubImage3D(u,n,x,_,v,p,m,g,d,T.data):o.texSubImage3D(u,n,x,_,v,p,m,g,d,c,T):e.isDataTexture?o.texSubImage2D(u,n,x,_,p,m,d,c,T.data):e.isCompressedTexture?o.compressedTexSubImage2D(u,n,x,_,T.width,T.height,d,T.data):o.texSubImage2D(u,n,x,_,p,m,d,c,T);o.pixelStorei(o.UNPACK_ROW_LENGTH,w),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,S),o.pixelStorei(o.UNPACK_SKIP_PIXELS,M),o.pixelStorei(o.UNPACK_SKIP_ROWS,N),o.pixelStorei(o.UNPACK_SKIP_IMAGES,E),0===n&&t.generateMipmaps&&o.generateMipmap(u),h.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:r}=this.backend,{textureGPU:n}=this.backend.get(e),{x:o,y:a,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!==o||0!==a;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-a-l;i.blitFramebuffer(o,p,o+h,p+l,o,p,o+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,o,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,o,c-l-a,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:o,depthBuffer:a,stencilBuffer:h,width:l,height:u}=n;if(r.bindRenderbuffer(r.RENDERBUFFER,e),a&&!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?(o&&o.isDepthTexture&&o.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 a&&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))}async copyTextureToBuffer(e,t,s,i,r,n){const{backend:o,gl:a}=this,{textureGPU:h,glFormat:l,glType:u}=this.backend.get(e),c=a.createFramebuffer();a.bindFramebuffer(a.READ_FRAMEBUFFER,c);const d=e.isCubeTexture?a.TEXTURE_CUBE_MAP_POSITIVE_X+n:a.TEXTURE_2D;a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,d,h,0);const p=this._getTypedArrayType(u),m=i*r*this._getBytesPerTexel(u,l),g=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,g),a.bufferData(a.PIXEL_PACK_BUFFER,m,a.STREAM_READ),a.readPixels(t,s,i,r,l,u,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();const f=new p(m/p.BYTES_PER_ELEMENT);return a.bindBuffer(a.PIXEL_PACK_BUFFER,g),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,f),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.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}}class _x{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 vx{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 Tx={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",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query"};class wx{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:o,index:a}=this;0!==a?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),o.update(r,t,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:o,object:a,info:h}=this;0!==s&&(0!==o?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),h.update(a,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:o}=this;if(0===s)return;const a=i.get("WEBGL_multi_draw");if(null===a)for(let i=0;i<s;i++)this.render(e[i],t[i]);else{0!==this.index?a.multiDrawElementsWEBGL(r,t,0,this.type,e,0,s):a.multiDrawArraysWEBGL(r,e,0,t,0,s);let i=0;for(let e=0;e<s;e++)i+=t[e];o.update(n,i,1)}}renderMultiDrawInstances(e,t,s,i){const{extensions:r,mode:n,object:o,info:a}=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];a.update(o,r,1)}}}class Sx{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.pendingResolve=!1}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class Mx extends Sx{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 console.warn("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 tt(`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.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);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){console.error("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.id);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){console.error("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=[];for(const[t,s]of this.queryStates)if("ended"===s){const s=this.queries[t];e.push(this.resolveQuery(s))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce(((e,t)=>e+t),0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("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){console.error("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 Nx extends ax{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.samples>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 _x(this),this.capabilities=new vx(this),this.attributeUtils=new dx(this),this.textureUtils=new xx(this),this.bufferRenderer=new wx(this),this.state=new px(this),this.utils=new mx(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.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return Le}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}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")&&e.autoAllocateDepthBuffer&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e.autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new Mx(this.gl,t,2048));const s=this.timestampQueryPool[t];null!==s.allocateQueriesForContext(e)&&s.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t,gl:s}=this,i=this.get(e);if(e.viewport?this.updateViewport(e):t.viewport(0,0,s.drawingBufferWidth,s.drawingBufferHeight),e.scissor){const{x:s,y:i,width:r,height:n}=e.scissorValue;t.scissor(s,e.height-n-i,r,n)}this.initTimestampQuery(e),i.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const r=e.occlusionQueryCount;r>0&&(i.currentOcclusionQueries=i.occlusionQueries,i.currentOcclusionQueryObjects=i.occlusionQueryObjects,i.lastOcclusionObject=null,i.occlusionQueries=new Array(r),i.occlusionQueryObjects=new Array(r),i.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 o=e.textures;if(null!==o)for(let e=0;e<o.length;e++){const t=o[e];t.generateMipmaps&&this.generateMipmaps(t)}if(this._currentContext=r,null!==e.textures&&e.renderTarget){const i=this.get(e.renderTarget),{samples:r}=e.renderTarget;if(r>0&&!1===this._useMultisampledRTT(e.renderTarget)){const r=i.framebuffers[e.getCacheKey()],n=t.COLOR_BUFFER_BIT,o=i.msaaFrameBuffer,a=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,o),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,r);for(let s=0;s<a.length;s++)if(e.scissor){const{x:s,y:r,width:o,height:a}=e.scissorValue,h=e.height-a-r;t.blitFramebuffer(s,h,s+o,h+a,s,h,s+o,h+a,n,t.NEAREST),!0===this._supportsInvalidateFramebuffer&&t.invalidateSubFramebuffer(t.READ_FRAMEBUFFER,i.invalidationArray,s,h,o,a)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,n,t.NEAREST),!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,i.invalidationArray)}}null!==r&&(this._setFramebuffer(r),r.viewport?this.updateViewport(r):s.viewport(0,0,t.drawingBufferWidth,t.drawingBufferHeight)),this.prepareTimestampBuffer(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 o=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),o++))}o<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)}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){const{gl:n,renderer:o}=this;if(null===i){i={textures:null,clearColorValue:this.getClearColor()}}let a=0;if(e&&(a|=n.COLOR_BUFFER_BIT),t&&(a|=n.DEPTH_BUFFER_BIT),s&&(a|=n.STENCIL_BUFFER_BIT),0!==a){let h;h=i.clearColorValue?i.clearColorValue:this.getClearColor();const l=o.getClearDepth(),u=o.getClearStencil();if(t&&this.state.setDepthMask(!0),null===i.textures)n.clearColor(h.r,h.g,h.b,h.a),n.clear(a);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++)0===e?n.clearBufferfv(n.COLOR,e,[h.r,h.g,h.b,h.a]):n.clearBufferfv(n.COLOR,e,[0,0,0,1]);t&&s?n.clearBufferfi(n.DEPTH_STENCIL,0,l,u):t?n.clearBufferfv(n.DEPTH,0,[l]):s&&n.clearBufferiv(n.STENCIL,0,[u])}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(e)}compute(e,t,s,i){const{state:r,gl:n}=this;!1===this.discard&&(n.enable(n.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformBuffers:a,attributes:h}=this.get(i),l=this._getVaoKey(h),u=this.vaoCache[l];void 0===u?this._createVao(h):r.setVertexState(u),r.useProgram(o),this._bindUniforms(s);const c=this._getTransformFeedback(a);n.bindTransformFeedback(n.TRANSFORM_FEEDBACK,c),n.beginTransformFeedback(n.POINTS),h[0].isStorageInstancedBufferAttribute?n.drawArraysInstanced(n.POINTS,0,1,t.count):n.drawArrays(n.POINTS,0,t.count),n.endTransformFeedback(),n.bindTransformFeedback(n.TRANSFORM_FEEDBACK,null);for(let e=0;e<a.length;e++){const t=a[e];t.pbo&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const t=this.gl;this.discard=!1,t.disable(t.RASTERIZER_DISCARD),this.prepareTimestampBuffer(e),this._currentContext&&this._setFramebuffer(this._currentContext)}draw(e){const{object:t,pipeline:s,material:i,context:r,hardwareClippingPlanes:n}=e,{programGPU:o}=this.get(s),{gl:a,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),h.useProgram(o);const d=this.get(e);let p=d.staticVao;if(void 0===p||d.geometryId!==e.geometry.id){const t=this._getVaoKey(e.getAttributes());if(p=this.vaoCache[t],void 0===p){let t;({vaoGPU:p,staticVao:t}=this._createVao(e.getAttributes())),t&&(d.staticVao=p,d.geometryId=e.geometry.id)}}const m=e.getIndex(),g=null!==m?this.get(m).bufferGPU:null;h.setVertexState(p,g);const f=l.lastOcclusionObject;if(f!==t&&void 0!==f){if(null!==f&&!0===f.occlusionTest&&(a.endQuery(a.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),!0===t.occlusionTest){const e=a.createQuery();a.beginQuery(a.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}const y=this.bufferRenderer;t.isPoints?y.mode=a.POINTS:t.isLineSegments?y.mode=a.LINES:t.isLine?y.mode=a.LINE_STRIP:t.isLineLoop?y.mode=a.LINE_LOOP:!0===i.wireframe?(h.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),y.mode=a.LINES):y.mode=a.TRIANGLES;const{vertexCount:b,instanceCount:x}=u;let{firstVertex:_}=u;if(y.object=t,null!==m){_*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);y.index=m.count,y.type=e.type}else y.index=0;const v=()=>{t.isBatchedMesh?null!==t._multiDrawInstances?(tt("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),y.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?y.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):tt("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):x>1?y.renderInstances(_,b,x):y.render(_,b)};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){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=a.createBuffer();e[0]=s,a.bindBuffer(a.UNIFORM_BUFFER,i),a.bufferData(a.UNIFORM_BUFFER,e,a.STATIC_DRAW),t.push(i)}s.indexesGPU=t}const n=this.get(r),o=this.renderer.getPixelRatio();for(let r=0,l=i.length;r<l;r++){const l=i[r];if(t.layers.test(l.layers)){const t=l.viewport,i=t.x*o,u=t.y*o,c=t.width*o,d=t.height*o;h.viewport(Math.floor(i),Math.floor(e.context.height-d-u),Math.floor(c),Math.floor(d)),h.bindBufferBase(a.UNIFORM_BUFFER,n.index,s.indexesGPU[r]),v()}}}else v()}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){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new rx(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,o=s.createProgram(),a=this.get(r).shaderGPU,h=this.get(n).shaderGPU;if(s.attachShader(o,a),s.attachShader(o,h),s.linkProgram(o),this.set(i,{programGPU:o,fragmentShader:a,vertexShader:h}),null!==t&&this.parallel){const r=new Promise((t=>{const r=this.parallel,n=()=>{s.getProgramParameter(o,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(n)};n()}));t.push(r)}else 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"),o=this._getShaderErrors(i,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+o)}else""!==r&&console.warn("THREE.WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:o,vertexShader:a}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,o,a),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,o=i.createProgram(),a=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(o,a),i.attachShader(o,h),i.transformFeedbackVaryings(o,u,i.SEPARATE_ATTRIBS),i.linkProgram(o),!1===i.getProgramParameter(o,i.LINK_STATUS)&&this._logProgramError(o,a,h),s.useProgram(o),this._setupBindings(t,o);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:o,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)if(s.isUniformsGroup||s.isUniformBuffer){const e=s.buffer,r=t.createBuffer();t.bindBuffer(t.UNIFORM_BUFFER,r),t.bufferData(t.UNIFORM_BUFFER,e,t.DYNAMIC_DRAW),this.set(s,{index:i++,bufferGPU:r})}else if(s.isSampledTexture){const{textureGPU:e,glTextureType:t}=this.get(s.texture);this.set(s,{index:r++,textureGPU:e,glTextureType:t})}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const s=this.get(e).bufferGPU,i=e.buffer;t.bindBuffer(t.UNIFORM_BUFFER,s),t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW)}}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(Tx).filter((t=>Tx[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)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(null!==e.textures){const r=e.renderTarget,n=this.get(r),{samples:o,depthBuffer:a,stencilBuffer:h}=r,l=!0===r.isWebGLCubeRenderTarget,u=!0===r.isRenderTarget3D,c=!0===r.isRenderTargetArray,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._useMultisampledRTT(r),b=kg(e);let x;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),x=n.cubeFramebuffers[b]):d&&!1===p?x=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),x=n.framebuffers[b]),void 0===x){x=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,x);const i=e.textures;if(l){n.cubeFramebuffers[b]=x;const{textureGPU:e}=this.get(i[0]),s=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+s,e,0)}else{n.framebuffers[b]=x;for(let s=0;s<i.length;s++){const r=i[s],n=this.get(r);n.renderTarget=e.renderTarget,n.cacheKey=b;const a=t.COLOR_ATTACHMENT0+s;if(u||c){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,a,n.textureGPU,0,e)}else p&&y?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,a,t.TEXTURE_2D,n.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,n.textureGPU,0)}s.drawBuffers(e,x)}if(r.isXRRenderTarget&&!0===r.autoAllocateDepthBuffer){const s=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(s,e,0,y),n.xrDepthRenderbuffer=s}else if(null!==e.depthTexture){const s=this.get(e.depthTexture),i=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;s.renderTarget=e.renderTarget,s.cacheKey=b,p&&y?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,i,t.TEXTURE_2D,s.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,i,t.TEXTURE_2D,s.textureGPU,0)}}else if(d&&p){s.bindFramebuffer(t.FRAMEBUFFER,x);const i=this.get(e.textures[0]);y?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0);const a=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,a,t.RENDERBUFFER,e)}else{const s=this.get(e.depthTexture);y?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,a,t.TEXTURE_2D,s.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,s.textureGPU,0)}}if(o>0&&!1===y){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++){if(r[s]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,r[s]),i.push(t.COLOR_ATTACHMENT0+s),a){const e=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;i.push(e)}const n=e.textures[s],l=this.get(n);t.renderbufferStorageMultisample(t.RENDERBUFFER,o,l.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+s,t.RENDERBUFFER,r[s])}if(n.msaaFrameBuffer=m,n.msaaRenderbuffers=r,void 0===g){g=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(g,e,o),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.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();let i="",r=!0;t.bindVertexArray(s);for(let s=0;s<e.length;s++){const n=e[s],o=this.get(n);let a,h;i+=":"+o.id,t.bindBuffer(t.ARRAY_BUFFER,o.bufferGPU),t.enableVertexAttribArray(s),(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&(r=!1),!0===n.isInterleavedBufferAttribute?(a=n.data.stride*o.bytesPerElement,h=n.offset*o.bytesPerElement):(a=0,h=0),o.isInteger?t.vertexAttribIPointer(s,n.itemSize,o.type,a,h):t.vertexAttribPointer(s,n.itemSize,o.type,n.normalized,a,h),n.isInstancedBufferAttribute&&!n.isInterleavedBufferAttribute?t.vertexAttribDivisor(s,n.meshPerAttribute):n.isInterleavedBufferAttribute&&n.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(s,n.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),this.vaoCache[i]=s,{vaoGPU:s,staticVao:r}}_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)}}_useMultisampledRTT(e){return e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e.autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const Ex="point-list",Ax="line-list",Cx="line-strip",Rx="triangle-list",Px="triangle-strip",Fx="never",Bx="less",Ix="equal",Lx="less-equal",Dx="greater",Ox="not-equal",kx="greater-equal",Ux="always",zx="store",Vx="load",Gx="clear",jx="ccw",Hx="none",Wx="front",$x="back",qx="uint16",Xx="uint32",Yx="r8unorm",Kx="r8snorm",Qx="r8uint",Zx="r8sint",Jx="r16uint",e_="r16sint",t_="r16float",s_="rg8unorm",i_="rg8snorm",r_="rg8uint",n_="rg8sint",o_="r32uint",a_="r32sint",h_="r32float",l_="rg16uint",u_="rg16sint",c_="rg16float",d_="rgba8unorm",p_="rgba8unorm-srgb",m_="rgba8snorm",g_="rgba8uint",f_="rgba8sint",y_="bgra8unorm",b_="bgra8unorm-srgb",x_="rgb9e5ufloat",__="rgb10a2unorm",v_="rgb10a2unorm",T_="rg32uint",w_="rg32sint",S_="rg32float",M_="rgba16uint",N_="rgba16sint",E_="rgba16float",A_="rgba32uint",C_="rgba32sint",R_="rgba32float",P_="depth16unorm",F_="depth24plus",B_="depth24plus-stencil8",I_="depth32float",L_="depth32float-stencil8",D_="bc1-rgba-unorm",O_="bc1-rgba-unorm-srgb",k_="bc2-rgba-unorm",U_="bc2-rgba-unorm-srgb",z_="bc3-rgba-unorm",V_="bc3-rgba-unorm-srgb",G_="bc4-r-unorm",j_="bc4-r-snorm",H_="bc5-rg-unorm",W_="bc5-rg-snorm",$_="bc6h-rgb-ufloat",q_="bc6h-rgb-float",X_="bc7-rgba-unorm",Y_="bc7-rgba-srgb",K_="etc2-rgb8unorm",Q_="etc2-rgb8unorm-srgb",Z_="etc2-rgb8a1unorm",J_="etc2-rgb8a1unorm-srgb",ev="etc2-rgba8unorm",tv="etc2-rgba8unorm-srgb",sv="eac-r11unorm",iv="eac-r11snorm",rv="eac-rg11unorm",nv="eac-rg11snorm",ov="astc-4x4-unorm",av="astc-4x4-unorm-srgb",hv="astc-5x4-unorm",lv="astc-5x4-unorm-srgb",uv="astc-5x5-unorm",cv="astc-5x5-unorm-srgb",dv="astc-6x5-unorm",pv="astc-6x5-unorm-srgb",mv="astc-6x6-unorm",gv="astc-6x6-unorm-srgb",fv="astc-8x5-unorm",yv="astc-8x5-unorm-srgb",bv="astc-8x6-unorm",xv="astc-8x6-unorm-srgb",_v="astc-8x8-unorm",vv="astc-8x8-unorm-srgb",Tv="astc-10x5-unorm",wv="astc-10x5-unorm-srgb",Sv="astc-10x6-unorm",Mv="astc-10x6-unorm-srgb",Nv="astc-10x8-unorm",Ev="astc-10x8-unorm-srgb",Av="astc-10x10-unorm",Cv="astc-10x10-unorm-srgb",Rv="astc-12x10-unorm",Pv="astc-12x10-unorm-srgb",Fv="astc-12x12-unorm",Bv="astc-12x12-unorm-srgb",Iv="clamp-to-edge",Lv="repeat",Dv="mirror-repeat",Ov="linear",kv="nearest",Uv="zero",zv="one",Vv="src",Gv="one-minus-src",jv="src-alpha",Hv="one-minus-src-alpha",Wv="dst",$v="one-minus-dst",qv="dst-alpha",Xv="one-minus-dst-alpha",Yv="src-alpha-saturated",Kv="constant",Qv="one-minus-constant",Zv="add",Jv="subtract",eT="reverse-subtract",tT="min",sT="max",iT=0,rT=15,nT="keep",oT="zero",aT="replace",hT="invert",lT="increment-clamp",uT="decrement-clamp",cT="increment-wrap",dT="decrement-wrap",pT="storage",mT="read-only-storage",gT="write-only",fT="read-only",yT="read-write",bT="float",xT="unfilterable-float",_T="depth",vT="sint",TT="uint",wT="2d",ST="3d",MT="2d",NT="2d-array",ET="cube",AT="3d",CT="all",RT="vertex",PT="instance",FT={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class BT extends Vb{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class IT extends BT{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){this.texture=this.textureNode.value}}class LT extends Gb{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let DT=0;class OT extends LT{constructor(e,t){super("StorageBuffer_"+DT++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:on,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class kT extends dg{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:Ov}),this.flipYSampler=e.createSampler({minFilter:kv}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4<f32>,\n\t@location( 0 ) vTex : vec2<f32>\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( -1.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 ),\n\t\tvec2<f32>( -1.0, -1.0 ),\n\t\tvec2<f32>( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( 0.0, 0.0 ),\n\t\tvec2<f32>( 1.0, 0.0 ),\n\t\tvec2<f32>( 0.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:Px,stripIndexFormat:Xx},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:Px,stripIndexFormat:Xx},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,o=this.getTransferPipeline(i),a=this.getFlipYPipeline(i),h=this.device.createTexture({size:{width:r,height:n,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:MT,baseArrayLayer:s}),u=h.createView({baseMipLevel:0,mipLevelCount:1,dimension:MT,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),d=(e,t,s)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:s,loadOp:Gx,storeOp:zx,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,r),n.draw(4,1,0,0),n.end()};d(o,l,u),d(a,u,l),this.device.queue.submit([c.finish()]),h.destroy()}generateMipmaps(e,t,s=0){const i=this.get(e);void 0===i.useCount&&(i.useCount=0,i.layers=[]);const r=i.layers[s]||this._mipmapCreateBundles(e,t,s),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,r),this.device.queue.submit([n.finish()]),0!==i.useCount&&(i.layers[s]=r),i.useCount++}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),r=i.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:MT,baseArrayLayer:s});const o=[];for(let a=1;a<t.mipLevelCount;a++){const h=this.device.createBindGroup({layout:r,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:n}]}),l=e.createView({baseMipLevel:a,mipLevelCount:1,dimension:MT,baseArrayLayer:s}),u={colorAttachments:[{view:l,loadOp:Gx,storeOp:zx,clearValue:[0,0,0,0]}]},c=this.device.createRenderBundleEncoder({colorFormats:[t.format]});c.setPipeline(i),c.setBindGroup(0,h),c.draw(4,1,0,0),o.push({renderBundles:[c.finish()],passDescriptor:u}),n=l}return o}_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 UT={[Me]:"never",[Ne]:"less",[Ee]:"equal",[Ae]:"less-equal",[Ce]:"greater",[Pe]:"greater-equal",[Fe]:"always",[Re]:"not-equal"},zT=[0,1,3,2,4,5];class VT{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this.colorBuffer=null,this.depthTexture=new rr,this.depthTexture.name="depthBuffer"}createSampler(e){const t=this.backend,s=t.device,i=t.get(e),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};r.magFilter===Ov&&r.minFilter===Ov&&r.mipmapFilter===Ov&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&(r.compare=UT[e.compareFunction]),i.sampler=s.createSampler(r)}createDefaultTexture(e){let t;const s=GT(e);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(s):e.isVideoTexture?this.backend.get(e).externalTexture=this._getDefaultVideoFrame():t=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.");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:o,levels:a}=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||GT(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&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:r,height:n,depthOrArrayLayers:o},mipLevelCount:a,sampleCount:c,dimension:h,format:l,usage:p};if(e.isVideoTexture){const t=e.source.data,s=new VideoFrame(t);m.size.width=s.displayWidth,m.size.height=s.displayHeight,s.close(),i.externalTexture=t}else{if(void 0===l)return console.warn("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);i.texture=s.device.createTexture(m)}if(d){const e=Object.assign({},m);e.label=e.label+"-msaa",e.sampleCount=u,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e){const t=this.backend,s=t.get(e);void 0!==s.texture&&s.texture.destroy(),void 0!==s.msaaTexture&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else{const s=e.image.depth||1;for(let e=0;e<s;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e)}}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:s}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:s,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.samples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!1){const s=this.backend,{width:i,height:r}=s.getDrawingBufferSize(),n=this.depthTexture,o=s.get(n).texture;let a,h;if(t?(a=$,h=G):e&&(a=W,h=U),void 0!==o){if(n.image.width===i&&n.image.height===r&&n.format===a&&n.type===h)return o;this.destroyTexture(n)}return n.name="depthBuffer",n.format=a,n.type=h,n.image.width=i,n.image.height=r,this.createTexture(n,{width:i,height:r}),s.get(n).texture}updateTexture(e,t){const s=this.backend.get(e),{textureDescriptorGPU:i}=s;if(!e.isRenderTargetTexture&&void 0!==i){if(e.isDataTexture)this._copyBufferToTexture(t.image,s.texture,i,0,e.flipY);else if(e.isDataArrayTexture||e.isData3DTexture)for(let r=0;r<t.image.depth;r++)this._copyBufferToTexture(t.image,s.texture,i,r,e.flipY,r);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,s.texture,i);else if(e.isCubeTexture)this._copyCubeMapToTexture(t.images,s.texture,i,e.flipY);else if(e.isVideoTexture){const t=e.source.data;s.externalTexture=t}else this._copyImageToTexture(t.image,s.texture,i,0,e.flipY);s.version=e.version,e.onUpdate&&e.onUpdate(e)}}async copyTextureToBuffer(e,t,s,i,r,n){const o=this.backend.device,a=this.backend.get(e),h=a.texture,l=a.textureDescriptorGPU.format,u=this._getBytesPerTexel(l);let c=i*u;c=256*Math.ceil(c/256);const d=o.createBuffer({size:i*r*u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=o.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);o.queue.submit([p.finish()]),await d.mapAsync(GPUMapMode.READ);return new m(d.getMappedRange())}_isEnvironmentTexture(e){const t=e.mapping;return t===w||t===S||t===v||t===T}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const s=new mt;s.minFilter=A,s.magFilter=A,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.defaultTexture[e];if(void 0===t){const s=new Di;s.minFilter=A,s.magFilter=A,this.createTexture(s,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultVideoFrame(){let e=this.defaultVideoFrame;if(null===e){const t={timestamp:0,codedWidth:1,codedHeight:1,format:"RGBA"};this.defaultVideoFrame=e=new VideoFrame(new Uint8Array([0,0,0,255]),t)}return e}_copyCubeMapToTexture(e,t,s,i){for(let r=0;r<6;r++){const n=e[r],o=!0===i?zT[r]:r;n.isDataTexture?this._copyBufferToTexture(n.image,t,s,o,i):this._copyImageToTexture(n,t,s,o,i)}}_copyImageToTexture(e,t,s,i,r){this.backend.device.queue.copyExternalImageToTexture({source:e,flipY:r},{texture:t,mipLevel:0,origin:{x:0,y:0,z:i}},{width:e.width,height:e.height,depthOrArrayLayers:1})}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new kT(this.backend.device)),e}_generateMipmaps(e,t,s=0){this._getPassUtils().generateMipmaps(e,t,s)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,r,n=0){const o=this.backend.device,a=e.data,h=this._getBytesPerTexel(s.format),l=e.width*h;o.queue.writeTexture({texture:t,mipLevel:0,origin:{x:0,y:0,z:i}},a,{offset:e.width*e.height*h*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 o=0;o<e.length;o++){const a=e[o],h=a.width,l=a.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:o,origin:{x:0,y:0,z:e}},a.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===D_||e===O_?{byteLength:8,width:4,height:4}:e===k_||e===U_||e===z_||e===V_?{byteLength:16,width:4,height:4}:e===G_||e===j_?{byteLength:8,width:4,height:4}:e===H_||e===W_||e===$_||e===q_||e===X_||e===Y_?{byteLength:16,width:4,height:4}:e===K_||e===Q_||e===Z_||e===J_?{byteLength:8,width:4,height:4}:e===ev||e===tv?{byteLength:16,width:4,height:4}:e===sv||e===iv?{byteLength:8,width:4,height:4}:e===rv||e===nv||e===ov||e===av?{byteLength:16,width:4,height:4}:e===hv||e===lv?{byteLength:16,width:5,height:4}:e===uv||e===cv?{byteLength:16,width:5,height:5}:e===dv||e===pv?{byteLength:16,width:6,height:5}:e===mv||e===gv?{byteLength:16,width:6,height:6}:e===fv||e===yv?{byteLength:16,width:8,height:5}:e===bv||e===xv?{byteLength:16,width:8,height:6}:e===_v||e===vv?{byteLength:16,width:8,height:8}:e===Tv||e===wv?{byteLength:16,width:10,height:5}:e===Sv||e===Mv?{byteLength:16,width:10,height:6}:e===Nv||e===Ev?{byteLength:16,width:10,height:8}:e===Av||e===Cv?{byteLength:16,width:10,height:10}:e===Rv||e===Pv?{byteLength:16,width:12,height:10}:e===Fv||e===Bv?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=Iv;return e===M?t=Lv:e===E&&(t=Dv),t}_convertFilterMode(e){let t=Ov;return e!==A&&1004!==e&&e!==R||(t=kv),t}_getBytesPerTexel(e){return e===Yx||e===Kx||e===Qx||e===Zx?1:e===Jx||e===e_||e===t_||e===s_||e===i_||e===r_||e===n_?2:e===o_||e===a_||e===h_||e===l_||e===u_||e===c_||e===d_||e===p_||e===m_||e===g_||e===f_||e===y_||e===b_||e===x_||e===__||e===v_||e===I_||e===F_||e===B_||e===L_?4:e===T_||e===w_||e===S_||e===M_||e===N_||e===E_?8:e===A_||e===C_||e===R_?16:void 0}_getTypedArrayType(e){return e===Qx?Uint8Array:e===Zx?Int8Array:e===Yx?Uint8Array:e===Kx?Int8Array:e===r_?Uint8Array:e===n_?Int8Array:e===s_?Uint8Array:e===i_?Int8Array:e===g_?Uint8Array:e===f_?Int8Array:e===d_?Uint8Array:e===m_?Int8Array:e===Jx?Uint16Array:e===e_?Int16Array:e===l_?Uint16Array:e===u_?Int16Array:e===M_?Uint16Array:e===N_?Int16Array:e===t_||e===c_||e===E_?Uint16Array:e===o_?Uint32Array:e===a_?Int32Array:e===h_?Float32Array:e===T_?Uint32Array:e===w_?Int32Array:e===S_?Float32Array:e===A_?Uint32Array:e===C_?Int32Array:e===R_?Float32Array:e===y_||e===b_?Uint8Array:e===__||e===x_||e===v_?Uint32Array:e===I_?Float32Array:e===F_||e===B_?Uint32Array:e===L_?Float32Array:void 0}_getDimension(e){let t;return t=e.isData3DTexture?ST:wT,t}}function GT(e,t=null){const s=e.format,i=e.type,r=e.colorSpace;let n;if(!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(s){case J:n=r===_e?O_:D_;break;case ee:n=r===_e?U_:k_;break;case te:n=r===_e?V_:z_;break;case se:n=r===_e?Q_:K_;break;case ie:n=r===_e?tv:ev;break;case re:n=r===_e?av:ov;break;case ne:n=r===_e?lv:hv;break;case oe:n=r===_e?cv:uv;break;case ae:n=r===_e?pv:dv;break;case he:n=r===_e?gv:mv;break;case le:n=r===_e?yv:fv;break;case ue:n=r===_e?xv:bv;break;case ce:n=r===_e?vv:_v;break;case de:n=r===_e?wv:Tv;break;case pe:n=r===_e?Mv:Sv;break;case me:n=r===_e?Ev:Nv;break;case ge:n=r===_e?Cv:Av;break;case fe:n=r===_e?Pv:Rv;break;case ye:n=r===_e?Bv:Fv;break;case H:n=r===_e?p_:d_;break;default:console.error("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case H:switch(i){case L:n=m_;break;case D:n=N_;break;case O:n=M_;break;case U:n=A_;break;case k:n=C_;break;case I:n=r===_e?p_:d_;break;case V:n=E_;break;case z:n=R_;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case j:if(35902===i)n=x_;else console.error("WebGPURenderer: Unsupported texture type with RGBFormat.",i);break;case q:switch(i){case L:n=Kx;break;case D:n=e_;break;case O:n=Jx;break;case U:n=o_;break;case k:n=a_;break;case I:n=Yx;break;case V:n=t_;break;case z:n=h_;break;default:console.error("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case Y:switch(i){case L:n=i_;break;case D:n=u_;break;case O:n=l_;break;case U:n=T_;break;case k:n=w_;break;case I:n=s_;break;case V:n=c_;break;case z:n=S_;break;default:console.error("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case W:switch(i){case O:n=P_;break;case U:n=F_;break;case z:n=I_;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case $:switch(i){case G:n=B_;break;case z:t&&!1===t.features.has(FT.Depth32FloatStencil8)&&console.error('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),n=L_;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case X:switch(i){case k:n=a_;break;case U:n=o_;break;default:console.error("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case K:switch(i){case k:n=w_;break;case U:n=T_;break;default:console.error("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case Q:switch(i){case k:n=C_;break;case U:n=A_;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:console.error("WebGPURenderer: Unsupported texture format.",s)}return n}const jT=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,HT=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,WT={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_multisampled_2d:"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 $T extends nb{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:o}=(e=>{const t=(e=e.trim()).match(jT);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=HT.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=WT[r]),n.push(new qy(r,t))}const o=e.substring(t[0].length),a=t[3]||"void",h=void 0!==t[1]?t[1]:"";return{type:WT[a]||a,inputs:n,name:h,inputsCode:s,blockCode:o,outputType:a}}throw new Error("FunctionNode: Function is not a WGSL code.")})(e);super(t,s,i),this.inputsCode=r,this.blockCode=n,this.outputType=o}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class qT extends rb{parseFunction(e){return new $T(e)}}const XT="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},YT={[rn]:"read",[nn]:"write",[on]:"read_write"},KT={[M]:"repeat",[N]:"clamp",[E]:"mirror"},QT={vertex:XT?XT.VERTEX:1,fragment:XT?XT.FRAGMENT:2,compute:XT?XT.COMPUTE:4},ZT={instance:!0,swizzleAssign:!1,storageBuffer:!0},JT={"^^":"tsl_xor"},ew={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>"},tw={},sw={tsl_xor:new vf("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new vf("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new vf("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new vf("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new vf("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new vf("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new vf("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new vf("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 vf("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 vf("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new vf("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 vf("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new vf("\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")},iw={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>"};"undefined"!=typeof navigator&&/Windows/g.test(navigator.userAgent)&&(sw.pow_float=new vf("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),sw.pow_vec2=new vf("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[sw.pow_float]),sw.pow_vec3=new vf("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[sw.pow_float]),sw.pow_vec4=new vf("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[sw.pow_float]),iw.pow_float="tsl_pow_float",iw.pow_vec2="tsl_pow_vec2",iw.pow_vec3="tsl_pow_vec3",iw.pow_vec4="tsl_pow_vec4");let rw="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(rw+="diagnostic( off, derivative_uniformity );\n");class nw extends Wy{constructor(e,t){super(e,t,new qT),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==xe}_generateTextureSample(e,t,s,i,r=this.shaderStage){return"fragment"===r?i?`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s):this.generateTextureLod(e,t,s,i,"0")}_generateVideoSample(e,t,s=this.shaderStage){if("fragment"===s)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2<f32>( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${s} shader.`)}_generateTextureSampleLevel(e,t,s,i,r,n=this.shaderStage){return"fragment"!==n&&"compute"!==n||!1!==this.isUnfilterable(e)?this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,i):this.generateTextureLod(e,t,s,r,i):`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`}generateWrapFunction(e){const t=`tsl_coord_${KT[e.wrapS]}S_${KT[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let s=tw[t];if(void 0===s){const i=[],r=e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const o=(e,t)=>{e===M?(i.push(sw.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===N?(i.push(sw.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===E?(i.push(sw.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};o(e.wrapS,"x"),n+=",\n",o(e.wrapT,"y"),e.isData3DTexture&&(n+=",\n",o(e.wrapR,"z")),n+="\n\t);\n\n}\n",tw[t]=s=new vf(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,o;const{primarySamples:a}=this.renderer.backend.utils.getTextureSampleData(e),h=a>1;o=e.isData3DTexture?"vec3<u32>":"vec2<u32>",n=h||e.isVideoTexture||e.isStorageTexture?t:`${t}${s?`, u32( ${s} )`:""}`,r=new jh(new fl(`textureDimensions( ${n} )`,o)),i.dimensionsSnippet[s]=r,(e.isDataArrayTexture||e.isData3DTexture)&&(i.arrayLayerCount=new jh(new fl(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new jh(new fl("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,s,i="0u"){this._include("biquadraticTexture");return`tsl_biquadraticTexture( ${t}, ${this.generateWrapFunction(e)}( ${s} ), ${this.generateTextureDimension(e,t,i)}, u32( ${i} ) )`}generateTextureLod(e,t,s,i,r="0u"){const n=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r),a=e.isData3DTexture?"vec3":"vec2",h=`${a}<u32>(${n}(${s}) * ${a}<f32>(${o}))`;return this.generateTextureLoad(e,t,h,i,r)}generateTextureLoad(e,t,s,i,r="0u"){return!0===e.isVideoTexture||!0===e.isStorageTexture?`textureLoad( ${t}, ${s} )`:i?`textureLoad( ${t}, ${s}, ${i}, u32( ${r} ) )`:`textureLoad( ${t}, ${s}, u32( ${r} ) )`}generateTextureStore(e,t,s,i){return`textureStore( ${t}, ${s}, ${i} )`}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===z||!1===this.isSampleCompare(e)&&e.minFilter===A&&e.magFilter===A||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,s,i,r=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,s,r):this.isUnfilterable(e)?this.generateTextureLod(e,t,s,i,"0",r):this._generateTextureSample(e,t,s,i,r),n}generateTextureGrad(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${n} shader.`)}generateTextureCompare(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} shader.`)}generateTextureLevel(e,t,s,i,r,n=this.shaderStage){let o=null;return o=!0===e.isVideoTexture?this._generateVideoSample(t,s,n):this._generateTextureSampleLevel(e,t,s,i,r,n),o}generateTextureBias(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${n} 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||"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=JT[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?rn:e.access}getStorageAccess(e,t){return YT[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 o;const a=e.groupNode,h=a.name,l=this.getBindGroupArray(h,s);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const n=this.getNodeAccess(e,s);if("texture"===t||"storageTexture"===t?i=new Qb(r.name,r.node,a,n):"cubeTexture"===t?i=new Zb(r.name,r.node,a,n):"texture3D"===t&&(i=new Jb(r.name,r.node,a,n)),i.store=!0===e.isStorageTextureNode,i.setVisibility(QT[s]),"fragment"!==s&&"compute"!==s||!1!==this.isUnfilterable(e.value)||!1!==i.store)l.push(i),o=[i];else{const e=new IT(`${r.name}_sampler`,r.node,a);e.setVisibility(QT[s]),l.push(e,i),o=[e,i]}}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=new("buffer"===t?Wb:OT)(e,a);n.setVisibility(QT[s]),l.push(n),o=n,r.name=i||"NodeBuffer_"+r.id}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let i=e[h];void 0===i&&(i=new Xb(h,a),i.setVisibility(QT[s]),e[h]=i,l.push(i)),o=this.getNodeUniform(r,t),i.addUniform(o)}n.uniformGPU=o}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","Vertex","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} )`;/^(int|uint|ivec|uvec)/.test(n.type)&&(e+=" @interpolate( flat )"),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){return e.value.isStorageBufferAttribute&&null!==e.node.structTypeNode}getUniforms(e){const t=this.uniforms[e],s=[],i=[],r=[],n={};for(const r of t){const t=r.groupNode.name,o=this.bindingsIndexes[t];if("texture"===r.type||"cubeTexture"===r.type||"storageTexture"===r.type||"texture3D"===r.type){const t=r.node.value;let i;"fragment"!==e&&"compute"!==e||!1!==this.isUnfilterable(t)||!0===r.node.isStorageTextureNode||(this.isSampleCompare(t)?s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name}_sampler : sampler_comparison;`):s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name}_sampler : sampler;`));let n="";const{primarySamples:a}=this.renderer.backend.utils.getTextureSampleData(t);if(a>1&&(n="_multisampled"),!0===t.isCubeTexture)i="texture_cube<f32>";else if(!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array<f32>";else if(!0===t.isDepthTexture)i=`texture_depth${n}_2d`;else if(!0===t.isVideoTexture)i="texture_external";else if(!0===t.isData3DTexture)i="texture_3d<f32>";else if(!0===r.node.isStorageTextureNode){i=`texture_storage_2d<${GT(t)}, ${this.getStorageAccess(r.node,e)}>`}else{i=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.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,a=n>0&&"buffer"===r.type?", "+n:"",h=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(r))i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${h}> ${r.name} : ${s};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${s}>`:`${s}`}${a} >`;i.push(this._getWGSLStructBinding(r.name,e,h,o.binding++,o.group))}}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(n[t]||(n[t]={index:o.binding++,id:o.group,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}}for(const e in n){const t=n[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let o=s.join("\n");return o+=i.join("\n"),o+=r.join("\n"),o}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],o=n.outputNode,a=void 0!==o&&!0===o.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.Vertex = ${r.result};`;else if("fragment"===t)if(a)s.returnType=o.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}this.shaderStage=null,null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getType(e){return ew[e]||e}isAvailable(e){let t=ZT[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),ZT[e]=t),t}_getWGSLMethod(e){return void 0!==sw[e]&&this._include(e),iw[e]}_include(e){const t=sw[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(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${rw}\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){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( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\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 ow{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=B_:e.depth&&(t=F_),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.samples}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}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?Ex:e.isLineSegments||e.isMesh&&!0===t.wireframe?Ax:e.isLine?Cx:e.isMesh?Rx:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===I)return y_;if(e===V)return E_;throw new Error("Unsupported outputType")}}const aw=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),hw=new Map([[ii,["float16"]]]),lw=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class uw{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 o=i.device;let a=s.array;if(!1===e.normalized)if(a.constructor===Int16Array||a.constructor===Int8Array)a=new Int32Array(a);else if((a.constructor===Uint16Array||a.constructor===Uint8Array)&&(a=new Uint32Array(a),t&GPUBufferUsage.INDEX))for(let e=0;e<a.length;e++)65535===a[e]&&(a[e]=4294967295);if(s.array=a,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&3===s.itemSize){a=new a.constructor(4*s.count);for(let e=0;e<s.count;e++)a.set(s.array.subarray(3*e,3*e+3),4*e);s.itemSize=4,s.array=a,r._force3to4BytesAlignment=!0}const h=a.byteLength+(4-a.byteLength%4)%4;n=o.createBuffer({label:s.name,size:h,usage:t,mappedAtCreation:!0}),new a.constructor(n.getMappedRange()).set(a),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 o=t.array;if(!0===r._force3to4BytesAlignment){o=new o.constructor(4*t.count);for(let e=0;e<t.count;e++)o.set(t.array.subarray(3*e,3*e+3),4*e);t.array=o}const a=this._isTypedArray(o),h=t.updateRanges;if(0===h.length)i.queue.writeBuffer(n,0,o,0);else{const e=a?1:o.BYTES_PER_ELEMENT;for(let t=0,s=h.length;t<s;t++){const s=h[t];let l,u;if(!0===r._force3to4BytesAlignment){l=4*Math.floor(s.start/3)*e,u=4*Math.ceil(s.count/3)*e}else l=s.start*e,u=s.count*e;const c=l*(a?o.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(n,c,o,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 o=s.get(n);if(void 0===o){let e,t;!0===i.isInterleavedBufferAttribute?(e=i.data.stride*r,t=i.data.isInstancedInterleavedBuffer?PT:RT):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?PT:RT),!1!==i.normalized||i.array.constructor!==Int16Array&&i.array.constructor!==Uint16Array||(e=4),o={arrayStride:e,attributes:[],stepMode:t},s.set(n,o)}const a=this._getVertexFormat(i),h=!0===i.isInterleavedBufferAttribute?i.offset*r:0;o.attributes.push({shaderLocation:e,offset:h,format:a})}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}),o=s.createCommandEncoder({label:`readback_encoder_${e.name}`});o.copyBufferToBuffer(i,0,n,0,r);const a=o.finish();s.queue.submit([a]),await n.mapAsync(GPUMapMode.READ);const h=n.getMappedRange(),l=new e.array.constructor(h.slice(0));return n.unmap(),l.buffer}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,r=e.constructor;let n;if(1===t)n=lw.get(i);else{const e=(hw.get(r)||aw.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||console.error("THREE.WebGPUAttributeUtils: Vertex format not supported yet."),n}_isTypedArray(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class cw{constructor(e){this.backend=e,this.bindGroupLayoutCache=new WeakMap}createBindingsLayout(e){const t=this.backend,s=t.device,i=[];let r=0;for(const s of e.bindings){const e={binding:r++,visibility:s.visibility};if(s.isUniformBuffer||s.isStorageBuffer){const t={};s.isStorageBuffer&&(4&s.visibility&&(s.access===on||s.access===nn)?t.type=pT:t.type=mT),e.buffer=t}else if(s.isSampler){const t={};s.texture.isDepthTexture&&null!==s.texture.compareFunction&&(t.type="comparison"),e.sampler=t}else if(s.isSampledTexture&&s.texture.isVideoTexture)e.externalTexture={};else if(s.isSampledTexture&&s.store){const t={};t.format=this.backend.get(s.texture).texture.format;const i=s.access;t.access=i===on?yT:i===nn?gT:fT,e.storageTexture=t}else if(s.isSampledTexture){const i={},{primarySamples:r}=t.utils.getTextureSampleData(s.texture);if(r>1&&(i.multisampled=!0,s.texture.isDepthTexture||(i.sampleType=xT)),s.texture.isDepthTexture)i.sampleType=_T;else if(s.texture.isDataTexture||s.texture.isDataArrayTexture||s.texture.isData3DTexture){const e=s.texture.type;e===k?i.sampleType=vT:e===U?i.sampleType=TT:e===z&&(this.backend.hasFeature("float32-filterable")?i.sampleType=bT:i.sampleType=xT)}s.isSampledCubeTexture?i.viewDimension=ET:s.texture.isDataArrayTexture||s.texture.isCompressedArrayTexture?i.viewDimension=NT:s.isSampledTexture3D&&(i.viewDimension=AT),e.texture=i}else console.error(`WebGPUBindingUtils: Unsupported binding "${s}".`);i.push(e)}return s.createBindGroupLayout({entries:i})}createBindings(e,t,s,i=0){const{backend:r,bindGroupLayoutCache:n}=this,o=r.get(e);let a,h=n.get(e.bindingsReference);void 0===h&&(h=this.createBindingsLayout(e),n.set(e.bindingsReference,h)),s>0&&(void 0===o.groups&&(o.groups=[],o.versions=[]),o.versions[s]===i&&(a=o.groups[s])),void 0===a&&(a=this.createBindGroup(e,h),s>0&&(o.groups[s]=a,o.versions[s]=i)),o.group=a,o.layout=h}updateBinding(e){const t=this.backend,s=t.device,i=e.buffer,r=t.get(e).buffer;s.queue.writeBuffer(r,0,i,0)}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 o=[{binding:0,resource:{buffer:n}}];return s.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:o})}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=i.createBuffer({label:"bindingBuffer_"+t.name,size:s,usage:r});e.buffer=n}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=s.get(t);if(void 0===e.buffer){const i=t.attribute;e.buffer=s.get(i).buffer}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isSampler){const e=s.get(t.texture);n.push({binding:r,resource:e.sampler})}else if(t.isSampledTexture){const e=s.get(t.texture);let o;if(void 0!==e.externalTexture)o=i.importExternalTexture({source:e.externalTexture});else{const s=t.store?1:e.texture.mipLevelCount,i=`view-${e.texture.width}-${e.texture.height}-${s}`;if(o=e[i],void 0===o){const r=CT;let n;n=t.isSampledCubeTexture?ET:t.isSampledTexture3D?AT:t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?NT:MT,o=e[i]=e.texture.createView({aspect:r,dimension:n,mipLevelCount:s})}}n.push({binding:r,resource:o})}r++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}}class dw{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:s,material:i,geometry:r,pipeline:n}=e,{vertexProgram:o,fragmentProgram:a}=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);d.push(e.layout)}const p=h.attributeUtils.createShaderVertexBuffers(e);let m;!0===i.transparent&&0!==i.blending&&(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;for(let e=0;e<t.length;e++){const s=u.getTextureFormatGPU(t[e]);y.push({format:s,blend:m,writeMask:f})}}else{const t=u.getCurrentColorFormat(e.context);y.push({format:t,blend:m,writeMask:f})}const b=h.get(o).module,x=h.get(a).module,_=this._getPrimitiveState(s,r,i),v=this._getDepthCompare(i),T=u.getCurrentDepthStencilFormat(e.context),w=this._getSampleCount(e.context),S={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},b,{buffers:p}),fragment:Object.assign({},x,{targets:y}),primitive:_,multisample:{count:w,alphaToCoverageEnabled:i.alphaToCoverage&&w>1},layout:l.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={},M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(M.depthBias=i.polygonOffsetUnits,M.depthBiasSlopeScale=i.polygonOffsetFactor,M.depthBiasClamp=0),S.depthStencil=M),null===t)c.pipeline=l.createRenderPipeline(S);else{const e=new Promise((e=>{l.createRenderPipelineAsync(S).then((t=>{c.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e){const t=this.backend,{utils:s,device:i}=t,r=s.getCurrentDepthStencilFormat(e),n={label:"renderBundleEncoder",colorFormats:[s.getCurrentColorFormat(e)],depthStencilFormat:r,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(n)}createComputePipeline(e,t){const s=this.backend,i=s.device,r=s.get(e.computeProgram).module,n=s.get(e),o=[];for(const e of t){const t=s.get(e);o.push(t.layout)}n.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:o})})}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,o=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,a=null!==e.blendDstAlpha?e.blendDstAlpha:n,h=null!==e.blendEquationAlpha?e.blendEquationAlpha:o;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(o)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(h)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:Zv},s={srcFactor:r,dstFactor:n,operation:Zv}};if(e.premultipliedAlpha)switch(i){case 1:r(zv,Hv,zv,Hv);break;case 2:r(zv,zv,zv,zv);break;case 3:r(Uv,Gv,Uv,zv);break;case 4:r(Uv,Vv,Uv,jv)}else switch(i){case 1:r(jv,Hv,zv,Hv);break;case 2:r(jv,zv,jv,zv);break;case 3:r(Uv,Gv,Uv,zv);break;case 4:r(Uv,Vv,Uv,Vv)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case u:t=Uv;break;case 201:t=zv;break;case 202:t=Vv;break;case 203:t=Gv;break;case m:t=jv;break;case g:t=Hv;break;case 208:t=Wv;break;case 209:t=$v;break;case 206:t=qv;break;case 207:t=Xv;break;case 210:t=Yv;break;case 211:t=Kv;break;case 212:t=Qv;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=Fx;break;case 519:t=Ux;break;case 513:t=Bx;break;case 515:t=Lx;break;case 514:t=Ix;break;case 518:t=kx;break;case 516:t=Dx;break;case 517:t=Ox;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case Se:t=nT;break;case 0:t=oT;break;case 7681:t=aT;break;case 5386:t=hT;break;case 7682:t=lT;break;case 7683:t=uT;break;case 34055:t=cT;break;case 34056:t=dT;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case a:t=Zv;break;case 101:t=Jv;break;case 102:t=eT;break;case 103:t=tT;break;case 104:t=sT;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},r=this.backend.utils;switch(i.topology=r.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?qx:Xx),s.side){case 0:i.frontFace=jx,i.cullMode=$x;break;case 1:i.frontFace=jx,i.cullMode=Wx;break;case 2:i.frontFace=jx,i.cullMode=Hx;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side)}return i}_getColorWriteMask(e){return!0===e.colorWrite?rT:iT}_getDepthCompare(e){let t;if(!1===e.depthTest)t=Ux;else{const s=e.depthFunc;switch(s){case 0:t=Fx;break;case 1:t=Ux;break;case 2:t=Bx;break;case 3:t=Lx;break;case 4:t=Ix;break;case 5:t=kx;break;case 6:t=Dx;break;case 7:t=Ox;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class pw extends Sx{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 tt(`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.id,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));let o=0;for(const[,t]of e){const e=n[t],s=n[t+1];o+=Number(s-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=o,o}catch(e){return console.error("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){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("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 mw extends ax{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.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new ow(this),this.attributeUtils=new uw(this),this.bindingUtils=new cw(this),this.pipelineUtils=new dw(this),this.textureUtils=new VT(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference},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(FT),n=[];for(const e of r)i.features.has(e)&&n.push(e);const o={requiredFeatures:n,requiredLimits:t.requiredLimits};s=await i.requestDevice(o)}else s=t.device;s.lost.then((t=>{const s={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(s)}));const i=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=s,this.context=i;const r=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(FT.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r}),this.updateSize()}get coordinateSystem(){return De}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const s=e.colorAttachments[0];this.renderer.samples>0?s.view=this.colorBuffer.createView():s.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_getRenderPassDescriptor(e,t={}){const s=e.renderTarget,i=this.get(s);let r=i.descriptors;if(void 0===r||i.width!==s.width||i.height!==s.height||i.dimensions!==s.dimensions||i.activeMipmapLevel!==e.activeMipmapLevel||i.activeCubeFace!==e.activeCubeFace||i.samples!==s.samples){r={},i.descriptors=r;const e=()=>{s.removeEventListener("dispose",e),this.delete(s)};!1===s.hasEventListener("dispose",e)&&s.addEventListener("dispose",e)}const n=e.getCacheKey();let o=r[n];if(void 0===o){const t=e.textures,a=[];let h;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:MT};s.isRenderTarget3D?(h=e.activeCubeFace,n.baseArrayLayer=0,n.dimension=AT,n.depthOrArrayLayers=t[i].image.depth):s.isRenderTargetArray&&(n.dimension=NT,n.depthOrArrayLayers=t[i].image.depth);const o=r.texture.createView(n);let l,u;void 0!==r.msaaTexture?(l=r.msaaTexture.createView(),u=o):(l=o,u=void 0),a.push({view:l,resolveTarget:u,depthSlice:h})}if(o={textureViews:a},e.depth){const t=this.get(e.depthTexture);o.depthStencilView=t.texture.createView()}r[n]=o,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace,i.dimensions=s.dimensions}const a={colorAttachments:[]};for(let e=0;e<o.textureViews.length;e++){const s=o.textureViews[e];let i={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(i=t.clearValue),a.colorAttachments.push({view:s.view,depthSlice:s.depthSlice,resolveTarget:s.resolveTarget,loadOp:t.loadOp||Vx,storeOp:t.storeOp||zx,clearValue:i})}return o.depthStencilView&&(a.depthStencilAttachment={view:o.depthStencilView}),a}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:Vx}),this.initTimestampQuery(e,n),n.occlusionQuerySet=r;const o=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=Gx,i.storeOp=zx):(i.loadOp=Vx,i.storeOp=zx)}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=Gx,t.storeOp=zx):(t.loadOp=Vx,t.storeOp=zx)}e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=Gx,o.depthStoreOp=zx):(o.depthLoadOp=Vx,o.depthStoreOp=zx)),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=Gx,o.stencilStoreOp=zx):(o.stencilLoadOp=Vx,o.stencilStoreOp=zx));const a=s.createCommandEncoder({label:"renderContext_"+e.id}),h=a.beginRenderPass(n);if(t.descriptor=n,t.encoder=a,t.currentPass=h,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[],e.viewport&&this.updateViewport(e),e.scissor){const{x:t,y:s,width:i,height:r}=e.scissorValue;h.setScissorRect(t,s,i,r)}}finishRender(e){const t=this.get(e),s=e.occlusionQueryCount;if(t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),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:o,maxDepth:a}=e.viewportValue;t.setViewport(s,i,r,n,o,a)}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 o,a,h,l,u=[];if(e){const e=this.getClearColor();a={r:e.r,g:e.g,b:e.b,a:e.a}}if(null===i){h=n.depth,l=n.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){u=t.colorAttachments;const e=u[0];e.clearValue=a,e.loadOp=Gx,e.storeOp=zx}(h||l)&&(o=t.depthStencilAttachment)}else{h=i.depth,l=i.stencil;const r={loadOp:e?Gx:Vx,clearValue:e?a:void 0};h&&(r.depthLoadOp=t?Gx:Vx,r.depthClearValue=t?n.getClearDepth():void 0,r.depthStoreOp=zx),l&&(r.stencilLoadOp=s?Gx:Vx,r.stencilClearValue=s?n.getClearStencil():void 0,r.stencilStoreOp=zx);const c=this._getRenderPassDescriptor(i,r);u=c.colorAttachments,o=c.depthStencilAttachment}h&&o&&void 0===o.depthLoadOp&&(t?(o.depthLoadOp=Gx,o.depthClearValue=n.getClearDepth(),o.depthStoreOp=zx):(o.depthLoadOp=Vx,o.depthStoreOp=zx)),l&&o&&void 0===o.stencilLoadOp&&(s?(o.stencilLoadOp=Gx,o.stencilClearValue=n.getClearStencil(),o.stencilStoreOp=zx):(o.stencilLoadOp=Vx,o.stencilStoreOp=zx));const c=r.createCommandEncoder({label:"clear"});c.beginRenderPass({colorAttachments:u,depthStencilAttachment:o}).end(),r.queue.submit([c.finish()])}beginCompute(e){const t=this.get(e),s={label:"computeGroup_"+e.id};this.initTimestampQuery(e,s),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(s)}compute(e,t,s,i){const{passEncoderGPU:r}=this.get(e),n=this.get(i).pipeline;r.setPipeline(n);for(let e=0,t=s.length;e<t;e++){const t=s[e],i=this.get(t);r.setBindGroup(e,i.group)}const o=this.device.limits.maxComputeWorkgroupsPerDimension,a=this.get(t);void 0===a.dispatchSize&&(a.dispatchSize={x:0,y:1,z:1});const{dispatchSize:h}=a;t.dispatchCount>o?(h.x=Math.min(t.dispatchCount,o),h.y=Math.ceil(t.dispatchCount/o)):h.x=t.dispatchCount,r.dispatchWorkgroups(h.x,h.y,h.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:s,material:i,context:r,pipeline:n}=e,o=e.getBindings(),a=this.get(r),h=this.get(n).pipeline,l=a.currentSets,u=a.currentPass,c=e.getDrawParameters();if(null===c)return;l.pipeline!==h&&(u.setPipeline(h),l.pipeline=h);const d=l.bindingGroups;for(let e=0,t=o.length;e<t;e++){const t=o[e],s=this.get(t);d[t.index]!==t.id&&(u.setBindGroup(t.index,s.group),d[t.index]=t.id)}const p=e.getIndex(),m=null!==p;if(!0===m&&l.index!==p){const e=this.get(p).buffer,t=p.array instanceof Uint16Array?qx:Xx;u.setIndexBuffer(e,t),l.index=p}const g=e.getVertexBuffers();for(let e=0,t=g.length;e<t;e++){const t=g[e];if(l.attributes[e]!==t){const s=this.get(t).buffer;u.setVertexBuffer(e,s),l.attributes[e]=t}}if(void 0!==a.occlusionQuerySet){const e=a.lastOcclusionObject;e!==s&&(null!==e&&!0===e.occlusionTest&&(u.endOcclusionQuery(),a.occlusionQueryIndex++),!0===s.occlusionTest&&(u.beginOcclusionQuery(a.occlusionQueryIndex),a.occlusionQueryObjects[a.occlusionQueryIndex]=s),a.lastOcclusionObject=s)}!0===r.stencil&&!0===i.stencilWrite&&a.currentStencilRef!==i.stencilRef&&(u.setStencilReference(i.stencilRef),a.currentStencilRef=i.stencilRef);const f=()=>{if(!0===s.isBatchedMesh){const e=s._multiDrawStarts,i=s._multiDrawCounts,r=s._multiDrawCount,n=s._multiDrawInstances;null!==n&&tt("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o<r;o++){const r=n?n[o]:1,a=r>1?0:o;!0===m?u.drawIndexed(i[o],r,e[o]/p.array.BYTES_PER_ELEMENT,0,a):u.draw(i[o],r,e[o],a),t.update(s,i[o],r)}}else if(!0===m){const{vertexCount:i,instanceCount:r,firstVertex:n}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;u.drawIndexedIndirect(e,0)}else u.drawIndexed(i,r,n,0,0);t.update(s,i,r)}else{const{vertexCount:i,instanceCount:r,firstVertex:n}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;u.drawIndirect(e,0)}else u.draw(i,r,n,0);t.update(s,i,r)}};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 i=this.bindingUtils.createBindGroupIndex(r,e.layout);s.push(i)}t.indexesGPU=s}const o=this.renderer.getPixelRatio();for(let e=0,a=i.length;e<a;e++){const a=i[e];if(s.layers.test(a.layers)){const s=a.viewport;u.setViewport(Math.floor(s.x*o),Math.floor(s.y*o),Math.floor(s.width*o),Math.floor(s.height*o),r.viewportValue.minDepth,r.viewportValue.maxDepth),u.setBindGroup(n.index,t.indexesGPU[e]),f()}}}else f()}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),o=r.getCurrentColorSpace(e.context),a=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===o&&t.colorFormat===a&&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=o,t.colorFormat=a,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;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,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,s),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}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){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const s=e.isComputeNode?"compute":"render";this.timestampQueryPool[s]||(this.timestampQueryPool[s]=new pw(this.device,s,2048));const i=this.timestampQueryPool[s],r=i.allocateQueriesForContext(e);t.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:r,endOfPassWriteIndex:r+1}}createNodeBuilder(e,t){return new nw(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)}createIndexAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}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.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){let o=0,a=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&&(o=i.x,a=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:o,y:a,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 console.error("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,n.format);let o;if(i.currentPass?(i.currentPass.end(),o=i.encoder):o=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),o.copyTextureToTexture({texture:r,origin:[s.x,s.y,0]},{texture:n},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=Vx;if(t.depth&&(e.depthStencilAttachment.depthLoadOp=Vx),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=Vx),i.currentPass=o.beginRenderPass(e),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor){const{x:e,y:s,width:r,height:n}=t.scissorValue;i.currentPass.setScissorRect(e,s,r,n)}}else this.device.queue.submit([o.finish()])}}class gw extends Sr{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 fw extends _b{constructor(){super(),this.addMaterial(Jd,"MeshPhongMaterial"),this.addMaterial(zm,"MeshStandardMaterial"),this.addMaterial(Gm,"MeshPhysicalMaterial"),this.addMaterial($m,"MeshToonMaterial"),this.addMaterial(Hd,"MeshBasicMaterial"),this.addMaterial(Qd,"MeshLambertMaterial"),this.addMaterial(Rd,"MeshNormalMaterial"),this.addMaterial(Km,"MeshMatcapMaterial"),this.addMaterial(Nd,"LineBasicMaterial"),this.addMaterial(Ad,"LineDashedMaterial"),this.addMaterial(sg,"PointsMaterial"),this.addMaterial(eg,"SpriteMaterial"),this.addMaterial(ng,"ShadowMaterial"),this.addLight(uy,Cr),this.addLight(Xy,Fr),this.addLight(Zy,Ir),this.addLight(Jy,Sr),this.addLight(tb,Br),this.addLight(sb,br),this.addLight(ib,Dr),this.addLight(eb,gw),this.addToneMapping(cf,1),this.addToneMapping(df,2),this.addToneMapping(pf,3),this.addToneMapping(gf,4),this.addToneMapping(xf,6),this.addToneMapping(_f,7)}}class yw extends zb{constructor(e={}){let t;e.forceWebGL?t=Nx:(t=mw,e.getFallback=()=>(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new Nx(e)));super(new t(e),e),this.library=new fw,this.isWebGPURenderer=!0}}const bw={type:"change"},xw={type:"start"},_w={type:"end"},vw=1e-6,Tw=-1,ww=0,Sw=1,Mw=2,Nw=3,Ew=4,Aw=new e.Vector2,Cw=new e.Vector2,Rw=new e.Vector3,Pw=new e.Vector3,Fw=new e.Vector3,Bw=new e.Quaternion,Iw=new e.Vector3,Lw=new e.Vector3,Dw=new e.Vector3,Ow=new e.Vector3;class kw 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=Tw,this.keyState=Tw,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=zw.bind(this),this._onPointerDown=Uw.bind(this),this._onPointerUp=Vw.bind(this),this._onPointerCancel=Gw.bind(this),this._onContextMenu=Yw.bind(this),this._onMouseWheel=Xw.bind(this),this._onKeyDown=Hw.bind(this),this._onKeyUp=jw.bind(this),this._onTouchStart=Kw.bind(this),this._onTouchMove=Qw.bind(this),this._onTouchEnd=Zw.bind(this),this._onMouseDown=Ww.bind(this),this._onMouseMove=$w.bind(this),this._onMouseUp=qw.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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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)>vw&&(this.dispatchEvent(bw),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>vw||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(bw),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=Tw,this.keyState=Tw,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(bw),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(Cw.copy(this._panEnd).sub(this._panStart),Cw.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;Cw.x*=e,Cw.y*=t}Cw.multiplyScalar(this._eye.length()*this.panSpeed),Pw.copy(this._eye).cross(this.object.up).setLength(Cw.x),Pw.add(Rw.copy(this.object.up).setLength(Cw.y)),this.object.position.add(Pw),this.target.add(Pw),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(Cw.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){Ow.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=Ow.length();e?(this._eye.copy(this.object.position).sub(this.target),Iw.copy(this._eye).normalize(),Lw.copy(this.object.up).normalize(),Dw.crossVectors(Lw,Iw).normalize(),Lw.setLength(this._moveCurr.y-this._movePrev.y),Dw.setLength(this._moveCurr.x-this._movePrev.x),Ow.copy(Lw.add(Dw)),Fw.crossVectors(Ow,this._eye).normalize(),e*=this.rotateSpeed,Bw.setFromAxisAngle(Fw,e),this._eye.applyQuaternion(Bw),this.object.up.applyQuaternion(Bw),this._lastAxis.copy(Fw),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),Bw.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(Bw),this.object.up.applyQuaternion(Bw)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let t;this.state===Ew?(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 Aw.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),Aw}_getMouseOnCircle(e,t){return Aw.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),Aw}_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 Uw(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e))}function zw(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function Vw(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.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp)))}function Gw(e){this._removePointer(e)}function jw(){!1!==this.enabled&&(this.keyState=Tw,window.addEventListener("keydown",this._onKeyDown))}function Hw(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===Tw&&(e.code!==this.keys[ww]||this.noRotate?e.code!==this.keys[Sw]||this.noZoom?e.code!==this.keys[Mw]||this.noPan||(this.keyState=Mw):this.keyState=Sw:this.keyState=ww))}function Ww(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=Sw;break;case e.MOUSE.ROTATE:this.state=ww;break;case e.MOUSE.PAN:this.state=Mw;break;default:this.state=Tw}const i=this.keyState!==Tw?this.keyState:this.state;i!==ww||this.noRotate?i!==Sw||this.noZoom?i!==Mw||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(xw)}function $w(e){const t=this.keyState!==Tw?this.keyState:this.state;t!==ww||this.noRotate?t!==Sw||this.noZoom?t!==Mw||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 qw(){this.state=Tw,this.dispatchEvent(_w)}function Xw(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(xw),this.dispatchEvent(_w)}}function Yw(e){!1!==this.enabled&&e.preventDefault()}function Kw(e){if(this._trackPointer(e),1===this._pointers.length)this.state=Nw,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=Ew;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(xw)}function Qw(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 Zw(e){switch(this._pointers.length){case 0:this.state=Tw;break;case 1:this.state=Nw,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=Ew;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(_w)}const Jw={type:"change"},eS={type:"start"},tS={type:"end"},sS=new e.Ray,iS=new e.Plane,rS=Math.cos(70*e.MathUtils.DEG2RAD),nS=new e.Vector3,oS=2*Math.PI,aS=-1,hS=0,lS=1,uS=2,cS=3,dS=4,pS=5,mS=6,gS=1e-6;class fS extends e.Controls{constructor(t,s=null){super(t,s),this.state=aS,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._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=bS.bind(this),this._onPointerDown=yS.bind(this),this._onPointerUp=xS.bind(this),this._onContextMenu=NS.bind(this),this._onMouseWheel=TS.bind(this),this._onKeyDown=wS.bind(this),this._onTouchStart=SS.bind(this),this._onTouchMove=MS.bind(this),this._onMouseDown=_S.bind(this),this._onMouseMove=vS.bind(this),this._interceptControlDown=ES.bind(this),this._interceptControlUp=AS.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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(Jw),this.update(),this.state=aS}update(t=null){const s=this.object.position;nS.copy(s).sub(this.target),nS.applyQuaternion(this._quat),this._spherical.setFromVector3(nS),this.autoRotate&&this.state===aS&&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+=oS:i>Math.PI&&(i-=oS),r<-Math.PI?r+=oS:r>Math.PI&&(r-=oS),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(nS.setFromSpherical(this._spherical),nS.applyQuaternion(this._quatInverse),s.copy(this.target).add(nS),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=nS.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=nS.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):(sS.origin.copy(this.object.position),sS.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(sS.direction))<rS?this.object.lookAt(this.target):(iS.setFromNormalAndCoplanarPoint(this.object.up,this.target),sS.intersectPlane(iS,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)>gS||8*(1-this._lastQuaternion.dot(this.object.quaternion))>gS||this._lastTargetPosition.distanceToSquared(this.target)>gS)&&(this.dispatchEvent(Jw),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?oS/60*this.autoRotateSpeed*e:oS/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){nS.setFromMatrixColumn(t,0),nS.multiplyScalar(-e),this._panOffset.add(nS)}_panUp(e,t){!0===this.screenSpacePanning?nS.setFromMatrixColumn(t,1):(nS.setFromMatrixColumn(t,0),nS.crossVectors(this.object.up,nS)),nS.multiplyScalar(e),this._panOffset.add(nS)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;nS.copy(i).sub(this.target);let r=nS.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,o=s.height;this._mouse.x=i/n*2-1,this._mouse.y=-r/o*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(oS*this._rotateDelta.x/t.clientHeight),this._rotateUp(oS*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(oS*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(-oS*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(oS*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(-oS*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(oS*this._rotateDelta.x/t.clientHeight),this._rotateUp(oS*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),o=.5*(e.pageY+t.y);this._updateZoomParameters(n,o)}_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 yS(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e)))}function bS(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function xS(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(tS),this.state=aS;break;case 1:const t=this._pointers[0],s=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:s.x,pageY:s.y})}}function _S(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=lS;break;case e.MOUSE.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=uS}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=hS}break;case e.MOUSE.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=hS}else{if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=uS}break;default:this.state=aS}this.state!==aS&&this.dispatchEvent(eS)}function vS(e){switch(this.state){case hS:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case lS:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case uS:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function TS(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===aS&&(e.preventDefault(),this.dispatchEvent(eS),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(tS))}function wS(e){!1!==this.enabled&&this._handleKeyDown(e)}function SS(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=cS;break;case e.TOUCH.PAN:if(!1===this.enablePan)return;this._handleTouchStartPan(t),this.state=dS;break;default:this.state=aS}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=pS;break;case e.TOUCH.DOLLY_ROTATE:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(t),this.state=mS;break;default:this.state=aS}break;default:this.state=aS}this.state!==aS&&this.dispatchEvent(eS)}function MS(e){switch(this._trackPointer(e),this.state){case cS:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case dS:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case pS:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case mS:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=aS}}function NS(e){!1!==this.enabled&&e.preventDefault()}function ES(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function AS(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const CS={type:"change"},RS=1e-6,PS=new e.Quaternion;class FS 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=BS.bind(this),this._onKeyUp=IS.bind(this),this._onPointerMove=DS.bind(this),this._onPointerDown=LS.bind(this),this._onPointerUp=OS.bind(this),this._onPointerCancel=kS.bind(this),this._onContextMenu=US.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),PS.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(PS),(this._lastPosition.distanceToSquared(t.position)>RS||8*(1-this._lastQuaternion.dot(t.quaternion))>RS)&&(this.dispatchEvent(CS),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 BS(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 IS(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 LS(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 DS(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 OS(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 kS(){!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 US(e){!1!==this.enabled&&e.preventDefault()}const zS={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 VS{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 GS=new e.OrthographicCamera(-1,1,1,-1,0,1);class jS 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 HS=new jS;class WS{constructor(t){this._mesh=new e.Mesh(HS,t)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,GS)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class $S extends VS{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 WS(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 qS extends VS{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,o;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(n=0,o=1):(n=1,o=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(o),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 XS extends VS{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class YS{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 $S(zS),this.copyPass.material.blending=e.NoBlending,this.clock=new e.Clock}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){void 0===e&&(e=this.clock.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!==qS&&(i instanceof qS?s=!0:i instanceof XS&&(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 KS extends VS{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._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 QS(){return QS=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},QS.apply(null,arguments)}function ZS(e,t){return ZS=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},ZS(e,t)}function JS(e){return JS=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},JS(e)}function eM(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(eM=function(){return!!e})()}function tM(e){var t="function"==typeof Map?new Map:void 0;return tM=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(eM())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return s&&ZS(r,s.prototype),r}(e,arguments,JS(this).constructor)}return s.prototype=Object.create(e.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),ZS(s,e)},tM(e)}var sM={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 iM(){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 rM=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,iM.apply(void 0,[sM[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,ZS(e,t)}(t,e),t}(tM(Error));function nM(e){return Math.round(255*e)}function oM(e,t,s){return nM(e)+","+nM(t)+","+nM(s)}function aM(e,t,s,i){if(void 0===i&&(i=oM),0===t)return i(s,s,s);var r=(e%360+360)%360/60,n=(1-Math.abs(2*s-1))*t,o=n*(1-Math.abs(r%2-1)),a=0,h=0,l=0;r>=0&&r<1?(a=n,h=o):r>=1&&r<2?(a=o,h=n):r>=2&&r<3?(h=n,l=o):r>=3&&r<4?(h=o,l=n):r>=4&&r<5?(a=o,l=n):r>=5&&r<6&&(a=n,l=o);var u=s-n/2;return i(a+u,h+u,l+u)}var hM={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 lM=/^#[a-fA-F0-9]{6}$/,uM=/^#[a-fA-F0-9]{8}$/,cM=/^#[a-fA-F0-9]{3}$/,dM=/^#[a-fA-F0-9]{4}$/,pM=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,mM=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,gM=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,fM=/^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 yM(e){if("string"!=typeof e)throw new rM(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return hM[t]?"#"+hM[t]:e}(e);if(t.match(lM))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(uM)){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(cM))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(dM)){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=pM.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var n=mM.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 o=gM.exec(t);if(o){var a="rgb("+aM(parseInt(""+o[1],10),parseInt(""+o[2],10)/100,parseInt(""+o[3],10)/100)+")",h=pM.exec(a);if(!h)throw new rM(4,t,a);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10)}}var l=fM.exec(t.substring(0,50));if(l){var u="rgb("+aM(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",c=pM.exec(u);if(!c)throw new rM(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 rM(5)}function bM(e){return function(e){var t,s=e.red/255,i=e.green/255,r=e.blue/255,n=Math.max(s,i,r),o=Math.min(s,i,r),a=(n+o)/2;if(n===o)return void 0!==e.alpha?{hue:0,saturation:0,lightness:a,alpha:e.alpha}:{hue:0,saturation:0,lightness:a};var h=n-o,l=a>.5?h/(2-n-o):h/(n+o);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:a,alpha:e.alpha}:{hue:t,saturation:l,lightness:a}}(yM(e))}var xM=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 _M(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function vM(e){return _M(Math.round(255*e))}function TM(e,t,s){return xM("#"+vM(e)+vM(t)+vM(s))}function wM(e,t,s){return aM(e,t,s,TM)}function SM(e,t,s){if("number"==typeof e&&"number"==typeof t&&"number"==typeof s)return xM("#"+_M(e)+_M(t)+_M(s));if("object"==typeof e&&void 0===t&&void 0===s)return xM("#"+_M(e.red)+_M(e.green)+_M(e.blue));throw new rM(6)}function MM(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?SM(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new rM(7)}function NM(e){if("object"!=typeof e)throw new rM(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return MM(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 SM(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?wM(e.hue,e.saturation,e.lightness):"rgba("+aM(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new rM(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 wM(e.hue,e.saturation,e.lightness);throw new rM(1)}(e);throw new rM(8)}function EM(e,t,s){return function(){var i=s.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):EM(e,t,i)}}function AM(e){return EM(e,e.length,[])}function CM(e,t,s){return Math.max(e,Math.min(t,s))}AM((function(e,t){if("transparent"===t)return t;var s=bM(t);return NM(QS({},s,{hue:s.hue+parseFloat(e)}))})),AM((function(e,t){if("transparent"===t)return t;var s=bM(t);return NM(QS({},s,{lightness:CM(0,1,s.lightness-parseFloat(e))}))})),AM((function(e,t){if("transparent"===t)return t;var s=bM(t);return NM(QS({},s,{saturation:CM(0,1,s.saturation-parseFloat(e))}))})),AM((function(e,t){if("transparent"===t)return t;var s=bM(t);return NM(QS({},s,{lightness:CM(0,1,s.lightness+parseFloat(e))}))}));var RM=AM((function(e,t,s){if("transparent"===t)return s;if("transparent"===s)return t;if(0===e)return s;var i=yM(t),r=QS({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),n=yM(s),o=QS({},n,{alpha:"number"==typeof n.alpha?n.alpha:1}),a=r.alpha-o.alpha,h=2*parseFloat(e)-1,l=((h*a==-1?h:h+a)/(1+h*a)+1)/2,u=1-l;return MM({red:Math.floor(r.red*l+o.red*u),green:Math.floor(r.green*l+o.green*u),blue:Math.floor(r.blue*l+o.blue*u),alpha:r.alpha*parseFloat(e)+o.alpha*(1-parseFloat(e))})})),PM=RM;var FM=AM((function(e,t){if("transparent"===t)return t;var s=yM(t);return MM(QS({},s,{alpha:CM(0,1,(100*("number"==typeof s.alpha?s.alpha:1)+100*parseFloat(e))/100)}))})),BM=FM;AM((function(e,t){if("transparent"===t)return t;var s=bM(t);return NM(QS({},s,{saturation:CM(0,1,s.saturation+parseFloat(e))}))})),AM((function(e,t){return"transparent"===t?t:NM(QS({},bM(t),{hue:parseFloat(e)}))})),AM((function(e,t){return"transparent"===t?t:NM(QS({},bM(t),{lightness:parseFloat(e)}))})),AM((function(e,t){return"transparent"===t?t:NM(QS({},bM(t),{saturation:parseFloat(e)}))})),AM((function(e,t){return"transparent"===t?t:PM(parseFloat(e),"rgb(0, 0, 0)",t)})),AM((function(e,t){return"transparent"===t?t:PM(parseFloat(e),"rgb(255, 255, 255)",t)})),AM((function(e,t){if("transparent"===t)return t;var s=yM(t);return MM(QS({},s,{alpha:CM(0,1,+(100*("number"==typeof s.alpha?s.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}));var IM=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-IM.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*IM.Bounce.In(2*e):.5*IM.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}}}}),LM=function(){return performance.now()},DM=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=LM()),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}(),OM={Linear:function(e,t){var s=e.length-1,i=s*t,r=Math.floor(i),n=OM.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}}},kM=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),UM=new DM,zM=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=IM.Linear.None,this._interpolationFunction=OM.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=kM.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=UM,UM.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=LM()),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 o=e[n],a=Array.isArray(o),h=a?"array":typeof o,l=!a&&Array.isArray(s[n]);if("undefined"!==h&&"function"!==h){if(l){if(0===(f=s[n]).length)continue;for(var u=[o],c=0,d=f.length;c<d;c+=1){var p=this._handleRelativeValue(o,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&&!a||!o||l)(void 0===t[n]||r)&&(t[n]=o),a||(t[n]*=1),i[n]=l?s[n].slice().reverse():t[n]||0;else{t[n]=a?[]:{};var m=o;for(var g in m)t[n][g]=m[g];i[n]=a?[]:{};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=LM()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=LM()),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=IM.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=OM.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=LM()),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 o=t-this._startTime,a=this._duration+(null!==(i=this._repeatDelayTime)&&void 0!==i?i:this._delayTime),h=this._duration+this._repeat*a,l=function(){if(0===n._duration)return 1;if(o>h)return 1;var e=Math.trunc(o/a),t=o-e*a,s=Math.min(t/n._duration,1);return 0===s&&o===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||o>=this._duration){if(this._repeat>0){var c=Math.min(Math.trunc((o-this._duration)/a)+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+=a*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,o=s[r],a=Array.isArray(e[r]),h=Array.isArray(o);!a&&h?e[r]=this._interpolationFunction(o,i):"object"==typeof o&&o?this._updateProperties(e[r],n,o,i):"number"==typeof(o=this._handleRelativeValue(n,o))&&(e[r]=n+(o-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}();kM.nextId;var VM=UM;VM.getAll.bind(VM),VM.removeAll.bind(VM),VM.add.bind(VM),VM.remove.bind(VM),VM.update.bind(VM);function GM(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var jM="object"==typeof global&&global&&global.Object===Object&&global,HM="object"==typeof self&&self&&self.Object===Object&&self,WM=jM||HM||Function("return this")(),$M=function(){return WM.Date.now()},qM=/\s/;var XM=/^\s+/;function YM(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&qM.test(e.charAt(t)););return t}(e)+1).replace(XM,""):e}var KM=WM.Symbol,QM=Object.prototype,ZM=QM.hasOwnProperty,JM=QM.toString,eN=KM?KM.toStringTag:void 0;var tN=Object.prototype.toString;var sN=KM?KM.toStringTag:void 0;function iN(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":sN&&sN in Object(e)?function(e){var t=ZM.call(e,eN),s=e[eN];try{e[eN]=void 0;var i=!0}catch(e){}var r=JM.call(e);return i&&(t?e[eN]=s:delete e[eN]),r}(e):function(e){return tN.call(e)}(e)}var rN=/^[-+]0x[0-9a-f]+$/i,nN=/^0b[01]+$/i,oN=/^0o[0-7]+$/i,aN=parseInt;function hN(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]"==iN(e)}(e))return NaN;if(GM(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=GM(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=YM(e);var s=nN.test(e);return s||oN.test(e)?aN(e.slice(2),s?2:8):rN.test(e)?NaN:+e}var lN=Math.max,uN=Math.min;function cN(e,t,s){var i,r,n,o,a,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,o=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=$M();if(m(e))return f(e);a=setTimeout(g,function(e){var s=t-(e-h);return c?uN(s,n-(e-l)):s}(e))}function f(e){return a=void 0,d&&i?p(e):(i=r=void 0,o)}function y(){var e=$M(),s=m(e);if(i=arguments,r=this,h=e,s){if(void 0===a)return function(e){return l=e,a=setTimeout(g,t),u?p(e):o}(h);if(c)return clearTimeout(a),a=setTimeout(g,t),p(h)}return void 0===a&&(a=setTimeout(g,t)),o}return t=hN(t)||0,GM(s)&&(u=!!s.leading,n=(c="maxWait"in s)?lN(hN(s.maxWait)||0,t):n,d="trailing"in s?!!s.trailing:d),y.cancel=function(){void 0!==a&&clearTimeout(a),l=0,i=h=r=a=void 0},y.flush=function(){return void 0===a?o:f($M())},y}function dN(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 pN(e,t,s){return Object.defineProperty(e,"prototype",{writable:!1}),e}function mN(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,o,a=[],h=!0,l=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(a.push(i.value),a.length!==t);h=!0);}catch(e){l=!0,r=e}finally{try{if(!h&&null!=s.return&&(o=s.return(),Object(o)!==o))return}finally{if(l)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return dN(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)?dN(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 gN=pN((function e(t,s){var i=s.default,r=void 0===i?null:i,n=s.triggerUpdate,o=void 0===n||n,a=s.onChange,h=void 0===a?function(e,t){}:a;!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=o,this.onChange=h}));function fN(e){var t=e.stateInit,s=void 0===t?function(){return{}}:t,i=e.props,r=void 0===i?{}:i,n=e.methods,o=void 0===n?{}:n,a=e.aliases,h=void 0===a?{}:a,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 gN(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),a=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=cN((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,o=e.defaultVal,a=void 0===o?null:o;return function(e){var s=m[t];if(!arguments.length)return s;var r=void 0===e?a:e;return m[t]=r,n.call(f,r,m,s),!g.hasOwnProperty(t)&&(g[t]=s),i&&b(),f}}(e)})),Object.keys(o).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=o[e]).call.apply(t,[f,m].concat(i))}})),Object.entries(h).forEach((function(e){var t=mN(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&&a&&f(a),f}}var yN="http://www.w3.org/1999/xhtml",bN={svg:"http://www.w3.org/2000/svg",xhtml:yN,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function xN(e){var t=e+="",s=t.indexOf(":");return s>=0&&"xmlns"!==(t=e.slice(0,s))&&(e=e.slice(s+1)),bN.hasOwnProperty(t)?{space:bN[t],local:e}:e}function _N(e){return function(){var t=this.ownerDocument,s=this.namespaceURI;return s===yN&&t.documentElement.namespaceURI===yN?t.createElement(e):t.createElementNS(s,e)}}function vN(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function TN(e){var t=xN(e);return(t.local?vN:_N)(t)}function wN(){}function SN(e){return null==e?wN:function(){return this.querySelector(e)}}function MN(){return[]}function NN(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function EN(e){return function(t){return t.matches(e)}}var AN=Array.prototype.find;function CN(){return this.firstElementChild}var RN=Array.prototype.filter;function PN(){return Array.from(this.children)}function FN(e){return new Array(e.length)}function BN(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function IN(e,t,s,i,r,n){for(var o,a=0,h=t.length,l=n.length;a<l;++a)(o=t[a])?(o.__data__=n[a],i[a]=o):s[a]=new BN(e,n[a]);for(;a<h;++a)(o=t[a])&&(r[a]=o)}function LN(e,t,s,i,r,n,o){var a,h,l,u=new Map,c=t.length,d=n.length,p=new Array(c);for(a=0;a<c;++a)(h=t[a])&&(p[a]=l=o.call(h,h.__data__,a,t)+"",u.has(l)?r[a]=h:u.set(l,h));for(a=0;a<d;++a)l=o.call(e,n[a],a,n)+"",(h=u.get(l))?(i[a]=h,h.__data__=n[a],u.delete(l)):s[a]=new BN(e,n[a]);for(a=0;a<c;++a)(h=t[a])&&u.get(p[a])===h&&(r[a]=h)}function DN(e){return e.__data__}function ON(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function kN(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function UN(e){return function(){this.removeAttribute(e)}}function zN(e){return function(){this.removeAttributeNS(e.space,e.local)}}function VN(e,t){return function(){this.setAttribute(e,t)}}function GN(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function jN(e,t){return function(){var s=t.apply(this,arguments);null==s?this.removeAttribute(e):this.setAttribute(e,s)}}function HN(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 WN(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function $N(e){return function(){this.style.removeProperty(e)}}function qN(e,t,s){return function(){this.style.setProperty(e,t,s)}}function XN(e,t,s){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,s)}}function YN(e){return function(){delete this[e]}}function KN(e,t){return function(){this[e]=t}}function QN(e,t){return function(){var s=t.apply(this,arguments);null==s?delete this[e]:this[e]=s}}function ZN(e){return e.trim().split(/^|\s+/)}function JN(e){return e.classList||new eE(e)}function eE(e){this._node=e,this._names=ZN(e.getAttribute("class")||"")}function tE(e,t){for(var s=JN(e),i=-1,r=t.length;++i<r;)s.add(t[i])}function sE(e,t){for(var s=JN(e),i=-1,r=t.length;++i<r;)s.remove(t[i])}function iE(e){return function(){tE(this,e)}}function rE(e){return function(){sE(this,e)}}function nE(e,t){return function(){(t.apply(this,arguments)?tE:sE)(this,e)}}function oE(){this.textContent=""}function aE(e){return function(){this.textContent=e}}function hE(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function lE(){this.innerHTML=""}function uE(e){return function(){this.innerHTML=e}}function cE(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function dE(){this.nextSibling&&this.parentNode.appendChild(this)}function pE(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function mE(){return null}function gE(){var e=this.parentNode;e&&e.removeChild(this)}function fE(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function yE(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function bE(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 xE(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 o=0,a=r.length;o<a;++o)if((i=r[o]).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 _E(e,t,s){var i=WN(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 vE(e,t){return function(){return _E(this,e,t)}}function TE(e,t){return function(){return _E(this,e,t.apply(this,arguments))}}BN.prototype={constructor:BN,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)}},eE.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 wE=[null];function SE(e,t){this._groups=e,this._parents=t}SE.prototype={constructor:SE,select:function(e){"function"!=typeof e&&(e=SN(e));for(var t=this._groups,s=t.length,i=new Array(s),r=0;r<s;++r)for(var n,o,a=t[r],h=a.length,l=i[r]=new Array(h),u=0;u<h;++u)(n=a[u])&&(o=e.call(n,n.__data__,u,a))&&("__data__"in n&&(o.__data__=n.__data__),l[u]=o);return new SE(i,this._parents)},selectAll:function(e){e="function"==typeof e?NN(e):function(e){return null==e?MN:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,s=t.length,i=[],r=[],n=0;n<s;++n)for(var o,a=t[n],h=a.length,l=0;l<h;++l)(o=a[l])&&(i.push(e.call(o,o.__data__,l,a)),r.push(o));return new SE(i,r)},selectChild:function(e){return this.select(null==e?CN:function(e){return function(){return AN.call(this.children,e)}}("function"==typeof e?e:EN(e)))},selectChildren:function(e){return this.selectAll(null==e?PN:function(e){return function(){return RN.call(this.children,e)}}("function"==typeof e?e:EN(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,o=t[r],a=o.length,h=i[r]=[],l=0;l<a;++l)(n=o[l])&&e.call(n,n.__data__,l,o)&&h.push(n);return new SE(i,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,DN);var s=t?LN:IN,i=this._parents,r=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var n=r.length,o=new Array(n),a=new Array(n),h=new Array(n),l=0;l<n;++l){var u=i[l],c=r[l],d=c.length,p=ON(e.call(u,u&&u.__data__,l,i)),m=p.length,g=a[l]=new Array(m),f=o[l]=new Array(m);s(u,c,g,f,h[l]=new Array(d),p,t);for(var y,b,x=0,_=0;x<m;++x)if(y=g[x]){for(x>=_&&(_=x+1);!(b=f[_])&&++_<m;);y._next=b||null}}return(o=new SE(o,i))._enter=a,o._exit=h,o},enter:function(){return new SE(this._enter||this._groups.map(FN),this._parents)},exit:function(){return new SE(this._exit||this._groups.map(FN),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,o=Math.min(r,n),a=new Array(r),h=0;h<o;++h)for(var l,u=s[h],c=i[h],d=u.length,p=a[h]=new Array(d),m=0;m<d;++m)(l=u[m]||c[m])&&(p[m]=l);for(;h<r;++h)a[h]=s[h];return new SE(a,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,o=r[n];--n>=0;)(i=r[n])&&(o&&4^i.compareDocumentPosition(o)&&o.parentNode.insertBefore(i,o),o=i);return this},sort:function(e){function t(t,s){return t&&s?e(t.__data__,s.__data__):!t-!s}e||(e=kN);for(var s=this._groups,i=s.length,r=new Array(i),n=0;n<i;++n){for(var o,a=s[n],h=a.length,l=r[n]=new Array(h),u=0;u<h;++u)(o=a[u])&&(l[u]=o);l.sort(t)}return new SE(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 o=i[r];if(o)return o}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],o=0,a=n.length;o<a;++o)(r=n[o])&&e.call(r,r.__data__,o,n);return this},attr:function(e,t){var s=xN(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?zN:UN:"function"==typeof t?s.local?HN:jN:s.local?GN:VN)(s,t))},style:function(e,t,s){return arguments.length>1?this.each((null==t?$N:"function"==typeof t?XN:qN)(e,t,null==s?"":s)):function(e,t){return e.style.getPropertyValue(t)||WN(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?YN:"function"==typeof t?QN:KN)(e,t)):this.node()[e]},classed:function(e,t){var s=ZN(e+"");if(arguments.length<2){for(var i=JN(this.node()),r=-1,n=s.length;++r<n;)if(!i.contains(s[r]))return!1;return!0}return this.each(("function"==typeof t?nE:t?iE:rE)(s,t))},text:function(e){return arguments.length?this.each(null==e?oE:("function"==typeof e?hE:aE)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?lE:("function"==typeof e?cE:uE)(e)):this.node().innerHTML},raise:function(){return this.each(dE)},lower:function(){return this.each(pE)},append:function(e){var t="function"==typeof e?e:TN(e);return this.select((function(){return this.appendChild(t.apply(this,arguments))}))},insert:function(e,t){var s="function"==typeof e?e:TN(e),i=null==t?mE:"function"==typeof t?t:SN(t);return this.select((function(){return this.insertBefore(s.apply(this,arguments),i.apply(this,arguments)||null)}))},remove:function(){return this.each(gE)},clone:function(e){return this.select(e?yE:fE)},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+""),o=n.length;if(!(arguments.length<2)){for(a=t?xE:bE,i=0;i<o;++i)this.each(a(n[i],t,s));return this}var a=this.node().__on;if(a)for(var h,l=0,u=a.length;l<u;++l)for(i=0,h=a[l];i<o;++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?TE:vE)(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,o=r.length;n<o;++n)(i=r[n])&&(yield i)}};var ME,NE,EE,AE,CE,RE,PE,FE,BE,IE,LE,DE,OE={},kE=[],UE=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,zE=Array.isArray;function VE(e,t){for(var s in t)e[s]=t[s];return e}function GE(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function jE(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?++EE:r,__i:-1,__u:0};return null==r&&null!=NE.vnode&&NE.vnode(n),n}function HE(e){return e.children}function WE(e,t){this.props=e,this.context=t}function $E(e,t){if(null==t)return e.__?$E(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?$E(e):null}function qE(e){var t,s;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(s=e.__k[t])&&null!=s.__e){e.__e=e.__c.base=s.__e;break}return qE(e)}}function XE(e){(!e.__d&&(e.__d=!0)&&CE.push(e)&&!YE.__r++||RE!==NE.debounceRendering)&&((RE=NE.debounceRendering)||PE)(YE)}function YE(){for(var e,t,s,i,r,n,o,a=1;CE.length;)CE.length>a&&CE.sort(FE),e=CE.shift(),a=CE.length,e.__d&&(s=void 0,r=(i=(t=e).__v).__e,n=[],o=[],t.__P&&((s=VE({},i)).__v=i.__v+1,NE.vnode&&NE.vnode(s),iA(t.__P,s,i,t.__n,t.__P.namespaceURI,32&i.__u?[r]:null,n,null==r?$E(i):r,!!(32&i.__u),o),s.__v=i.__v,s.__.__k[s.__i]=s,rA(n,s,o),s.__e!=r&&qE(s)));YE.__r=0}function KE(e,t,s,i,r,n,o,a,h,l,u){var c,d,p,m,g,f,y=i&&i.__k||kE,b=t.length;for(h=QE(s,t,y,h,b),c=0;c<b;c++)null!=(p=s.__k[c])&&(d=-1===p.__i?OE:y[p.__i]||OE,p.__i=c,f=iA(e,p,d,r,n,o,a,h,l,u),m=p.__e,p.ref&&d.ref!=p.ref&&(d.ref&&aA(d.ref,null,p),u.push(p.ref,p.__c||m,p)),null==g&&null!=m&&(g=m),4&p.__u||d.__k===p.__k?h=ZE(p,h,e):"function"==typeof p.type&&void 0!==f?h=f:m&&(h=m.nextSibling),p.__u&=-7);return s.__e=g,h}function QE(e,t,s,i,r){var n,o,a,h,l,u=s.length,c=u,d=0;for(e.__k=new Array(r),n=0;n<r;n++)null!=(o=t[n])&&"boolean"!=typeof o&&"function"!=typeof o?(h=n+d,(o=e.__k[n]="string"==typeof o||"number"==typeof o||"bigint"==typeof o||o.constructor==String?jE(null,o,null,null,null):zE(o)?jE(HE,{children:o},null,null,null):void 0===o.constructor&&o.__b>0?jE(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=e,o.__b=e.__b+1,a=null,-1!==(l=o.__i=JE(o,s,h,c))&&(c--,(a=s[l])&&(a.__u|=2)),null==a||null===a.__v?(-1==l&&(r>u?d--:r<u&&d++),"function"!=typeof o.type&&(o.__u|=4)):l!=h&&(l==h-1?d--:l==h+1?d++:(l>h?d--:d++,o.__u|=4))):e.__k[n]=null;if(c)for(n=0;n<u;n++)null!=(a=s[n])&&!(2&a.__u)&&(a.__e==i&&(i=$E(a)),hA(a,a));return i}function ZE(e,t,s){var i,r;if("function"==typeof e.type){for(i=e.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=e,t=ZE(i[r],t,s));return t}e.__e!=t&&(t&&e.type&&!s.contains(t)&&(t=$E(e)),s.insertBefore(e.__e,t||null),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function JE(e,t,s,i){var r,n,o=e.key,a=e.type,h=t[s];if(null===h&&null==e.key||h&&o==h.key&&a===h.type&&!(2&h.__u))return s;if(i>(null==h||2&h.__u?0:1))for(r=s-1,n=s+1;r>=0||n<t.length;){if(r>=0){if((h=t[r])&&!(2&h.__u)&&o==h.key&&a===h.type)return r;r--}if(n<t.length){if((h=t[n])&&!(2&h.__u)&&o==h.key&&a===h.type)return n;n++}}return-1}function eA(e,t,s){"-"==t[0]?e.setProperty(t,null==s?"":s):e[t]=null==s?"":"number"!=typeof s||UE.test(t)?s:s+"px"}function tA(e,t,s,i,r){var n;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||eA(e.style,t,"");if(s)for(t in s)i&&s[t]===i[t]||eA(e.style,t,s[t])}else if("o"==t[0]&&"n"==t[1])n=t!=(t=t.replace(BE,"$1")),t=t.toLowerCase()in e||"onFocusOut"==t||"onFocusIn"==t?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+n]=s,s?i?s.t=i.t:(s.t=IE,e.addEventListener(t,n?DE:LE,n)):e.removeEventListener(t,n?DE:LE,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 sA(e){return function(t){if(this.l){var s=this.l[t.type+e];if(null==t.u)t.u=IE++;else if(t.u<s.t)return;return s(NE.event?NE.event(t):t)}}}function iA(e,t,s,i,r,n,o,a,h,l){var u,c,d,p,m,g,f,y,b,x,_,v,T,w,S,M,N,E=t.type;if(void 0!==t.constructor)return null;128&s.__u&&(h=!!(32&s.__u),n=[a=t.__e=s.__e]),(u=NE.__b)&&u(t);e:if("function"==typeof E)try{if(y=t.props,b="prototype"in E&&E.prototype.render,x=(u=E.contextType)&&i[u.__c],_=u?x?x.props.value:u.__:i,s.__c?f=(c=t.__c=s.__c).__=c.__E:(b?t.__c=c=new E(y,_):(t.__c=c=new WE(y,_),c.constructor=E,c.render=lA),x&&x.sub(c),c.props=y,c.state||(c.state={}),c.context=_,c.__n=i,d=c.__d=!0,c.__h=[],c._sb=[]),b&&null==c.__s&&(c.__s=c.state),b&&null!=E.getDerivedStateFromProps&&(c.__s==c.state&&(c.__s=VE({},c.__s)),VE(c.__s,E.getDerivedStateFromProps(y,c.__s))),p=c.props,m=c.state,c.__v=t,d)b&&null==E.getDerivedStateFromProps&&null!=c.componentWillMount&&c.componentWillMount(),b&&null!=c.componentDidMount&&c.__h.push(c.componentDidMount);else{if(b&&null==E.getDerivedStateFromProps&&y!==p&&null!=c.componentWillReceiveProps&&c.componentWillReceiveProps(y,_),!c.__e&&(null!=c.shouldComponentUpdate&&!1===c.shouldComponentUpdate(y,c.__s,_)||t.__v==s.__v)){for(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)})),v=0;v<c._sb.length;v++)c.__h.push(c._sb[v]);c._sb=[],c.__h.length&&o.push(c);break e}null!=c.componentWillUpdate&&c.componentWillUpdate(y,c.__s,_),b&&null!=c.componentDidUpdate&&c.__h.push((function(){c.componentDidUpdate(p,m,g)}))}if(c.context=_,c.props=y,c.__P=e,c.__e=!1,T=NE.__r,w=0,b){for(c.state=c.__s,c.__d=!1,T&&T(t),u=c.render(c.props,c.state,c.context),S=0;S<c._sb.length;S++)c.__h.push(c._sb[S]);c._sb=[]}else do{c.__d=!1,T&&T(t),u=c.render(c.props,c.state,c.context),c.state=c.__s}while(c.__d&&++w<25);c.state=c.__s,null!=c.getChildContext&&(i=VE(VE({},i),c.getChildContext())),b&&!d&&null!=c.getSnapshotBeforeUpdate&&(g=c.getSnapshotBeforeUpdate(p,m)),M=u,null!=u&&u.type===HE&&null==u.key&&(M=nA(u.props.children)),a=KE(e,zE(M)?M:[M],t,s,i,r,n,o,a,h,l),c.base=t.__e,t.__u&=-161,c.__h.length&&o.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;a&&8==a.nodeType&&a.nextSibling;)a=a.nextSibling;n[n.indexOf(a)]=null,t.__e=a}else for(N=n.length;N--;)GE(n[N]);else t.__e=s.__e,t.__k=s.__k;NE.__e(e,t,s)}else null==n&&t.__v==s.__v?(t.__k=s.__k,t.__e=s.__e):a=t.__e=oA(s.__e,t,s,i,r,n,o,h,l);return(u=NE.diffed)&&u(t),128&t.__u?void 0:a}function rA(e,t,s){for(var i=0;i<s.length;i++)aA(s[i],s[++i],s[++i]);NE.__c&&NE.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){NE.__e(e,t.__v)}}))}function nA(e){return"object"!=typeof e||null==e?e:zE(e)?e.map(nA):VE({},e)}function oA(e,t,s,i,r,n,o,a,h){var l,u,c,d,p,m,g,f=s.props,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),a&&(NE.__m&&NE.__m(t,n),a=!1),n=null}if(null===b)f===y||a&&e.data===y||(e.data=y);else{if(n=n&&ME.call(e.childNodes),f=s.props||OE,!a&&null!=n)for(f={},l=0;l<e.attributes.length;l++)f[(p=e.attributes[l]).name]=p.value;for(l in f)if(p=f[l],"children"==l);else if("dangerouslySetInnerHTML"==l)c=p;else if(!(l in y)){if("value"==l&&"defaultValue"in y||"checked"==l&&"defaultChecked"in y)continue;tA(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:a&&"function"!=typeof p||f[l]===p||tA(e,l,p,f[l],r);if(u)a||c&&(u.__html===c.__html||u.__html===e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(c&&(e.innerHTML=""),KE("template"===t.type?e.content:e,zE(d)?d:[d],t,s,i,"foreignObject"==b?"http://www.w3.org/1999/xhtml":r,n,o,n?n[0]:s.__k&&$E(s,0),a,h),null!=n)for(l=n.length;l--;)GE(n[l]);a||(l="value","progress"==b&&null==m?e.removeAttribute("value"):void 0!==m&&(m!==e[l]||"progress"==b&&!m||"option"==b&&m!==f[l])&&tA(e,l,m,f[l],r),l="checked",void 0!==g&&g!==e[l]&&tA(e,l,g,f[l],r))}return e}function aA(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){NE.__e(e,s)}}function hA(e,t,s){var i,r;if(NE.unmount&&NE.unmount(e),(i=e.ref)&&(i.current&&i.current!==e.__e||aA(i,null,t)),null!=(i=e.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(e){NE.__e(e,t)}i.base=i.__P=null}if(i=e.__k)for(r=0;r<i.length;r++)i[r]&&hA(i[r],t,s||"function"!=typeof e.type);s||GE(e.__e),e.__c=e.__=e.__e=void 0}function lA(e,t,s){return this.constructor(e,s)}function uA(e,t,s){var i,r,n;t==document&&(t=document.documentElement),NE.__&&NE.__(e,t),i=!1?null:t.__k,r=[],n=[],iA(t,e=t.__k=function(e,t,s){var i,r,n,o={};for(n in t)"key"==n?i=t[n]:"ref"==n?r=t[n]:o[n]=t[n];if(arguments.length>2&&(o.children=arguments.length>3?ME.call(arguments,2):s),"function"==typeof e&&null!=e.defaultProps)for(n in e.defaultProps)void 0===o[n]&&(o[n]=e.defaultProps[n]);return jE(e,o,i,r,null)}(HE,null,[e]),i||OE,OE,t.namespaceURI,i?null:t.firstChild?ME.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,n),rA(r,e,n)}function cA(e,t,s){var i,r,n,o,a=VE({},e.props);for(n in e.type&&e.type.defaultProps&&(o=e.type.defaultProps),t)"key"==n?i=t[n]:"ref"==n?r=t[n]:a[n]=void 0===t[n]&&void 0!==o?o[n]:t[n];return arguments.length>2&&(a.children=arguments.length>3?ME.call(arguments,2):s),jE(e.type,a,i||e.key,r||e.ref,null)}function dA(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 pA(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 mA(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 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,o,a=[],h=!0,l=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(a.push(i.value),a.length!==t);h=!0);}catch(e){l=!0,r=e}finally{try{if(!h&&null!=s.return&&(o=s.return(),Object(o)!==o))return}finally{if(l)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return dA(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)?dA(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 fA(e){return fA="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},fA(e)}ME=kE.slice,NE={__e:function(e,t,s,i){for(var r,n,o;t=t.__;)if((r=t.__c)&&!r.__)try{if((n=r.constructor)&&null!=n.getDerivedStateFromError&&(r.setState(n.getDerivedStateFromError(e)),o=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(e,i||{}),o=r.__d),o)return r.__E=r}catch(t){e=t}throw e}},EE=0,AE=function(e){return null!=e&&null==e.constructor},WE.prototype.setState=function(e,t){var s;s=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=VE({},this.state),"function"==typeof e&&(e=e(VE({},s),this.props)),e&&VE(s,e),null!=e&&this.__v&&(t&&this._sb.push(t),XE(this))},WE.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),XE(this))},WE.prototype.render=HE,CE=[],PE="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,FE=function(e,t){return e.__v.__b-t.__v.__b},YE.__r=0,BE=/(PointerCapture)$|Capture$/i,IE=0,LE=sA(!1),DE=sA(!0);var yA=function(e){if("object"!==fA(e))return e;var t,s=cA(e);s.props&&(s.props=function(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?mA(Object(s),!0).forEach((function(t){pA(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):mA(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(yA):yA(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 bA=fN({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 SE([[document.querySelector(e)]],[document.documentElement]):new SE([[e]],wE)}(!!e&&"object"===fA(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=gA(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,o=i.offsetHeight,a=[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?o>130&&o-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(a.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 AE(cA(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,uA(yA(t),s)):e.tooltipEl.text("")}}),xA=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,Clock:e.Clock},_A=fN({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.update&&e.controls.update(Math.min(1,e.clock.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,o=s||{x:0,y:0,z:0};if(i){var a=Object.assign({},r.position),h=c();e.tweenGroup.add(new zM(a).to(n,i).easing(IM.Quadratic.Out).onUpdate(l).start()),e.tweenGroup.add(new zM(h).to(o,i/3).easing(IM.Quadratic.Out).onUpdate(u).start())}else l(n),u(o);return this}return Object.assign({},r.position,{lookAt:c()});function l(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 u(t){var s=new xA.Vector3(t.x,t.y,t.z);e.controls.target?e.controls.target=s:r.lookAt(s)}function c(){return Object.assign(new xA.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,o=e.camera;if(t){var a=new xA.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(a[s]-e)}))))})))),l=(1-2*n/e.height)*o.fov,u=h/Math.atan(l*Math.PI/180),c=u/o.aspect,d=Math.max(u,c);if(d>0){var p=a.clone().sub(o.position).normalize().multiplyScalar(-d);this.cameraPosition(p,a,s)}}return this},getBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0},i=new xA.Box3(new xA.Vector3(0,0,0),new xA.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 xA.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 xA.Vector2(t/e.width*2-1,-s/e.height*2+1),n=new xA.Raycaster;return n.setFromCamera(r,e.camera),Object.assign({},n.ray.at(i,new xA.Vector3))},intersectingObjects:function(e,t,s){var i=new xA.Vector2(t/e.width*2-1,-s/e.height*2+1),r=new xA.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}},stateInit:function(){return{scene:new xA.Scene,camera:new xA.PerspectiveCamera,clock:new xA.Clock,tweenGroup:new DM,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,o=s.useWebGPU,a=void 0!==o&&o,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 bA(t.container),t.pointerPos=new xA.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)&&("touch"!==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(),o=window.pageXOffset||document.documentElement.scrollLeft,a=window.pageYOffset||document.documentElement.scrollTop,{top:n.top+a,left:n.left+o});t.pointerPos.x=s.pageX-i.left,t.pointerPos.y=s.pageY-i.top}var r,n,o,a}),{passive:!0})})),t.container.addEventListener("pointerup",(function(e){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(a?yw:xA.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 YS(t.renderer),t.postProcessingComposer.addPass(new KS(t.scene,t.camera)),t.controls=new{trackball:kw,orbit:fS,fly:FS}[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 xA.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 o=e.viewOffset.slice(0,2);o.some((function(e){return e}))&&(s=e.camera).setViewOffset.apply(s,[i,n].concat(r(o),[i,n])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,h=e.width,l=e.height,u=e.viewOffset.slice(0,2);u.some((function(e){return e}))?(a=e.camera).setViewOffset.apply(a,[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 xA.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=yM(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new xA.Color(BM(1,e.backgroundColor)),c)}function d(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new xA.TextureLoader).load(e.backgroundImageUrl,(function(t){t.colorSpace=xA.SRGBColorSpace,e.skysphere.material=new xA.MeshBasicMaterial({map:t,side:xA.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 _A}));
1
+ // Version 1.40.1 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="176",o=100,h=101,l=102,u=200,c=201,d=202,p=203,m=204,g=205,f=206,y=207,b=208,x=209,_=210,v=301,T=302,w=303,S=304,M=1e3,N=1001,E=1002,A=1003,C=1004,R=1005,P=1006,F=1007,I=1008,B=1009,L=1010,D=1011,O=1012,k=1013,U=1014,z=1015,V=1016,G=1020,j=1022,H=1023,W=1026,$=1027,q=1028,X=1029,Y=1030,K=1031,Q=1033,Z=33776,J=33777,ee=33778,te=33779,se=37492,ie=37496,re=37808,ne=37809,ae=37810,oe=37811,he=37812,le=37813,ue=37814,ce=37815,de=37816,pe=37817,me=37818,ge=37819,fe=37820,ye=37821,be=36492,xe="",_e="srgb",ve="srgb-linear",Te="linear",we="srgb",Se=7680,Me=512,Ne=513,Ee=514,Ae=515,Ce=516,Re=517,Pe=518,Fe=519,Ie=35044,Be=35048,Le=2e3,De=2001;class Oe{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 ke=["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 Ue=1234567;const ze=Math.PI/180,Ve=180/Math.PI;function Ge(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(ke[255&e]+ke[e>>8&255]+ke[e>>16&255]+ke[e>>24&255]+"-"+ke[255&t]+ke[t>>8&255]+"-"+ke[t>>16&15|64]+ke[t>>24&255]+"-"+ke[63&s|128]+ke[s>>8&255]+"-"+ke[s>>16&255]+ke[s>>24&255]+ke[255&i]+ke[i>>8&255]+ke[i>>16&255]+ke[i>>24&255]).toLowerCase()}function je(e,t,s){return Math.max(t,Math.min(s,e))}function He(e,t){return(e%t+t)%t}function We(e,t,s){return(1-s)*e+s*t}function $e(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 qe(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 Xe={DEG2RAD:ze,RAD2DEG:Ve,generateUUID:Ge,clamp:je,euclideanModulo:He,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:We,damp:function(e,t,s,i){return We(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(He(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&&(Ue=e);let t=Ue+=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*ze},radToDeg:function(e){return e*Ve},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:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:qe,denormalize:$e};class Ye{constructor(e=0,t=0){Ye.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=je(this.x,e.x,t.x),this.y=je(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=je(this.x,e,t),this.y=je(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(je(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(je(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 Ke{constructor(e,t,s,i,r,n,a,o,h){Ke.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 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],x=i[7],_=i[2],v=i[5],T=i[8];return r[0]=n*m+a*y+o*_,r[3]=n*g+a*b+o*v,r[6]=n*f+a*x+o*T,r[1]=h*m+l*y+u*_,r[4]=h*g+l*b+u*v,r[7]=h*f+l*x+u*T,r[2]=c*m+d*y+p*_,r[5]=c*g+d*b+p*v,r[8]=c*f+d*x+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(Qe.makeScale(e,t)),this}rotate(e){return this.premultiply(Qe.makeRotation(-e)),this}translate(e,t){return this.premultiply(Qe.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 Qe=new Ke;function Ze(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Je(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const et={};function tt(e){e in et||(et[e]=!0,console.warn(e))}const st=(new Ke).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),it=(new Ke).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function rt(){const e={enabled:!0,workingColorSpace:ve,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===we&&(e.r=at(e.r),e.g=at(e.g),e.b=at(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===we&&(e.r=ot(e.r),e.g=ot(e.g),e.b=ot(e.b)),e):e},fromWorkingColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===xe?Te:this.spaces[e].transfer},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}},t=[.64,.33,.3,.6,.15,.06],s=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[ve]:{primaries:t,whitePoint:i,transfer:Te,toXYZ:st,fromXYZ:it,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:_e},outputColorSpaceConfig:{drawingBufferColorSpace:_e}},[_e]:{primaries:t,whitePoint:i,transfer:we,toXYZ:st,fromXYZ:it,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:_e}}}),e}const nt=rt();function at(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function ot(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let ht;class lt{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=Je("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=Je("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*at(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*at(t[e]/255)):t[e]=at(t[e]);return{data:t,width:e.width,height:e.height}}return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let ut=0;class ct{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:ut++}),this.uuid=Ge(),this.data=e,this.dataReady=!0,this.version=0}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(dt(i[t].image)):e.push(dt(i[t]))}else e=dt(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function dt(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?lt.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let pt=0;class mt extends Oe{constructor(e=mt.DEFAULT_IMAGE,t=mt.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,a=1023,o=1009,h=mt.DEFAULT_ANISOTROPY,l=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:pt++}),this.uuid=Ge(),this.name="",this.source=new ct(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 Ye(0,0),this.repeat=new Ye(1,1),this.center=new Ye(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ke,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=l,this.userData={},this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isTextureArray=!1,this.pmremVersion=0}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)}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.isTextureArray=e.isTextureArray,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}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.6,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 M:e.x=e.x-Math.floor(e.x);break;case N:e.x=e.x<0?0:1;break;case E: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 M:e.y=e.y-Math.floor(e.y);break;case N:e.y=e.y<0?0:1;break;case E: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++}}mt.DEFAULT_IMAGE=null,mt.DEFAULT_MAPPING=300,mt.DEFAULT_ANISOTROPY=1;class gt{constructor(e=0,t=0,s=0,i=1){gt.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],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,x=(u+m)/4,_=(p+g)/4;return e>o&&e>y?e<n?(s=0,i=.707106781,r=.707106781):(s=Math.sqrt(e),i=b/s,r=x/s):o>y?o<n?(s=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),s=b/i,r=_/i):y<n?(s=.707106781,i=.707106781,r=0):(r=Math.sqrt(y),s=x/r,i=_/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=je(this.x,e.x,t.x),this.y=je(this.y,e.y,t.y),this.z=je(this.z,e.z,t.z),this.w=je(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=je(this.x,e,t),this.y=je(this.y,e,t),this.z=je(this.z,e,t),this.w=je(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(je(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 ft extends Oe{constructor(e=1,t=1,s={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=s.depth?s.depth:1,this.scissor=new gt(0,0,e,t),this.scissorTest=!1,this.viewport=new gt(0,0,e,t);const i={width:e,height:t,depth:this.depth};s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:P,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,multiview:!1},s);const r=new mt(i,s.mapping,s.wrapS,s.wrapT,s.magFilter,s.minFilter,s.format,s.type,s.anisotropy,s.colorSpace);r.flipY=!1,r.generateMipmaps=s.generateMipmaps,r.internalFormat=s.internalFormat,this.textures=[];const 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.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}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;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 ct(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 yt extends ft{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}class bt extends mt{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=A,this.minFilter=A,this.wrapR=N,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class xt{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];const c=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(0===a)return e[t+0]=o,e[t+1]=h,e[t+2]=l,void(e[t+3]=u);if(1===a)return e[t+0]=c,e[t+1]=d,e[t+2]=p,void(e[t+3]=m);if(u!==m||o!==c||h!==d||l!==p){let e=1-a;const t=o*c+h*d+l*p+u*m,s=t>=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),n=Math.atan2(r,t*s);e=Math.sin(e*n)/r,a=Math.sin(a*n)/r}const r=a*s;if(o=o*e+c*r,h=h*e+d*r,l=l*e+p*r,u=u*e+m*r,e===1-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:console.warn("THREE.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<Number.EPSILON?(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(je(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){if(0===t)return this;if(1===t)return this.copy(e);const s=this._x,i=this._y,r=this._z,n=this._w;let a=n*e._w+s*e._x+i*e._y+r*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=n,this._x=s,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const e=1-t;return this._w=e*n+t*this._w,this._x=e*s+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const h=Math.sqrt(o),l=Math.atan2(h,a),u=Math.sin((1-t)*l)/h,c=Math.sin(t*l)/h;return this._w=n*u+this._w*c,this._x=s*u+this._x*c,this._y=i*u+this._y*c,this._z=r*u+this._z*c,this._onChangeCallback(),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 _t{constructor(e=0,t=0,s=0){_t.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(Tt.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Tt.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=je(this.x,e.x,t.x),this.y=je(this.y,e.y,t.y),this.z=je(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=je(this.x,e,t),this.y=je(this.y,e,t),this.z=je(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(je(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 vt.copy(this).projectOnVector(e),this.sub(vt)}reflect(e){return this.sub(vt.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(je(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 vt=new _t,Tt=new xt;class wt{constructor(e=new _t(1/0,1/0,1/0),t=new _t(-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(Mt.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(Mt.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=Mt.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,Mt):Mt.fromBufferAttribute(i,t),Mt.applyMatrix4(e.matrixWorld),this.expandByPoint(Mt);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),Nt.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),Nt.copy(s.boundingBox)),Nt.applyMatrix4(e.matrixWorld),this.union(Nt)}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,Mt),Mt.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(It),Bt.subVectors(this.max,It),Et.subVectors(e.a,It),At.subVectors(e.b,It),Ct.subVectors(e.c,It),Rt.subVectors(At,Et),Pt.subVectors(Ct,At),Ft.subVectors(Et,Ct);let t=[0,-Rt.z,Rt.y,0,-Pt.z,Pt.y,0,-Ft.z,Ft.y,Rt.z,0,-Rt.x,Pt.z,0,-Pt.x,Ft.z,0,-Ft.x,-Rt.y,Rt.x,0,-Pt.y,Pt.x,0,-Ft.y,Ft.x,0];return!!Ot(t,Et,At,Ct,Bt)&&(t=[1,0,0,0,1,0,0,0,1],!!Ot(t,Et,At,Ct,Bt)&&(Lt.crossVectors(Rt,Pt),t=[Lt.x,Lt.y,Lt.z],Ot(t,Et,At,Ct,Bt)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Mt).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Mt).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()||(St[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),St[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),St[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),St[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),St[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),St[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),St[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),St[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(St)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const St=[new _t,new _t,new _t,new _t,new _t,new _t,new _t,new _t],Mt=new _t,Nt=new wt,Et=new _t,At=new _t,Ct=new _t,Rt=new _t,Pt=new _t,Ft=new _t,It=new _t,Bt=new _t,Lt=new _t,Dt=new _t;function Ot(e,t,s,i,r){for(let n=0,a=e.length-3;n<=a;n+=3){Dt.fromArray(e,n);const a=r.x*Math.abs(Dt.x)+r.y*Math.abs(Dt.y)+r.z*Math.abs(Dt.z),o=t.dot(Dt),h=s.dot(Dt),l=i.dot(Dt);if(Math.max(-Math.max(o,h,l),Math.min(o,h,l))>a)return!1}return!0}const kt=new wt,Ut=new _t,zt=new _t;class Vt{constructor(e=new _t,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):kt.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;Ut.subVectors(e,this.center);const t=Ut.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Ut,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):(zt.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ut.copy(e.center).add(zt)),this.expandByPoint(Ut.copy(e.center).sub(zt))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Gt=new _t,jt=new _t,Ht=new _t,Wt=new _t,$t=new _t,qt=new _t,Xt=new _t;class Yt{constructor(e=new _t,t=new _t(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,Gt)),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=Gt.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Gt.copy(this.origin).addScaledVector(this.direction,t),Gt.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){jt.copy(e).add(t).multiplyScalar(.5),Ht.copy(t).sub(e).normalize(),Wt.copy(this.origin).sub(jt);const r=.5*e.distanceTo(t),n=-this.direction.dot(Ht),a=Wt.dot(this.direction),o=-Wt.dot(Ht),h=Wt.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(jt).addScaledVector(Ht,c),d}intersectSphere(e,t){Gt.subVectors(e.center,this.origin);const s=Gt.dot(this.direction),i=Gt.dot(Gt)-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 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,Gt)}intersectTriangle(e,t,s,i,r){$t.subVectors(t,e),qt.subVectors(s,e),Xt.crossVectors($t,qt);let n,a=this.direction.dot(Xt);if(a>0){if(i)return null;n=1}else{if(!(a<0))return null;n=-1,a=-a}Wt.subVectors(this.origin,e);const o=n*this.direction.dot(qt.crossVectors(Wt,qt));if(o<0)return null;const h=n*this.direction.dot($t.cross(Wt));if(h<0)return null;if(o+h>a)return null;const l=-n*Wt.dot(Xt);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 Kt{constructor(e,t,s,i,r,n,a,o,h,l,u,c,d,p,m,g){Kt.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,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 Kt).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 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){const t=this.elements,s=e.elements,i=1/Qt.setFromMatrixColumn(e,0).length(),r=1/Qt.setFromMatrixColumn(e,1).length(),n=1/Qt.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(Jt,e,es)}lookAt(e,t,s){const i=this.elements;return is.subVectors(e,t),0===is.lengthSq()&&(is.z=1),is.normalize(),ts.crossVectors(s,is),0===ts.lengthSq()&&(1===Math.abs(s.z)?is.x+=1e-4:is.z+=1e-4,is.normalize(),ts.crossVectors(s,is)),ts.normalize(),ss.crossVectors(is,ts),i[0]=ts.x,i[4]=ss.x,i[8]=is.x,i[1]=ts.y,i[5]=ss.y,i[9]=is.y,i[2]=ts.z,i[6]=ss.z,i[10]=is.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],x=s[11],_=s[15],v=i[0],T=i[4],w=i[8],S=i[12],M=i[1],N=i[5],E=i[9],A=i[13],C=i[2],R=i[6],P=i[10],F=i[14],I=i[3],B=i[7],L=i[11],D=i[15];return r[0]=n*v+a*M+o*C+h*I,r[4]=n*T+a*N+o*R+h*B,r[8]=n*w+a*E+o*P+h*L,r[12]=n*S+a*A+o*F+h*D,r[1]=l*v+u*M+c*C+d*I,r[5]=l*T+u*N+c*R+d*B,r[9]=l*w+u*E+c*P+d*L,r[13]=l*S+u*A+c*F+d*D,r[2]=p*v+m*M+g*C+f*I,r[6]=p*T+m*N+g*R+f*B,r[10]=p*w+m*E+g*P+f*L,r[14]=p*S+m*A+g*F+f*D,r[3]=y*v+b*M+x*C+_*I,r[7]=y*T+b*N+x*R+_*B,r[11]=y*w+b*E+x*P+_*L,r[15]=y*S+b*A+x*F+_*D,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];return e[3]*(+r*o*u-i*h*u-r*a*c+s*h*c+i*a*d-s*o*d)+e[7]*(+t*o*d-t*h*c+r*n*c-i*n*d+i*h*l-r*o*l)+e[11]*(+t*h*u-t*a*d-r*n*u+s*n*d+r*a*l-s*h*l)+e[15]*(-i*a*l-t*o*u+t*a*c+i*n*u-s*n*c+s*o*l)}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=u*g*h-m*c*h+m*o*d-a*g*d-u*o*f+a*c*f,b=p*c*h-l*g*h-p*o*d+n*g*d+l*o*f-n*c*f,x=l*m*h-p*u*h+p*a*d-n*m*d-l*a*f+n*u*f,_=p*u*o-l*m*o-p*a*c+n*m*c+l*a*g-n*u*g,v=t*y+s*b+i*x+r*_;if(0===v)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const T=1/v;return e[0]=y*T,e[1]=(m*c*r-u*g*r-m*i*d+s*g*d+u*i*f-s*c*f)*T,e[2]=(a*g*r-m*o*r+m*i*h-s*g*h-a*i*f+s*o*f)*T,e[3]=(u*o*r-a*c*r-u*i*h+s*c*h+a*i*d-s*o*d)*T,e[4]=b*T,e[5]=(l*g*r-p*c*r+p*i*d-t*g*d-l*i*f+t*c*f)*T,e[6]=(p*o*r-n*g*r-p*i*h+t*g*h+n*i*f-t*o*f)*T,e[7]=(n*c*r-l*o*r+l*i*h-t*c*h-n*i*d+t*o*d)*T,e[8]=x*T,e[9]=(p*u*r-l*m*r-p*s*d+t*m*d+l*s*f-t*u*f)*T,e[10]=(n*m*r-p*a*r+p*s*h-t*m*h-n*s*f+t*a*f)*T,e[11]=(l*a*r-n*u*r-l*s*h+t*u*h+n*s*d-t*a*d)*T,e[12]=_*T,e[13]=(l*m*i-p*u*i+p*s*c-t*m*c-l*s*g+t*u*g)*T,e[14]=(p*a*i-n*m*i-p*s*o+t*m*o+n*s*g-t*a*g)*T,e[15]=(n*u*i-l*a*i+l*s*o-t*u*o-n*s*c+t*a*c)*T,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,x=o*u,_=s.x,v=s.y,T=s.z;return i[0]=(1-(m+f))*_,i[1]=(d+x)*_,i[2]=(p-b)*_,i[3]=0,i[4]=(d-x)*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;let r=Qt.set(i[0],i[1],i[2]).length();const n=Qt.set(i[4],i[5],i[6]).length(),a=Qt.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],Zt.copy(this);const o=1/r,h=1/n,l=1/a;return Zt.elements[0]*=o,Zt.elements[1]*=o,Zt.elements[2]*=o,Zt.elements[4]*=h,Zt.elements[5]*=h,Zt.elements[6]*=h,Zt.elements[8]*=l,Zt.elements[9]*=l,Zt.elements[10]*=l,t.setFromRotationMatrix(Zt),s.x=r,s.y=n,s.z=a,this}makePerspective(e,t,s,i,r,n,a=2e3){const o=this.elements,h=2*r/(t-e),l=2*r/(s-i),u=(t+e)/(t-e),c=(s+i)/(s-i);let d,p;if(a===Le)d=-(n+r)/(n-r),p=-2*n*r/(n-r);else{if(a!==De)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-n/(n-r),p=-n*r/(n-r)}return o[0]=h,o[4]=0,o[8]=u,o[12]=0,o[1]=0,o[5]=l,o[9]=c,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(e,t,s,i,r,n,a=2e3){const o=this.elements,h=1/(t-e),l=1/(s-i),u=1/(n-r),c=(t+e)*h,d=(s+i)*l;let p,m;if(a===Le)p=(n+r)*u,m=-2*u;else{if(a!==De)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*u,m=-1*u}return o[0]=2*h,o[4]=0,o[8]=0,o[12]=-c,o[1]=0,o[5]=2*l,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=m,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[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 Qt=new _t,Zt=new Kt,Jt=new _t(0,0,0),es=new _t(1,1,1),ts=new _t,ss=new _t,is=new _t,rs=new Kt,ns=new xt;class as{constructor(e=0,t=0,s=0,i=as.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(je(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(-je(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(je(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(-je(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(je(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(-je(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:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return rs.makeRotationFromQuaternion(e),this.setFromRotationMatrix(rs,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ns.setFromEuler(this),this.setFromQuaternion(ns,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}}as.DEFAULT_ORDER="XYZ";class os{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!!(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let hs=0;const ls=new _t,us=new xt,cs=new Kt,ds=new _t,ps=new _t,ms=new _t,gs=new xt,fs=new _t(1,0,0),ys=new _t(0,1,0),bs=new _t(0,0,1),xs={type:"added"},_s={type:"removed"},vs={type:"childadded",child:null},Ts={type:"childremoved",child:null};class ws extends Oe{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:hs++}),this.uuid=Ge(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ws.DEFAULT_UP.clone();const e=new _t,t=new as,s=new xt,i=new _t(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 Kt},normalMatrix:{value:new Ke}}),this.matrix=new Kt,this.matrixWorld=new Kt,this.matrixAutoUpdate=ws.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=ws.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new os,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return us.setFromAxisAngle(e,t),this.quaternion.multiply(us),this}rotateOnWorldAxis(e,t){return us.setFromAxisAngle(e,t),this.quaternion.premultiply(us),this}rotateX(e){return this.rotateOnAxis(fs,e)}rotateY(e){return this.rotateOnAxis(ys,e)}rotateZ(e){return this.rotateOnAxis(bs,e)}translateOnAxis(e,t){return ls.copy(e).applyQuaternion(this.quaternion),this.position.add(ls.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(fs,e)}translateY(e){return this.translateOnAxis(ys,e)}translateZ(e){return this.translateOnAxis(bs,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(cs.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?ds.copy(e):ds.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),ps.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?cs.lookAt(ps,ds,this.up):cs.lookAt(ds,ps,this.up),this.quaternion.setFromRotationMatrix(cs),i&&(cs.extractRotation(i.matrixWorld),us.setFromRotationMatrix(cs),this.quaternion.premultiply(us.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(console.error("THREE.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(xs),vs.child=e,this.dispatchEvent(vs),vs.child=null):console.error("THREE.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(_s),Ts.child=e,this.dispatchEvent(Ts),Ts.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),cs.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),cs.multiply(e.parent.matrixWorld)),e.applyMatrix4(cs),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(xs),vs.child=e,this.dispatchEvent(vs),vs.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(ps,e,ms),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ps,gs,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),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.6,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),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(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),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?{min:e.boundingBox.min.toArray(),max:e.boundingBox.max.toArray()}:void 0,boundingSphere:e.boundingSphere?{radius:e.boundingSphere.radius,center:e.boundingSphere.center.toArray()}: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={center:this.boundingSphere.center.toArray(),radius:this.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:this.boundingBox.min.toArray(),max:this.boundingBox.max.toArray()})),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.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t<e.children.length;t++){const s=e.children[t];this.add(s.clone())}return this}}ws.DEFAULT_UP=new _t(0,1,0),ws.DEFAULT_MATRIX_AUTO_UPDATE=!0,ws.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Ss=new _t,Ms=new _t,Ns=new _t,Es=new _t,As=new _t,Cs=new _t,Rs=new _t,Ps=new _t,Fs=new _t,Is=new _t,Bs=new gt,Ls=new gt,Ds=new gt;class Os{constructor(e=new _t,t=new _t,s=new _t){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),Ss.subVectors(e,t),i.cross(Ss);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){Ss.subVectors(i,t),Ms.subVectors(s,t),Ns.subVectors(e,t);const n=Ss.dot(Ss),a=Ss.dot(Ms),o=Ss.dot(Ns),h=Ms.dot(Ms),l=Ms.dot(Ns),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,Es)&&(Es.x>=0&&Es.y>=0&&Es.x+Es.y<=1)}static getInterpolation(e,t,s,i,r,n,a,o){return null===this.getBarycoord(e,t,s,i,Es)?(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,Es.x),o.addScaledVector(n,Es.y),o.addScaledVector(a,Es.z),o)}static getInterpolatedAttribute(e,t,s,i,r,n){return Bs.setScalar(0),Ls.setScalar(0),Ds.setScalar(0),Bs.fromBufferAttribute(e,t),Ls.fromBufferAttribute(e,s),Ds.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Bs,r.x),n.addScaledVector(Ls,r.y),n.addScaledVector(Ds,r.z),n}static isFrontFacing(e,t,s,i){return Ss.subVectors(s,t),Ms.subVectors(e,t),Ss.cross(Ms).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 Ss.subVectors(this.c,this.b),Ms.subVectors(this.a,this.b),.5*Ss.cross(Ms).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Os.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Os.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Os.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Os.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Os.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;As.subVectors(i,s),Cs.subVectors(r,s),Ps.subVectors(e,s);const o=As.dot(Ps),h=Cs.dot(Ps);if(o<=0&&h<=0)return t.copy(s);Fs.subVectors(e,i);const l=As.dot(Fs),u=Cs.dot(Fs);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(As,n);Is.subVectors(e,r);const d=As.dot(Is),p=Cs.dot(Is);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(Cs,a);const g=l*p-d*u;if(g<=0&&u-l>=0&&d-p>=0)return Rs.subVectors(r,i),a=(u-l)/(u-l+(d-p)),t.copy(i).addScaledVector(Rs,a);const f=1/(g+m+c);return n=m*f,a=c*f,t.copy(s).addScaledVector(As,n).addScaledVector(Cs,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const ks={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},Us={h:0,s:0,l:0},zs={h:0,s:0,l:0};function Vs(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 Gs{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=_e){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,nt.toWorkingColorSpace(this,t),this}setRGB(e,t,s,i=nt.workingColorSpace){return this.r=e,this.g=t,this.b=s,nt.toWorkingColorSpace(this,i),this}setHSL(e,t,s,i=nt.workingColorSpace){if(e=He(e,1),t=je(t,0,1),s=je(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=Vs(r,i,e+1/3),this.g=Vs(r,i,e),this.b=Vs(r,i,e-1/3)}return nt.toWorkingColorSpace(this,i),this}setStyle(e,t=_e){function s(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.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:console.warn("THREE.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);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=_e){const s=ks[e.toLowerCase()];return void 0!==s?this.setHex(s,t):console.warn("THREE.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=at(e.r),this.g=at(e.g),this.b=at(e.b),this}copyLinearToSRGB(e){return this.r=ot(e.r),this.g=ot(e.g),this.b=ot(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=_e){return nt.fromWorkingColorSpace(js.copy(this),e),65536*Math.round(je(255*js.r,0,255))+256*Math.round(je(255*js.g,0,255))+Math.round(je(255*js.b,0,255))}getHexString(e=_e){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=nt.workingColorSpace){nt.fromWorkingColorSpace(js.copy(this),t);const s=js.r,i=js.g,r=js.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=nt.workingColorSpace){return nt.fromWorkingColorSpace(js.copy(this),t),e.r=js.r,e.g=js.g,e.b=js.b,e}getStyle(e=_e){nt.fromWorkingColorSpace(js.copy(this),e);const t=js.r,s=js.g,i=js.b;return e!==_e?`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(Us),this.setHSL(Us.h+e,Us.s+t,Us.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(Us),e.getHSL(zs);const s=We(Us.h,zs.h,t),i=We(Us.s,zs.s,t),r=We(Us.l,zs.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 js=new Gs;Gs.NAMES=ks;let Hs=0;class Ws extends Oe{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Hs++}),this.uuid=Ge(),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=m,this.blendDst=g,this.blendEquation=o,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Gs(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=Se,this.stencilZFail=Se,this.stencilZPass=Se,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){console.warn(`THREE.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:console.warn(`THREE.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.6,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()),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!==m&&(s.blendSrc=this.blendSrc),this.blendDst!==g&&(s.blendDst=this.blendDst),this.blendEquation!==o&&(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!==Se&&(s.stencilFail=this.stencilFail),this.stencilZFail!==Se&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==Se&&(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),!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.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 $s extends Ws{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Gs(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 as,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 qs=Xs();function Xs(){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 Ys(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=je(e,-65504,65504),qs.floatView[0]=e;const t=qs.uint32View[0],s=t>>23&511;return qs.baseTable[s]+((8388607&t)>>qs.shiftTable[s])}function Ks(e){const t=e>>10;return qs.uint32View[0]=qs.mantissaTable[qs.offsetTable[t]+(1023&e)]+qs.exponentTable[t],qs.floatView[0]}const Qs=new _t,Zs=new Ye;let Js=0;class ei{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:Js++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Ie,this.updateRanges=[],this.gpuType=z,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++)Zs.fromBufferAttribute(this,t),Zs.applyMatrix3(e),this.setXY(t,Zs.x,Zs.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)Qs.fromBufferAttribute(this,t),Qs.applyMatrix3(e),this.setXYZ(t,Qs.x,Qs.y,Qs.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)Qs.fromBufferAttribute(this,t),Qs.applyMatrix4(e),this.setXYZ(t,Qs.x,Qs.y,Qs.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Qs.fromBufferAttribute(this,t),Qs.applyNormalMatrix(e),this.setXYZ(t,Qs.x,Qs.y,Qs.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Qs.fromBufferAttribute(this,t),Qs.transformDirection(e),this.setXYZ(t,Qs.x,Qs.y,Qs.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=$e(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=qe(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=$e(t,this.array)),t}setX(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=$e(t,this.array)),t}setY(e,t){return this.normalized&&(t=qe(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=$e(t,this.array)),t}setZ(e,t){return this.normalized&&(t=qe(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=$e(t,this.array)),t}setW(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=qe(t,this.array),s=qe(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=qe(t,this.array),s=qe(s,this.array),i=qe(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=qe(t,this.array),s=qe(s,this.array),i=qe(i,this.array),r=qe(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!==Ie&&(e.usage=this.usage),e}}class ti extends ei{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class si extends ei{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class ii extends ei{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=Ks(this.array[e*this.itemSize]);return this.normalized&&(t=$e(t,this.array)),t}setX(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize]=Ys(t),this}getY(e){let t=Ks(this.array[e*this.itemSize+1]);return this.normalized&&(t=$e(t,this.array)),t}setY(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize+1]=Ys(t),this}getZ(e){let t=Ks(this.array[e*this.itemSize+2]);return this.normalized&&(t=$e(t,this.array)),t}setZ(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize+2]=Ys(t),this}getW(e){let t=Ks(this.array[e*this.itemSize+3]);return this.normalized&&(t=$e(t,this.array)),t}setW(e,t){return this.normalized&&(t=qe(t,this.array)),this.array[e*this.itemSize+3]=Ys(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=qe(t,this.array),s=qe(s,this.array)),this.array[e+0]=Ys(t),this.array[e+1]=Ys(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=qe(t,this.array),s=qe(s,this.array),i=qe(i,this.array)),this.array[e+0]=Ys(t),this.array[e+1]=Ys(s),this.array[e+2]=Ys(i),this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=qe(t,this.array),s=qe(s,this.array),i=qe(i,this.array),r=qe(r,this.array)),this.array[e+0]=Ys(t),this.array[e+1]=Ys(s),this.array[e+2]=Ys(i),this.array[e+3]=Ys(r),this}}class ri extends ei{constructor(e,t,s){super(new Float32Array(e),t,s)}}let ni=0;const ai=new Kt,oi=new ws,hi=new _t,li=new wt,ui=new wt,ci=new _t;class di extends Oe{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:ni++}),this.uuid=Ge(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Ze(e)?si:ti)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return 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 Ke).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 ai.makeRotationFromQuaternion(e),this.applyMatrix4(ai),this}rotateX(e){return ai.makeRotationX(e),this.applyMatrix4(ai),this}rotateY(e){return ai.makeRotationY(e),this.applyMatrix4(ai),this}rotateZ(e){return ai.makeRotationZ(e),this.applyMatrix4(ai),this}translate(e,t,s){return ai.makeTranslation(e,t,s),this.applyMatrix4(ai),this}scale(e,t,s){return ai.makeScale(e,t,s),this.applyMatrix4(ai),this}lookAt(e){return oi.lookAt(e),oi.updateMatrix(),this.applyMatrix4(oi.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(hi).negate(),this.translate(hi.x,hi.y,hi.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&&console.warn("THREE.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 wt);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new _t(-1/0,-1/0,-1/0),new _t(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?(ci.addVectors(this.boundingBox.min,li.min),this.boundingBox.expandByPoint(ci),ci.addVectors(this.boundingBox.max,li.max),this.boundingBox.expandByPoint(ci)):(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))&&console.error('THREE.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 Vt);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new _t,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];ui.setFromBufferAttribute(s),this.morphTargetsRelative?(ci.addVectors(li.min,ui.min),li.expandByPoint(ci),ci.addVectors(li.max,ui.max),li.expandByPoint(ci)):(li.expandByPoint(ui.min),li.expandByPoint(ui.max))}li.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)ci.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(ci));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++)ci.fromBufferAttribute(n,t),a&&(hi.fromBufferAttribute(e,t),ci.add(hi)),i=Math.max(i,s.distanceToSquared(ci))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.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 console.error("THREE.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 ei(new Float32Array(4*s.count),4));const n=this.getAttribute("tangent"),a=[],o=[];for(let e=0;e<s.count;e++)a[e]=new _t,o[e]=new _t;const h=new _t,l=new _t,u=new _t,c=new Ye,d=new Ye,p=new Ye,m=new _t,g=new _t;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 _t,x=new _t,_=new _t,v=new _t;function T(e){_.fromBufferAttribute(i,e),v.copy(_);const t=a[e];b.copy(t),b.sub(_.multiplyScalar(_.dot(t))).normalize(),x.crossVectors(v,t);const s=x.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 ei(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 _t,r=new _t,n=new _t,a=new _t,o=new _t,h=new _t,l=new _t,u=new _t;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++)ci.fromBufferAttribute(e,t),ci.normalize(),e.setXYZ(t,ci.x,ci.y,ci.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 ei(n,i,r)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new di,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.6,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={center:a.center.toArray(),radius:a.radius}),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"})}}const pi=new Kt,mi=new Yt,gi=new Vt,fi=new _t,yi=new _t,bi=new _t,xi=new _t,_i=new _t,vi=new _t,Ti=new _t,wi=new _t;class Si extends ws{constructor(e=new di,t=new $s){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,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){vi.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=a[s],o=r[s];0!==i&&(_i.fromBufferAttribute(o,e),n?vi.addScaledVector(_i,i):vi.addScaledVector(_i.sub(t),i))}t.add(vi)}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(),gi.copy(s.boundingSphere),gi.applyMatrix4(r),mi.copy(e.ray).recast(e.near),!1===gi.containsPoint(mi.origin)){if(null===mi.intersectSphere(gi,fi))return;if(mi.origin.distanceToSquared(fi)>(e.far-e.near)**2)return}pi.copy(r).invert(),mi.copy(e.ray).applyMatrix4(pi),null!==s.boundingBox&&!1===mi.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,mi)}}_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=Mi(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=Mi(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=Mi(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=Mi(this,n,e,s,h,l,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function Mi(e,t,s,i,r,n,a,o,h,l){e.getVertexPosition(o,yi),e.getVertexPosition(h,bi),e.getVertexPosition(l,xi);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;wi.copy(o),wi.applyMatrix4(e.matrixWorld);const l=s.ray.origin.distanceTo(wi);return l<s.near||l>s.far?null:{distance:l,point:wi.clone(),object:e}}(e,t,s,i,yi,bi,xi,Ti);if(u){const e=new _t;Os.getBarycoord(Ti,yi,bi,xi,e),r&&(u.uv=Os.getInterpolatedAttribute(r,o,h,l,e,new Ye)),n&&(u.uv1=Os.getInterpolatedAttribute(n,o,h,l,e,new Ye)),a&&(u.normal=Os.getInterpolatedAttribute(a,o,h,l,e,new _t),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const t={a:o,b:h,c:l,normal:new _t,materialIndex:0};Os.getNormal(yi,bi,xi,t.normal),u.face=t,u.barycoord=e}return u}class Ni extends di{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,x=p/f,_=n/2,v=p/2,T=m/2,w=g+1,S=f+1;let M=0,N=0;const E=new _t;for(let n=0;n<S;n++){const a=n*x-v;for(let o=0;o<w;o++){const c=o*b-_;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,l.push(E.x,E.y,E.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+w*e,i=c+t+w*(e+1),r=c+(t+1)+w*(e+1),n=c+(t+1)+w*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 Ni(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Ei(e){const t={};for(const s in e){t[s]={};for(const i in e[s]){const r=e[s][i];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?r.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[s][i]=null):t[s][i]=r.clone():Array.isArray(r)?t[s][i]=r.slice():t[s][i]=r}}return t}class Ai extends Ws{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==e&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Ei(e.uniforms),this.uniformsGroups=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].clone());return t}(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const i=this.uniforms[s].value;i&&i.isTexture?t.uniforms[s]={type:"t",value:i.toJSON(e).uuid}:i&&i.isColor?t.uniforms[s]={type:"c",value:i.getHex()}:i&&i.isVector2?t.uniforms[s]={type:"v2",value:i.toArray()}:i&&i.isVector3?t.uniforms[s]={type:"v3",value:i.toArray()}:i&&i.isVector4?t.uniforms[s]={type:"v4",value:i.toArray()}:i&&i.isMatrix3?t.uniforms[s]={type:"m3",value:i.toArray()}:i&&i.isMatrix4?t.uniforms[s]={type:"m4",value:i.toArray()}:t.uniforms[s]={value:i}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const e in this.extensions)!0===this.extensions[e]&&(s[e]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class Ci extends ws{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Kt,this.projectionMatrix=new Kt,this.projectionMatrixInverse=new Kt,this.coordinateSystem=Le}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Ri=new _t,Pi=new Ye,Fi=new Ye;class Ii extends Ci{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*Ve*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*ze*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Ve*Math.atan(Math.tan(.5*ze*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){Ri.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ri.x,Ri.y).multiplyScalar(-e/Ri.z),Ri.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Ri.x,Ri.y).multiplyScalar(-e/Ri.z)}getViewSize(e,t){return this.getViewBounds(e,Pi,Fi),t.subVectors(Fi,Pi)}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*ze*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.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}}const Bi=-90;class Li extends ws{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Ii(Bi,1,e,t);i.layers=this.layers,this.add(i);const r=new Ii(Bi,1,e,t);r.layers=this.layers,this.add(r);const n=new Ii(Bi,1,e,t);n.layers=this.layers,this.add(n);const a=new Ii(Bi,1,e,t);a.layers=this.layers,this.add(a);const o=new Ii(Bi,1,e,t);o.layers=this.layers,this.add(o);const h=new Ii(Bi,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===Le)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!==De)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,e.setRenderTarget(s,0,i),e.render(t,r),e.setRenderTarget(s,1,i),e.render(t,n),e.setRenderTarget(s,2,i),e.render(t,a),e.setRenderTarget(s,3,i),e.render(t,o),e.setRenderTarget(s,4,i),e.render(t,h),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),e.render(t,l),e.setRenderTarget(u,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class Di extends mt{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 Oi extends yt{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Di(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:P}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const s={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Ni(5,5,5),r=new Ai({name:"CubemapFromEquirect",uniforms:Ei(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const n=new Si(i,r),a=t.minFilter;t.minFilter===I&&(t.minFilter=P);return new Li(1,10,this).update(e,n),t.minFilter=a,n.geometry.dispose(),n.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)}}let ki=class extends ws{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Ui={type:"move"};class zi{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new ki,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 ki,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new _t,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new _t),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new ki,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new _t,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new _t),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));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(Ui)))}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 ki;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}class Vi extends ws{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 as,this.environmentIntensity=1,this.environmentRotation=new as,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}}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=Ie,this.updateRanges=[],this.version=0,this.uuid=Ge()}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=Ge()),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=Ge()),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 _t;class Hi{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=$e(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=qe(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=qe(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=qe(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=qe(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=qe(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=$e(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=$e(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=$e(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=$e(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=qe(t,this.array),s=qe(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=qe(t,this.array),s=qe(s,this.array),i=qe(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=qe(t,this.array),s=qe(s,this.array),i=qe(i,this.array),r=qe(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){console.log("THREE.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 ei(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 Hi(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){console.log("THREE.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}}}class Wi extends Ws{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Gs(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}}class $i extends mt{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 qi extends ei{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 Xi=new _t,Yi=new _t,Ki=new Ke;class Qi{constructor(e=new _t(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=Xi.subVectors(s,t).cross(Yi.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(Xi),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||Ki.getNormalMatrix(e),i=this.coplanarPoint(Xi).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 Zi=new Vt,Ji=new _t;class er{constructor(e=new Qi,t=new Qi,s=new Qi,i=new Qi,r=new Qi,n=new Qi){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){const s=this.planes,i=e.elements,r=i[0],n=i[1],a=i[2],o=i[3],h=i[4],l=i[5],u=i[6],c=i[7],d=i[8],p=i[9],m=i[10],g=i[11],f=i[12],y=i[13],b=i[14],x=i[15];if(s[0].setComponents(o-r,c-h,g-d,x-f).normalize(),s[1].setComponents(o+r,c+h,g+d,x+f).normalize(),s[2].setComponents(o+n,c+l,g+p,x+y).normalize(),s[3].setComponents(o-n,c-l,g-p,x-y).normalize(),s[4].setComponents(o-a,c-u,g-m,x-b).normalize(),t===Le)s[5].setComponents(o+a,c+u,g+m,x+b).normalize();else{if(t!==De)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);s[5].setComponents(a,u,m,b).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Zi.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Zi.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Zi)}intersectsSprite(e){return Zi.center.set(0,0,0),Zi.radius=.7071067811865476,Zi.applyMatrix4(e.matrixWorld),this.intersectsSphere(Zi)}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(Ji.x=i.normal.x>0?e.max.x:e.min.x,Ji.y=i.normal.y>0?e.max.y:e.min.y,Ji.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Ji)<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 tr=new Kt,sr=new er;class ir{constructor(){this.coordinateSystem=Le}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(tr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),sr.setFromProjectionMatrix(tr,this.coordinateSystem),sr.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(tr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),sr.setFromProjectionMatrix(tr,this.coordinateSystem),sr.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(tr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),sr.setFromProjectionMatrix(tr,this.coordinateSystem),sr.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(tr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),sr.setFromProjectionMatrix(tr,this.coordinateSystem),sr.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(tr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),sr.setFromProjectionMatrix(tr,this.coordinateSystem),sr.containsPoint(e))return!0}return!1}clone(){return new ir}}class rr extends Ws{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Gs(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 nr extends Ws{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Gs(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 ar extends mt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=A,this.minFilter=A,this.generateMipmaps=!1,this.needsUpdate=!0}}class or extends mt{constructor(e,t,s=1014,i,r,n,a=1003,o=1003,h,l=1026){if(l!==W&&l!==$)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super(null,i,r,n,a,o,l,s,h),this.isDepthTexture=!0,this.image={width:e,height:t},this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ct(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 hr extends or{constructor(e=1,t=1,s=1){super(e,t),this.isDepthArrayTexture=!0,this.image={width:e,height:t,depth:s},this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class lr extends di{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 Ye,m=new _t;let y=0;const b=!0===s?e:t,x=!0===s?1:-1;for(let e=1;e<=i;e++)u.push(0,g*x,0),c.push(0,x,0),d.push(.5,.5),p++;const _=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*x,m.z=b*s,u.push(m.x,m.y,m.z),c.push(0,x,0),n.x=.5*s+.5,n.y=.5*r*x+.5,d.push(n.x,n.y),p++}for(let e=0;e<i;e++){const t=r+e,i=_+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 _t,y=new _t;let b=0;const x=(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,x,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 lr(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class ur extends di{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 ur(e.width,e.height,e.widthSegments,e.heightSegments)}}class cr extends di{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 _t,c=new _t,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 cr(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class dr extends Ws{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Gs(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 pr extends Ws{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Gs(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 Gs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(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 as,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 mr extends pr{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 Ye(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return je(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 Gs(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 Gs(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Gs(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 Ws{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Gs(16777215),this.specular=new Gs(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Gs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new as,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class fr extends Ws{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Gs(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Gs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(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 yr extends Ws{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(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 br extends Ws{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Gs(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Gs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new as,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class xr extends Ws{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Gs(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ye(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,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.flatShading=e.flatShading,this.fog=e.fog,this}}class _r 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 vr extends ws{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Gs(e),this.intensity=t}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,void 0!==this.groundColor&&(t.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(t.object.distance=this.distance),void 0!==this.angle&&(t.object.angle=this.angle),void 0!==this.decay&&(t.object.decay=this.decay),void 0!==this.penumbra&&(t.object.penumbra=this.penumbra),void 0!==this.shadow&&(t.object.shadow=this.shadow.toJSON()),void 0!==this.target&&(t.object.target=this.target.uuid),t}}class Tr extends vr{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(ws.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Gs(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const wr=new Kt,Sr=new _t,Mr=new _t;class Nr{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Ye(512,512),this.mapType=B,this.map=null,this.mapPass=null,this.matrix=new Kt,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new er,this._frameExtents=new Ye(1,1),this._viewportCount=1,this._viewports=[new gt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;Sr.setFromMatrixPosition(e.matrixWorld),t.position.copy(Sr),Mr.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Mr),t.updateMatrixWorld(),wr.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(wr),s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(wr)}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}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}}class Er extends Nr{constructor(){super(new Ii(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,s=2*Ve*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height,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 Ar extends vr{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(ws.DEFAULT_UP),this.updateMatrix(),this.target=new ws,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new Er}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}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.shadow=e.shadow.clone(),this}}const Cr=new Kt,Rr=new _t,Pr=new _t;class Fr extends Nr{constructor(){super(new Ii(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Ye(4,2),this._viewportCount=6,this._viewports=[new gt(2,1,1,1),new gt(0,1,1,1),new gt(3,1,1,1),new gt(1,1,1,1),new gt(3,0,1,1),new gt(1,0,1,1)],this._cubeDirections=[new _t(1,0,0),new _t(-1,0,0),new _t(0,0,1),new _t(0,0,-1),new _t(0,1,0),new _t(0,-1,0)],this._cubeUps=[new _t(0,1,0),new _t(0,1,0),new _t(0,1,0),new _t(0,1,0),new _t(0,0,1),new _t(0,0,-1)]}updateMatrices(e,t=0){const s=this.camera,i=this.matrix,r=e.distance||s.far;r!==s.far&&(s.far=r,s.updateProjectionMatrix()),Rr.setFromMatrixPosition(e.matrixWorld),s.position.copy(Rr),Pr.copy(s.position),Pr.add(this._cubeDirections[t]),s.up.copy(this._cubeUps[t]),s.lookAt(Pr),s.updateMatrixWorld(),i.makeTranslation(-Rr.x,-Rr.y,-Rr.z),Cr.multiplyMatrices(s.projectionMatrix,s.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Cr)}}class Ir extends vr{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 Fr}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}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}}class Br extends Ci{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.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 Lr extends Nr{constructor(){super(new Br(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Dr extends vr{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ws.DEFAULT_UP),this.updateMatrix(),this.target=new ws,this.shadow=new Lr}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class Or extends vr{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class kr extends vr{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 Ur{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new _t)}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 zr extends vr{constructor(e=new Ur,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}fromJSON(e){return this.intensity=e.intensity,this.sh.fromArray(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}class Vr extends Ii{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Gr extends ft{constructor(e=1,t=1,s=1,i={}){super(e,t,i),this.isRenderTargetArray=!0,this.depth=s,this.texture=new bt(null,e,t,s),this.texture.isRenderTargetTexture=!0}}class jr 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 Hr{constructor(e,t,s,i){Hr.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}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:a}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=a);const Wr=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveMap","envMap","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"];class $r{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Wr,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),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}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={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 null!==e.renderer.overrideNodes.modelViewMatrix||null!==e.renderer.overrideNodes.modelNormalViewMatrix}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){const{object:t,material:s,geometry:i}=e,r=this.getRenderObjectData(e);if(!0!==r.worldMatrix.equals(t.matrixWorld))return r.worldMatrix.copy(t.matrixWorld),!1;const n=r.material;for(const e in n){const t=n[e],i=s[e];if(void 0!==t.equals){if(!1===t.equals(i))return t.copy(i),!1}else if(!0===i.isTexture){if(t.id!==i.id||t.version!==i.version)return t.id=i.id,t.version=i.version,!1}else if(t!==i)return n[e]=i,!1}if(n.transmission>0){const{width:t,height:s}=e.context;if(r.bufferWidth!==t||r.bufferHeight!==s)return r.bufferWidth=t,r.bufferHeight=s,!1}const a=r.geometry,o=i.attributes,h=a.attributes,l=Object.keys(h),u=Object.keys(o);if(a.id!==i.id)return a.id=i.id,!1;if(l.length!==u.length)return r.geometry.attributes=this.getAttributesData(o),!1;for(const e of l){const t=h[e],s=o[e];if(void 0===s)return delete h[e],!1;if(t.version!==s.version)return t.version=s.version,!1}const c=i.index,d=a.indexVersion,p=c?c.version:null;if(d!==p)return a.indexVersion=p,!1;if(a.drawRange.start!==i.drawRange.start||a.drawRange.count!==i.drawRange.count)return a.drawRange.start=i.drawRange.start,a.drawRange.count=i.drawRange.count,!1;if(r.morphTargetInfluences){let e=!1;for(let s=0;s<r.morphTargetInfluences.length;s++)r.morphTargetInfluences[s]!==t.morphTargetInfluences[s]&&(e=!0);if(e)return!0}return r.center&&!1===r.center.equals(t.center)?(r.center.copy(t.center),!0):(null!==e.bundle&&(r.version=e.bundle.version),!0)}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;return!0!==this.equals(e)}}function qr(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 Xr=e=>qr(e),Yr=(...e)=>qr(e);function Kr(e,t=!1){const s=[];!0===e.isNode&&(s.push(e.id),e=e.getSelf());for(const{property:i,childNode:r}of Qr(e))s.push(qr(i.slice(0,-4)),r.getCacheKey(t));return qr(s)}function*Qr(e,t=!1){for(const s in e){if(!0===s.startsWith("_"))continue;const i=e[s];if(!0===Array.isArray(i))for(let e=0;e<i.length;e++){const r=i[e];r&&(!0===r.isNode||t&&"function"==typeof r.toJSON)&&(yield{property:s,index:e,childNode:r})}else if(i&&!0===i.isNode)yield{property:s,childNode:i};else if("object"==typeof i)for(const e in i){const r=i[e];r&&(!0===r.isNode||t&&"function"==typeof r.toJSON)&&(yield{property:s,index:e,childNode:r})}}}const Zr=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Jr=new WeakMap;function en(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 tn(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 Gs(...t):"vec2"===s?new Ye(...t):"vec3"===s?new _t(...t):"vec4"===s?new gt(...t):"mat2"===s?new Hr(...t):"mat3"===s?new Ke(...t):"mat4"===s?new Kt(...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 sn(e){let t=Jr.get(e);return void 0===t&&(t={},Jr.set(e,t)),t}const rn="vertex",nn="none",an="frame",on="render",hn="object",ln="readOnly",un="writeOnly",cn="readWrite",dn=["setup","analyze","generate"],pn=["fragment","vertex","compute"],mn=["x","y","z","w"];let gn=0;class fn extends Oe{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=nn,this.updateBeforeType=nn,this.updateAfterType=nn,this.uuid=Xe.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:gn++})}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.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,an)}onRenderUpdate(e){return this.onUpdate(e,on)}onObjectUpdate(e){return this.onUpdate(e,hn)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of Qr(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Yr(Kr(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}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}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){if(1===e.increaseUsage(this)){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);e.addNode(this),e.addChain(this);let i=null;const r=e.getBuildStage();if("setup"===r){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0;const s=this.setup(e),i=s&&!0===s.isNode;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)}i&&s.build(e),t.outputNode=s}i=t.outputNode||null}else if("analyze"===r)this.analyze(e);else if("generate"===r){if(1===this.generate.length){const s=this.getNodeType(e),r=e.getDataFromNode(this);i=r.snippet,void 0===i?void 0===r.generated?(r.generated=!0,i=this.generate(e)||"",r.snippet=i):(console.warn("THREE.Node: Recursion detected.",this),i=""):void 0!==r.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),i=e.format(i,s,t)}else i=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),i}getSerializeChildren(){return Qr(this)}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.6,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}}class yn extends fn{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)}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 bn extends fn{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 xn extends fn{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 _n extends xn{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){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${s}()' type.`);break}let r,h=t.getNodeType(e),l=e.getTypeLength(h);o+l>i&&(console.error(`THREE.TSL: Length of '${s}()' data exceeds maximum length of output type.`),l=i-o,h=e.getTypeFromLength(l)),o+=l,r=t.build(e,h);const u=e.getComponentType(h);u!==n&&(r=e.format(r,u,n)),a.push(r)}const h=`${e.getType(s)}( ${a.join(", ")} )`;return e.format(h,s,t)}}const vn=mn.join("");class Tn extends fn{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(mn.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))}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===vn.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 wn extends xn{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),l=e.getTypeLength(r),u=[];for(let e=0;e<l;e++){const t=mn[e];t===s[0]?(u.push(o),e+=s.length-1):u.push(h+"."+t)}return`${e.getType(r)}( ${u.join(", ")} )`}}class Sn extends xn{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 l=0;for(let e=0;e<o;e++){const s=mn[e];s===t[l]?(h.push("1.0 - "+a+"."+s),l++):h.push(a+"."+s)}return`${e.getType(i)}( ${h.join(", ")} )`}}class Mn extends fn{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?en(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=en(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)?tn(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){console.warn("Abstract function.")}}const Nn=/float|u?int/;class En extends Mn{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 Nn.test(s)&&Nn.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class An extends fn{static get type(){return"MemberNode"}constructor(e,t){super(),this.node=e,this.property=t,this.isMemberNode=!0}getNodeType(e){return this.node.getMemberType(e,this.property)}generate(e){return this.node.build(e)+"."+this.property}}let Cn=null;const Rn=new Map;function Pn(e,t){if(Rn.has(e))console.warn(`THREE.TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);Rn.set(e,t)}}const Fn=e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),In=e=>Fn(e).split("").sort().join(""),Bn={setup(e,t){const s=t.shift();return e(ra(s),...t)},get(e,t,s){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(Cn.assign(s,...e),s);if(Rn.has(t)){const i=Rn.get(t);return e.isStackNode?(...e)=>s.add(i(...e)):(...e)=>i(s,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Rn.has(t.slice(0,t.length-6))){const i=Rn.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>s.assign(e[0],i(...e)):(...e)=>s.assign(i(s,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=Fn(t),ia(new Tn(s,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=In(t.slice(3).toLowerCase()),s=>ia(new wn(e,t,s));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=In(t.slice(4).toLowerCase()),()=>ia(new Sn(ia(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),ia(new Tn(e,t));if(!0===/^\d+$/.test(t))return ia(new yn(s,new En(Number(t),"uint")));if(!0===/^get$/.test(t))return e=>ia(new An(s,e))}return Reflect.get(e,t,s)},set:(e,t,s,i)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,s,i):(i[t].assign(s),!0)},Ln=new WeakMap,Dn=new WeakMap,On=function(e,t=null){for(const s in e)e[s]=ia(e[s],t);return e},kn=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=ia(e[i],t);return e},Un=function(e,t=null,s=null,i=null){const r=e=>ia(null!==i?Object.assign(e,i):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?(console.error(`THREE.TSL: "${s}" parameter length is less than minimum required.`),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(console.error(`THREE.TSL: "${s}" parameter length exceeds limit.`),t.slice(0,o)):t}return null===t?n=(...t)=>r(new e(...na(l(t)))):null!==s?(s=ia(s),n=(...i)=>r(new e(t,...na(l(i)),s))):n=(...s)=>r(new e(t,...na(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},zn=function(e,...t){return ia(new e(...na(t)))};class Vn extends fn{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:s}=this,i=e.getNodeProperties(t);if(i.onceOutput)return i.onceOutput;let r=null;if(t.layout){let i=Dn.get(e.constructor);void 0===i&&(i=new WeakMap,Dn.set(e.constructor,i));let n=i.get(t);void 0===n&&(n=ia(e.buildFunctionNode(t)),i.set(t,n)),e.addInclude(n),r=ia(n.call(s))}else{const i=t.jsFunc,n=null!==s||i.length>1?i(s||[],e):i(e);r=ia(n)}return t.once&&(i.onceOutput=r),r}getOutputNode(e){const t=e.getNodeProperties(this);return null===t.outputNode&&(t.outputNode=this.setupOutput(e)),t.outputNode}setup(e){return this.getOutputNode(e)}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){return this.getOutputNode(e).build(e,t)}}class Gn extends fn{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return ra(e),ia(new Vn(this,e))}setup(){return this.call()}}const jn=[!1,!0],Hn=[0,1,2,3],Wn=[-1,-2],$n=[.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],qn=new Map;for(const e of jn)qn.set(e,new En(e));const Xn=new Map;for(const e of Hn)Xn.set(e,new En(e,"uint"));const Yn=new Map([...Xn].map((e=>new En(e.value,"int"))));for(const e of Wn)Yn.set(e,new En(e,"int"));const Kn=new Map([...Yn].map((e=>new En(e.value))));for(const e of $n)Kn.set(e,new En(e));for(const e of $n)Kn.set(-e,new En(-e));const Qn={bool:qn,uint:Xn,ints:Yn,float:Kn},Zn=new Map([...qn,...Kn]),Jn=(e,t)=>Zn.has(e)?Zn.get(e):!0===e.isNode?e:new En(e,t),ea=function(e,t=null){return(...s)=>{if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every((e=>"object"!=typeof e)))&&(s=[tn(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return ia(t.get(s[0]));if(1===s.length){const t=Jn(s[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?ia(t):ia(new bn(t,e))}const i=s.map((e=>Jn(e)));return ia(new _n(i,e))}},ta=e=>"object"==typeof e&&null!==e?e.value:e;function sa(e,t){return new Proxy(new Gn(e,t),Bn)}const ia=(e,t=null)=>function(e,t=null){const s=en(e);if("node"===s){let t=Ln.get(e);return void 0===t&&(t=new Proxy(e,Bn),Ln.set(e,t),Ln.set(t,t)),t}return null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?ia(Jn(e,t)):"shader"===s?la(e):e}(e,t),ra=(e,t=null)=>new On(e,t),na=(e,t=null)=>new kn(e,t),aa=(...e)=>new Un(...e),oa=(...e)=>new zn(...e);let ha=0;const la=(e,t=null)=>{let s=null;null!==t&&("object"==typeof t?s=t.return:("string"==typeof t?s=t:console.error("THREE.TSL: Invalid layout type."),t=null));const i=new sa(e,s),r=(...e)=>{let t;ra(e),t=e[0]&&e[0].isNode?[...e]:e[0];const r=i.call(t);return"void"===s&&r.toStack(),r};if(r.shaderNode=i,r.setLayout=e=>(i.setLayout(e),r),r.once=()=>(i.once=!0,r),null!==t){if("object"!=typeof t.inputs){const e={name:"fn"+ha++,type:s,inputs:[]};for(const s in t)"return"!==s&&e.inputs.push({name:s,type:t[s]});t=e}r.setLayout(t)}return r};Pn("toGlobal",(e=>(e.global=!0,e)));const ua=e=>{Cn=e},ca=()=>Cn,da=(...e)=>Cn.If(...e);function pa(e){return Cn&&Cn.add(e),e}Pn("toStack",pa);const ma=new ea("color"),ga=new ea("float",Qn.float),fa=new ea("int",Qn.ints),ya=new ea("uint",Qn.uint),ba=new ea("bool",Qn.bool),xa=new ea("vec2"),_a=new ea("ivec2"),va=new ea("uvec2"),Ta=new ea("bvec2"),wa=new ea("vec3"),Sa=new ea("ivec3"),Ma=new ea("uvec3"),Na=new ea("bvec3"),Ea=new ea("vec4"),Aa=new ea("ivec4"),Ca=new ea("uvec4"),Ra=new ea("bvec4"),Pa=new ea("mat2"),Fa=new ea("mat3"),Ia=new ea("mat4");Pn("toColor",ma),Pn("toFloat",ga),Pn("toInt",fa),Pn("toUint",ya),Pn("toBool",ba),Pn("toVec2",xa),Pn("toIVec2",_a),Pn("toUVec2",va),Pn("toBVec2",Ta),Pn("toVec3",wa),Pn("toIVec3",Sa),Pn("toUVec3",Ma),Pn("toBVec3",Na),Pn("toVec4",Ea),Pn("toIVec4",Aa),Pn("toUVec4",Ca),Pn("toBVec4",Ra),Pn("toMat2",Pa),Pn("toMat3",Fa),Pn("toMat4",Ia);Pn("element",aa(yn).setParameterLength(2)),Pn("convert",((e,t)=>ia(new bn(ia(e),t)))),Pn("append",(e=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),pa(e))));class Ba extends fn{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}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 La=(e,t)=>ia(new Ba(e,t)),Da=(e,t)=>ia(new Ba(e,t,!0)),Oa=oa(Ba,"vec4","DiffuseColor"),ka=oa(Ba,"vec3","EmissiveColor"),Ua=oa(Ba,"float","Roughness"),za=oa(Ba,"float","Metalness"),Va=oa(Ba,"float","Clearcoat"),Ga=oa(Ba,"float","ClearcoatRoughness"),ja=oa(Ba,"vec3","Sheen"),Ha=oa(Ba,"float","SheenRoughness"),Wa=oa(Ba,"float","Iridescence"),$a=oa(Ba,"float","IridescenceIOR"),qa=oa(Ba,"float","IridescenceThickness"),Xa=oa(Ba,"float","AlphaT"),Ya=oa(Ba,"float","Anisotropy"),Ka=oa(Ba,"vec3","AnisotropyT"),Qa=oa(Ba,"vec3","AnisotropyB"),Za=oa(Ba,"color","SpecularColor"),Ja=oa(Ba,"float","SpecularF90"),eo=oa(Ba,"float","Shininess"),to=oa(Ba,"vec4","Output"),so=oa(Ba,"float","dashSize"),io=oa(Ba,"float","gapSize"),ro=oa(Ba,"float","IOR"),no=oa(Ba,"float","Transmission"),ao=oa(Ba,"float","Thickness"),oo=oa(Ba,"float","AttenuationDistance"),ho=oa(Ba,"color","AttenuationColor"),lo=oa(Ba,"float","Dispersion");class uo extends fn{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 co=e=>new uo(e),po=(e,t=0)=>new uo(e,!0,t),mo=po("frame"),go=po("render"),fo=co("object");class yo extends Mn{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=fo}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const s=this.getSelf();return e=e.bind(s),super.onUpdate((t=>{const i=e(t,s);void 0!==i&&(this.value=i)}),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.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,s,t)}}const bo=(e,t)=>{const s=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e),i=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return ia(new yo(i,s))};class xo extends xn{static get type(){return"ArrayNode"}constructor(e,t,s=null){super(e),this.count=t,this.values=s,this.isArrayNode=!0}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}Pn("toArray",((e,t)=>((...e)=>{let t;if(1===e.length){const s=e[0];t=new xo(null,s.length,s)}else{const s=e[0],i=e[1];t=new xo(s,i)}return ia(t)})(Array(t).fill(e))));class _o extends xn{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}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 mn.join("").slice(0,s)!==t.components}return!1}generate(e,t){const{targetNode:s,sourceNode:i}=this,r=this.needsSplitAssign(e),n=s.getNodeType(e),a=s.context({assign:!0}).build(e),o=i.build(e,n),h=i.getNodeType(e),l=e.getDataFromNode(this);let u;if(!0===l.initialized)"void"!==t&&(u=a);else if(r){const i=e.getVarFromNode(this,null,n),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`,this);const h=s.node.context({assign:!0}).build(e);for(let t=0;t<s.components.length;t++){const i=s.components[t];e.addLineFlowCode(`${h}.${i} = ${r}[ ${t} ]`,this)}"void"!==t&&(u=a)}else u=`${a} = ${o}`,"void"!==t&&"void"!==h||(e.addLineFlowCode(u,this),"void"!==t&&(u=a));return l.initialized=!0,e.format(u,n,t)}}Pn("assign",aa(_o).setParameterLength(2));class vo extends xn{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)}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)console.error("THREE.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(console.error("THREE.TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(ga(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)):(console.error(`THREE.TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(n(ga(0),e)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}Pn("call",((e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?na(t):ra(t[0]),ia(new vo(ia(e),t)))));const To={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class wo extends xn{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new wo(e,t,s);for(let t=0;t<i.length-1;t++)r=new wo(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(To[this.op],t)}getNodeType(e){const t=this.op,s=this.aNode,i=this.bNode,r=s.getNodeType(e),n=void 0!==i?i.getNodeType(e):null;if("void"===r||"void"===n)return"void";if("%"===t)return r;if("~"===t||"&"===t||"|"===t||"^"===t||">>"===t||"<<"===t)return e.getIntegerType(r);if("!"===t||"&&"===t||"||"===t||"^^"===t)return"bool";if("=="===t||"!="===t||"<"===t||">"===t||"<="===t||">="===t){const t=Math.max(e.getTypeLength(r),e.getTypeLength(n));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(r)){if("float"===n)return r;if(e.isVector(n))return e.getVectorFromMatrix(r);if(e.isMatrix(n))return r}else if(e.isMatrix(n)){if("float"===r)return n;if(e.isVector(r))return e.getVectorFromMatrix(n)}return e.getTypeLength(n)>e.getTypeLength(r)?n:r}generate(e,t){const s=this.op,i=this.aNode,r=this.bNode,n=this.getNodeType(e);let a=null,o=null;"void"!==n?(a=i.getNodeType(e),o=void 0!==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=void 0!==r?r.build(e,o):null,u=e.getFunctionOperator(s);if("void"!==t){const i=e.renderer.coordinateSystem===Le;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 So=aa(wo,"+").setParameterLength(2,1/0).setName("add"),Mo=aa(wo,"-").setParameterLength(2,1/0).setName("sub"),No=aa(wo,"*").setParameterLength(2,1/0).setName("mul"),Eo=aa(wo,"/").setParameterLength(2,1/0).setName("div"),Ao=aa(wo,"%").setParameterLength(2).setName("mod"),Co=aa(wo,"==").setParameterLength(2).setName("equal"),Ro=aa(wo,"!=").setParameterLength(2).setName("notEqual"),Po=aa(wo,"<").setParameterLength(2).setName("lessThan"),Fo=aa(wo,">").setParameterLength(2).setName("greaterThan"),Io=aa(wo,"<=").setParameterLength(2).setName("lessThanEqual"),Bo=aa(wo,">=").setParameterLength(2).setName("greaterThanEqual"),Lo=aa(wo,"&&").setParameterLength(2,1/0).setName("and"),Do=aa(wo,"||").setParameterLength(2,1/0).setName("or"),Oo=aa(wo,"!").setParameterLength(1).setName("not"),ko=aa(wo,"^^").setParameterLength(2).setName("xor"),Uo=aa(wo,"&").setParameterLength(2).setName("bitAnd"),zo=aa(wo,"~").setParameterLength(2).setName("bitNot"),Vo=aa(wo,"|").setParameterLength(2).setName("bitOr"),Go=aa(wo,"^").setParameterLength(2).setName("bitXor"),jo=aa(wo,"<<").setParameterLength(2).setName("shiftLeft"),Ho=aa(wo,">>").setParameterLength(2).setName("shiftRight"),Wo=la((([e])=>(e.addAssign(1),e))),$o=la((([e])=>(e.subAssign(1),e))),qo=la((([e])=>{const t=fa(e).toConst();return e.addAssign(1),t})),Xo=la((([e])=>{const t=fa(e).toConst();return e.subAssign(1),t}));Pn("add",So),Pn("sub",Mo),Pn("mul",No),Pn("div",Eo),Pn("mod",Ao),Pn("equal",Co),Pn("notEqual",Ro),Pn("lessThan",Po),Pn("greaterThan",Fo),Pn("lessThanEqual",Io),Pn("greaterThanEqual",Bo),Pn("and",Lo),Pn("or",Do),Pn("not",Oo),Pn("xor",ko),Pn("bitAnd",Uo),Pn("bitNot",zo),Pn("bitOr",Vo),Pn("bitXor",Go),Pn("shiftLeft",jo),Pn("shiftRight",Ho),Pn("incrementBefore",Wo),Pn("decrementBefore",$o),Pn("increment",qo),Pn("decrement",Xo);Pn("remainder",((e,t)=>(console.warn('THREE.TSL: "remainder()" is deprecated. Use "mod( int( ... ) )" instead.'),Ao(e,t)))),Pn("modInt",((e,t)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),Ao(fa(e),fa(t)))));class Yo extends xn{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===Yo.MAX||e===Yo.MIN)&&arguments.length>3){let r=new Yo(e,t,s);for(let t=2;t<arguments.length-1;t++)r=new Yo(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===Yo.LENGTH||t===Yo.DISTANCE||t===Yo.DOT?"float":t===Yo.CROSS?"vec3":t===Yo.ALL||t===Yo.ANY?"bool":t===Yo.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}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===Yo.TRANSFORM_DIRECTION){let s=n,i=a;e.isMatrix(s.getNodeType(e))?i=Ea(wa(i),0):s=Ea(wa(s),0);const r=No(s,i).xyz;return uh(r).build(e,t)}if(s===Yo.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);if(s===Yo.ONE_MINUS)return Mo(1,n).build(e,t);if(s===Yo.RECIPROCAL)return Eo(1,n).build(e,t);if(s===Yo.DIFFERENCE)return bh(Mo(n,a)).build(e,t);{const l=[];return s===Yo.CROSS?l.push(n.build(e,i),a.build(e,i)):h===Le&&s===Yo.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),a.build(e,r)):h!==Le||s!==Yo.MIN&&s!==Yo.MAX?s===Yo.REFRACT?l.push(n.build(e,r),a.build(e,r),o.build(e,"float")):s===Yo.MIX?l.push(n.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(h===De&&s===Yo.ATAN&&null!==a&&(s="atan2"),"fragment"===e.shaderStage||s!==Yo.DFDX&&s!==Yo.DFDY||(console.warn(`THREE.TSL: '${s}' is not supported in the ${e.shaderStage} stage.`),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}}Yo.ALL="all",Yo.ANY="any",Yo.RADIANS="radians",Yo.DEGREES="degrees",Yo.EXP="exp",Yo.EXP2="exp2",Yo.LOG="log",Yo.LOG2="log2",Yo.SQRT="sqrt",Yo.INVERSE_SQRT="inversesqrt",Yo.FLOOR="floor",Yo.CEIL="ceil",Yo.NORMALIZE="normalize",Yo.FRACT="fract",Yo.SIN="sin",Yo.COS="cos",Yo.TAN="tan",Yo.ASIN="asin",Yo.ACOS="acos",Yo.ATAN="atan",Yo.ABS="abs",Yo.SIGN="sign",Yo.LENGTH="length",Yo.NEGATE="negate",Yo.ONE_MINUS="oneMinus",Yo.DFDX="dFdx",Yo.DFDY="dFdy",Yo.ROUND="round",Yo.RECIPROCAL="reciprocal",Yo.TRUNC="trunc",Yo.FWIDTH="fwidth",Yo.TRANSPOSE="transpose",Yo.BITCAST="bitcast",Yo.EQUALS="equals",Yo.MIN="min",Yo.MAX="max",Yo.STEP="step",Yo.REFLECT="reflect",Yo.DISTANCE="distance",Yo.DIFFERENCE="difference",Yo.DOT="dot",Yo.CROSS="cross",Yo.POW="pow",Yo.TRANSFORM_DIRECTION="transformDirection",Yo.MIX="mix",Yo.CLAMP="clamp",Yo.REFRACT="refract",Yo.SMOOTHSTEP="smoothstep",Yo.FACEFORWARD="faceforward";const Ko=ga(1e-6),Qo=ga(Math.PI),Zo=aa(Yo,Yo.ALL).setParameterLength(1),Jo=aa(Yo,Yo.ANY).setParameterLength(1),eh=aa(Yo,Yo.RADIANS).setParameterLength(1),th=aa(Yo,Yo.DEGREES).setParameterLength(1),sh=aa(Yo,Yo.EXP).setParameterLength(1),ih=aa(Yo,Yo.EXP2).setParameterLength(1),rh=aa(Yo,Yo.LOG).setParameterLength(1),nh=aa(Yo,Yo.LOG2).setParameterLength(1),ah=aa(Yo,Yo.SQRT).setParameterLength(1),oh=aa(Yo,Yo.INVERSE_SQRT).setParameterLength(1),hh=aa(Yo,Yo.FLOOR).setParameterLength(1),lh=aa(Yo,Yo.CEIL).setParameterLength(1),uh=aa(Yo,Yo.NORMALIZE).setParameterLength(1),ch=aa(Yo,Yo.FRACT).setParameterLength(1),dh=aa(Yo,Yo.SIN).setParameterLength(1),ph=aa(Yo,Yo.COS).setParameterLength(1),mh=aa(Yo,Yo.TAN).setParameterLength(1),gh=aa(Yo,Yo.ASIN).setParameterLength(1),fh=aa(Yo,Yo.ACOS).setParameterLength(1),yh=aa(Yo,Yo.ATAN).setParameterLength(1,2),bh=aa(Yo,Yo.ABS).setParameterLength(1),xh=aa(Yo,Yo.SIGN).setParameterLength(1),_h=aa(Yo,Yo.LENGTH).setParameterLength(1),vh=aa(Yo,Yo.NEGATE).setParameterLength(1),Th=aa(Yo,Yo.ONE_MINUS).setParameterLength(1),wh=aa(Yo,Yo.DFDX).setParameterLength(1),Sh=aa(Yo,Yo.DFDY).setParameterLength(1),Mh=aa(Yo,Yo.ROUND).setParameterLength(1),Nh=aa(Yo,Yo.RECIPROCAL).setParameterLength(1),Eh=aa(Yo,Yo.TRUNC).setParameterLength(1),Ah=aa(Yo,Yo.FWIDTH).setParameterLength(1),Ch=aa(Yo,Yo.TRANSPOSE).setParameterLength(1),Rh=aa(Yo,Yo.MIN).setParameterLength(2,1/0),Ph=aa(Yo,Yo.MAX).setParameterLength(2,1/0),Fh=aa(Yo,Yo.STEP).setParameterLength(2),Ih=aa(Yo,Yo.REFLECT).setParameterLength(2),Bh=aa(Yo,Yo.DISTANCE).setParameterLength(2),Lh=aa(Yo,Yo.DIFFERENCE).setParameterLength(2),Dh=aa(Yo,Yo.DOT).setParameterLength(2),Oh=aa(Yo,Yo.CROSS).setParameterLength(2),kh=aa(Yo,Yo.POW).setParameterLength(2),Uh=aa(Yo,Yo.POW,2).setParameterLength(1),zh=aa(Yo,Yo.POW,3).setParameterLength(1),Vh=aa(Yo,Yo.POW,4).setParameterLength(1),Gh=aa(Yo,Yo.TRANSFORM_DIRECTION).setParameterLength(2),jh=e=>Dh(e,e),Hh=aa(Yo,Yo.MIX).setParameterLength(3),Wh=(e,t=0,s=1)=>ia(new Yo(Yo.CLAMP,ia(e),ia(t),ia(s))),$h=aa(Yo,Yo.REFRACT).setParameterLength(3),qh=aa(Yo,Yo.SMOOTHSTEP).setParameterLength(3),Xh=aa(Yo,Yo.FACEFORWARD).setParameterLength(3),Yh=la((([e])=>{const t=Dh(e.xy,xa(12.9898,78.233)),s=Ao(t,Qo);return ch(dh(s).mul(43758.5453))}));Pn("all",Zo),Pn("any",Jo),Pn("equals",((e,t)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),Co(e,t)))),Pn("radians",eh),Pn("degrees",th),Pn("exp",sh),Pn("exp2",ih),Pn("log",rh),Pn("log2",nh),Pn("sqrt",ah),Pn("inverseSqrt",oh),Pn("floor",hh),Pn("ceil",lh),Pn("normalize",uh),Pn("fract",ch),Pn("sin",dh),Pn("cos",ph),Pn("tan",mh),Pn("asin",gh),Pn("acos",fh),Pn("atan",yh),Pn("abs",bh),Pn("sign",xh),Pn("length",_h),Pn("lengthSq",jh),Pn("negate",vh),Pn("oneMinus",Th),Pn("dFdx",wh),Pn("dFdy",Sh),Pn("round",Mh),Pn("reciprocal",Nh),Pn("trunc",Eh),Pn("fwidth",Ah),Pn("atan2",((e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),yh(e,t)))),Pn("min",Rh),Pn("max",Ph),Pn("step",Fh),Pn("reflect",Ih),Pn("distance",Bh),Pn("dot",Dh),Pn("cross",Oh),Pn("pow",kh),Pn("pow2",Uh),Pn("pow3",zh),Pn("pow4",Vh),Pn("transformDirection",Gh),Pn("mix",((e,t,s)=>Hh(t,s,e))),Pn("clamp",Wh),Pn("refract",$h),Pn("smoothstep",((e,t,s)=>qh(t,s,e))),Pn("faceForward",Xh),Pn("difference",Lh),Pn("saturate",(e=>Wh(e))),Pn("cbrt",(e=>No(xh(e),kh(bh(e),1/3)))),Pn("transpose",Ch),Pn("rand",Yh);class Kh extends fn{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 this.setup(e),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.cache(),s=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,r=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const n=e.getNodeProperties(this);n.condNode=t,n.ifNode=s.context({nodeBlock:s}),n.elseNode=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?La(s).build(e):"";i.nodeProperty=l;const u=r.build(e,"bool");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&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),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&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),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 Qh=aa(Kh).setParameterLength(2,3);Pn("select",Qh);Pn("cond",((...e)=>(console.warn("THREE.TSL: cond() has been renamed to select()."),Qh(...e))));class Zh extends fn{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){this.node.build(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value});const s=this.node.build(e);return e.setContext(t),s}generate(e,t){const s=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(s),i}}const Jh=aa(Zh).setParameterLength(1,2);Pn("context",Jh),Pn("label",((e,t)=>Jh(e,{label:t})));class el extends fn{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}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(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=e.getVectorType(this.getNodeType(e)),l=t.build(e,h),u=e.getVarFromNode(this,s,h,void 0,o),c=e.getPropertyName(u);let d=c;if(o)if(n)d=a?`const ${c}`:`let ${c}`;else{const s=e.getArrayCount(t);d=`const ${e.getVar(u.type,c,s)}`}return e.addLineFlowCode(`${d} = ${l}`,this),c}}const tl=aa(el);Pn("toVar",((e,t=null)=>tl(e,t).toStack())),Pn("toConst",((e,t=null)=>tl(e,t,!0).toStack()));Pn("temp",(e=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),tl(e))));class sl extends fn{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null}isGlobal(){return!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=this.node}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e)}analyze(e){return this.setupVarying(e),this.node.analyze(e)}generate(e){const t=e.getNodeProperties(this),s=this.setupVarying(e),i="fragment"===e.shaderStage&&!0===t.reassignPosition&&e.context.needsPositionReassign;if(void 0===t.propertyName||i){const r=this.getNodeType(e),n=e.getPropertyName(s,rn);e.flowNodeFromShaderStage(rn,this.node,r,n),t.propertyName=n,i?t.reassignPosition=!1:void 0===t.reassignPosition&&e.context.isPositionNodeInput&&(t.reassignPosition=!0)}return e.getPropertyName(s)}}const il=aa(sl).setParameterLength(1,2);Pn("toVarying",il),Pn("toVertexStage",(e=>il(e))),Pn("varying",((...e)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),il(...e)))),Pn("vertexStage",((...e)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),il(...e))));const rl=la((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return Hh(t,s,i)})).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),nl=la((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return Hh(t,s,i)})).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),al="WorkingColorSpace",ol="OutputColorSpace";class hl extends xn{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===al?nt.workingColorSpace:t===ol?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!==nt.enabled&&s!==i&&s&&i?(nt.getTransfer(s)===we&&(r=Ea(rl(r.rgb),r.a)),nt.getPrimaries(s)!==nt.getPrimaries(i)&&(r=Ea(Fa(nt._getMatrix(new Ke,s,i)).mul(r.rgb),r.a)),nt.getTransfer(i)===we&&(r=Ea(nl(r.rgb),r.a)),r):r}}const ll=(e,t)=>ia(new hl(ia(e),t,al));Pn("toOutputColorSpace",(e=>ia(new hl(ia(e),al,ol)))),Pn("toWorkingColorSpace",(e=>ia(new hl(ia(e),ol,al)))),Pn("workingToColorSpace",((e,t)=>ia(new hl(ia(e),al,t)))),Pn("colorSpaceToWorking",ll);let ul=class extends yn{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 cl extends fn{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=hn}setGroup(e){return this.group=e,this}element(e){return ia(new ul(this,ia(e)))}setNodeType(e){const t=bo(null,e).getSelf();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 dl extends cl{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(go)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const pl=(e,t,s=null)=>ia(new dl(e,t,s));class ml extends xn{static get type(){return"ToneMappingNode"}constructor(e,t=gl,s=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return Yr(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=Ea(r(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const gl=pl("toneMappingExposure","float");Pn("toneMapping",((e,t,s)=>((e,t,s)=>ia(new ml(e,ia(t),ia(s))))(t,s,e)));class fl extends Mn{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=Ie,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(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=this.value,i=e.getTypeLength(t),r=this.bufferStride||i,n=this.bufferOffset,a=!0===s.isInterleavedBuffer?s:new Gi(s,r),o=new Hi(a,i,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=il(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}}const yl=(e,t=null,s=0,i=0)=>ia(new fl(e,t,s,i)),bl=(e,t=null,s=0,i=0)=>yl(e,t,s,i).setInstanced(!0),xl=(e,t=null,s=0,i=0)=>((e,t=null,s=0,i=0)=>yl(e,t,s,i).setUsage(Be))(e,t,s,i).setInstanced(!0);Pn("toAttribute",(e=>yl(e.value)));class _l extends fn{static get type(){return"ComputeNode"}constructor(e,t,s=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=s,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=hn,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let s=t[0];for(let e=1;e<t.length;e++)s*=t[e];this.dispatchCount=Math.ceil(e/s)}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)}}}Pn("compute",((e,t,s)=>ia(new _l(ia(e),t,s))));class vl extends fn{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!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}}const Tl=(e,t)=>ia(new vl(ia(e),t));Pn("cache",Tl);class wl extends fn{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)}}Pn("bypass",aa(wl).setParameterLength(2));class Sl extends fn{static get type(){return"RemapNode"}constructor(e,t,s,i=ga(0),r=ga(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 Ml=aa(Sl,null,null,{doClamp:!1}).setParameterLength(3,5),Nl=aa(Sl).setParameterLength(3,5);Pn("remap",Ml),Pn("remapClamp",Nl);class El extends fn{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 Al=aa(El).setParameterLength(1,2);Pn("discard",(e=>(e?Qh(e,Al("discard")):Al("discard")).toStack()));class Cl extends xn{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=s,this.isRenderOutputNode=!0}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)||xe;return 0!==s&&(t=t.toneMapping(s)),i!==xe&&i!==nt.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}Pn("renderOutput",((e,t=null,s=null)=>ia(new Cl(ia(e),t,s))));class Rl extends xn{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),i="--- TSL debug - "+e.shaderStage+" shader ---",r="-".repeat(i.length);let n="";return n+="// #"+i+"#\n",n+=e.flow.code.replace(/^\t/gm,"")+"\n",n+="/* ... */ "+s+" /* ... */\n",n+="// #"+r+"#\n",null!==t?t(e,n):console.log(n),s}}Pn("debug",((e,t=null)=>ia(new Rl(ia(e),t))));class Pl extends fn{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 il(this).build(e,s)}return console.warn(`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 Fl=(e,t=null)=>ia(new Pl(e,t)),Il=(e=0)=>Fl("uv"+(e>0?e:""),"vec2");class Bl extends fn{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 Ll=aa(Bl).setParameterLength(1,2);class Dl extends yo{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=an}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 Ol=aa(Dl).setParameterLength(1);class kl extends yo{static get type(){return"TextureNode"}constructor(e,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.sampler=!0,this.updateMatrix=!1,this.updateType=nn,this.referenceNode=null,this._value=e,this._matrixUniform=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===U?"uvec4":this.value.type===k?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Il(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=bo(this.value.matrix)),this._matrixUniform.mul(wa(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?hn:nn,this}setupUV(e,t){const s=this.value;return e.isFlipY()&&(s.image instanceof ImageBitmap&&!0===s.flipY||!0===s.isRenderTargetTexture||!0===s.isFramebufferTexture||!0===s.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(fa(Ll(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const s=this.value;if(!s||!0!==s.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let i=this.uvNode;null!==i&&!0!==e.context.forceUVContext||!e.context.getUV||(i=e.context.getUV(this,e)),i||(i=this.getDefaultUV()),!0===this.updateMatrix&&(i=this.getTransformedUV(i)),i=this.setupUV(e,i);let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,s,i,r,n,a,o){const h=this.value;let l;return l=i?e.generateTextureLevel(h,t,s,i,n):r?e.generateTextureBias(h,t,s,r,n):o?e.generateTextureGrad(h,t,s,o,n):a?e.generateTextureCompare(h,t,s,a,n):!1===this.sampler?e.generateTextureLoad(h,t,s,n):e.generateTexture(h,t,s,n),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);let a=n.propertyName;if(void 0===a){const{uvNode:t,levelNode:s,biasNode:o,compareNode:h,depthNode:l,gradNode:u}=i,c=this.generateUV(e,t),d=s?s.build(e,"float"):null,p=o?o.build(e,"float"):null,m=l?l.build(e,"int"):null,g=h?h.build(e,"float"):null,f=u?[u[0].build(e,"vec2"),u[1].build(e,"vec2")]:null,y=e.getVarFromNode(this);a=e.getPropertyName(y);const b=this.generateSnippet(e,r,c,d,p,m,g,f);e.addLineFlowCode(`${a} = ${b}`,this),n.snippet=b,n.propertyName=a}let o=a;const h=this.getNodeType(e);return e.needsToWorkingColorSpace(s)&&(o=ll(Al(o,h),s.colorSpace).setup(e).build(e,h)),e.format(o,h,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=ia(e),t.referenceNode=this.getSelf(),ia(t)}blur(e){const t=this.clone();t.biasNode=ia(e).mul(Ol(t)),t.referenceNode=this.getSelf();const s=t.value;return!1===t.generateMipmaps&&(s&&!1===s.generateMipmaps||s.minFilter===A||s.magFilter===A)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),ia(t)}level(e){const t=this.clone();return t.levelNode=ia(e),t.referenceNode=this.getSelf(),ia(t)}size(e){return Ll(this,e)}bias(e){const t=this.clone();return t.biasNode=ia(e),t.referenceNode=this.getSelf(),ia(t)}compare(e){const t=this.clone();return t.compareNode=ia(e),t.referenceNode=this.getSelf(),ia(t)}grad(e,t){const s=this.clone();return s.gradNode=[ia(e),ia(t)],s.referenceNode=this.getSelf(),ia(s)}depth(e){const t=this.clone();return t.depthNode=ia(e),t.referenceNode=this.getSelf(),ia(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()}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}}const Ul=aa(kl).setParameterLength(1,4),zl=(...e)=>Ul(...e).setSampler(!1);class Vl extends yo{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Gl=(e,t,s)=>ia(new Vl(e,t,s));class jl extends yn{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 Vl{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?en(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=on,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,super.setup(e)}element(e){return ia(new jl(this,ia(e)))}}const Wl=(e,t)=>ia(new Hl(e,t));const $l=aa(class extends fn{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1),ql=bo(0,"uint").label("u_cameraIndex").setGroup(po("cameraIndex")).toVarying("v_cameraIndex"),Xl=bo("float").label("cameraNear").setGroup(go).onRenderUpdate((({camera:e})=>e.near)),Yl=bo("float").label("cameraFar").setGroup(go).onRenderUpdate((({camera:e})=>e.far)),Kl=la((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrix);t=Wl(s).setGroup(go).label("cameraProjectionMatrices").element(e.isMultiViewCamera?$l("gl_ViewID_OVR"):ql).toVar("cameraProjectionMatrix")}else t=bo("mat4").label("cameraProjectionMatrix").setGroup(go).onRenderUpdate((({camera:e})=>e.projectionMatrix));return t})).once()(),Ql=la((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorldInverse);t=Wl(s).setGroup(go).label("cameraViewMatrices").element(e.isMultiViewCamera?$l("gl_ViewID_OVR"):ql).toVar("cameraViewMatrix")}else t=bo("mat4").label("cameraViewMatrix").setGroup(go).onRenderUpdate((({camera:e})=>e.matrixWorldInverse));return t})).once()(),Zl=bo(new _t).label("cameraPosition").setGroup(go).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),Jl=new Vt;class eu extends fn{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=hn,this._uniformNode=new yo(null)}getNodeType(){const e=this.scope;return e===eu.WORLD_MATRIX?"mat4":e===eu.POSITION||e===eu.VIEW_POSITION||e===eu.DIRECTION||e===eu.SCALE?"vec3":e===eu.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this._uniformNode,i=this.scope;if(i===eu.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===eu.POSITION)s.value=s.value||new _t,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===eu.SCALE)s.value=s.value||new _t,s.value.setFromMatrixScale(t.matrixWorld);else if(i===eu.DIRECTION)s.value=s.value||new _t,t.getWorldDirection(s.value);else if(i===eu.VIEW_POSITION){const i=e.camera;s.value=s.value||new _t,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===eu.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),Jl.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),s.value=Jl.radius}}generate(e){const t=this.scope;return t===eu.WORLD_MATRIX?this._uniformNode.nodeType="mat4":t===eu.POSITION||t===eu.VIEW_POSITION||t===eu.DIRECTION||t===eu.SCALE?this._uniformNode.nodeType="vec3":t===eu.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}}eu.WORLD_MATRIX="worldMatrix",eu.POSITION="position",eu.SCALE="scale",eu.VIEW_POSITION="viewPosition",eu.DIRECTION="direction",eu.RADIUS="radius";const tu=aa(eu,eu.POSITION).setParameterLength(1);class su extends eu{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const iu=oa(su,su.WORLD_MATRIX),ru=bo(new Ke).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),nu=la((e=>e.renderer.overrideNodes.modelViewMatrix||au)).once()().toVar("modelViewMatrix"),au=Ql.mul(iu),ou=la((e=>(e.context.isHighPrecisionModelViewMatrix=!0,bo("mat4").onObjectUpdate((({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))))).once()().toVar("highpModelViewMatrix"),hu=la((e=>{const t=e.context.isHighPrecisionModelViewMatrix;return bo("mat3").onObjectUpdate((({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix))))})).once()().toVar("highpModelNormalViewMatrix"),lu=Fl("position","vec3"),uu=lu.toVarying("positionLocal"),cu=lu.toVarying("positionPrevious"),du=iu.mul(uu).xyz.toVarying("v_positionWorld").context({needsPositionReassign:!0}),pu=uu.transformDirection(iu).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection").context({needsPositionReassign:!0}),mu=la((e=>e.context.setupPositionView()),"vec3").once()().toVarying("v_positionView").context({needsPositionReassign:!0}),gu=mu.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class fu extends fn{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:s}=e;return t.coordinateSystem===Le&&1===s.side?"false":e.getFrontFacing()}}const yu=ga(oa(fu)).mul(2).sub(1),bu=Fl("normal","vec3"),xu=la((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),wa(0,1,0)):bu),"vec3").once()().toVar("normalLocal"),_u=mu.dFdx().cross(mu.dFdy()).normalize().toVar("normalFlat"),vu=la((e=>{let t;return t=!0===e.material.flatShading?_u:il(Eu(xu),"v_normalView").normalize(),t}),"vec3").once()().toVar("normalView"),Tu=la((e=>{let t=vu.transformDirection(Ql);return!0!==e.material.flatShading&&(t=il(t,"v_normalWorld")),t}),"vec3").once()().normalize().toVar("normalWorld"),wu=la((e=>{let t=e.context.setupNormal().context({getUV:null});return!0!==e.material.flatShading&&(t=t.mul(yu)),t}),"vec3").once()().toVar("transformedNormalView"),Su=wu.transformDirection(Ql).toVar("transformedNormalWorld"),Mu=la((e=>{let t=e.context.setupClearcoatNormal().context({getUV:null});return!0!==e.material.flatShading&&(t=t.mul(yu)),t}),"vec3").once()().toVar("transformedClearcoatNormalView"),Nu=la((([e,t=iu])=>{const s=Fa(t),i=e.div(wa(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz})),Eu=la((([e],t)=>{const s=t.renderer.overrideNodes.modelNormalViewMatrix;if(null!==s)return s.transformDirection(e);const i=ru.mul(e);return Ql.transformDirection(i)})),Au=new as,Cu=new Kt,Ru=bo(0).onReference((({material:e})=>e)).onObjectUpdate((({material:e})=>e.refractionRatio)),Pu=bo(1).onReference((({material:e})=>e)).onObjectUpdate((function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity})),Fu=bo(new Kt).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?(Au.copy(s),Cu.makeRotationFromEuler(Au)):Cu.identity(),Cu})),Iu=gu.negate().reflect(wu),Bu=gu.negate().refract(wu,Ru),Lu=Iu.transformDirection(Ql).toVar("reflectVector"),Du=Bu.transformDirection(Ql).toVar("reflectVector");class Ou 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"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===v?Lu:e.mapping===T?Du:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),wa(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return e.renderer.coordinateSystem!==De&&s.isRenderTargetTexture||(t=wa(t.x.negate(),t.yz)),Fu.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const ku=aa(Ou).setParameterLength(1,4).setName("cubeTexture");class Uu extends yn{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 zu extends fn{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=hn}element(e){return ia(new Uu(this,ia(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Gl(null,e,this.count):Array.isArray(this.getValueFromReference())?Wl(null,e):"texture"===e?Ul(null):"cubeTexture"===e?ku(null):bo(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}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 Vu=(e,t,s)=>ia(new zu(e,t,s)),Gu=(e,t,s,i)=>ia(new zu(e,t,i,s));class ju extends zu{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 Hu=(e,t,s=null)=>ia(new ju(e,t,s)),Wu=la((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Fl("tangent","vec4"))))(),$u=Wu.xyz.toVar("tangentLocal"),qu=nu.mul(Ea($u,0)).xyz.toVarying("v_tangentView").normalize().toVar("tangentView"),Xu=la((([e,t],s)=>{let i=e.mul(Wu.w).xyz;return!0!==s.material.flatShading&&(i=il(e,t)),i})).once()(vu.cross(qu),"v_bitangentView").normalize().toVar("bitangentView"),Yu=Fa(qu,Xu,vu),Ku=(()=>{let e=Qa.cross(gu);return e=e.cross(Qa).normalize(),e=Hh(e,wu,Ya.mul(Ua.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})(),Qu=la((e=>{const{eye_pos:t,surf_norm:s,mapN:i,uv:r}=e,n=t.dFdx(),a=t.dFdy(),o=r.dFdx(),h=r.dFdy(),l=s,u=a.cross(l),c=l.cross(n),d=u.mul(o.x).add(c.mul(h.x)),p=u.mul(o.y).add(c.mul(h.y)),m=d.dot(d).max(p.dot(p)),g=yu.mul(m.inverseSqrt());return So(d.mul(i.x,g),p.mul(i.y,g),l.mul(i.z)).normalize()}));class Zu extends xn{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup(e){const{normalMapType:t,scaleNode:s}=this;let i=this.node.mul(2).sub(1);null!==s&&(i=wa(i.xy.mul(s),i.z));let r=null;if(1===t)r=Eu(i);else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?Yu.mul(i).normalize():Qu({eye_pos:mu,surf_norm:vu,mapN:i,uv:Il()})}return r}}const Ju=aa(Zu).setParameterLength(1,2),ec=la((({textureNode:e,bumpScale:t})=>{const s=t=>e.cache().context({getUV:e=>t(e.uvNode||Il()),forceUVContext:!0}),i=ga(s((e=>e)));return xa(ga(s((e=>e.add(e.dFdx())))).sub(i),ga(s((e=>e.add(e.dFdy())))).sub(i)).mul(t)})),tc=la((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(yu),l=h.sign().mul(i.x.mul(a).add(i.y.mul(o)));return h.abs().mul(s).sub(l).normalize()}));class sc extends xn{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=ec({textureNode:this.textureNode,bumpScale:e});return tc({surf_pos:mu,surf_norm:vu,dHdxy:t})}}const ic=aa(sc).setParameterLength(1,2),rc=new Map;class nc extends fn{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=rc.get(e);return void 0===s&&(s=Hu(e,t),rc.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===nc.COLOR){const e=void 0!==t.color?this.getColor(s):wa();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===nc.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===nc.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:ga(1);else if(s===nc.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(s).a):e}else if(s===nc.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===nc.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===nc.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===nc.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===nc.NORMAL)t.normalMap?(i=Ju(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):i=t.bumpMap?ic(this.getTexture("bump").r,this.getFloat("bumpScale")):vu;else if(s===nc.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===nc.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===nc.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?Ju(this.getTexture(s),this.getCache(s+"Scale","vec2")):vu;else if(s===nc.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===nc.SHEEN_ROUGHNESS){const e=this.getFloat(s);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,i=i.clamp(.07,1)}else if(s===nc.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=Pa(Gc.x,Gc.y,Gc.y.negate(),Gc.x).mul(e.rg.mul(2).sub(xa(1)).normalize().mul(e.b))}else i=Gc;else if(s===nc.IRIDESCENCE_THICKNESS){const e=Vu("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Vu("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===nc.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===nc.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===nc.IOR)i=this.getFloat(s);else if(s===nc.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===nc.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}nc.ALPHA_TEST="alphaTest",nc.COLOR="color",nc.OPACITY="opacity",nc.SHININESS="shininess",nc.SPECULAR="specular",nc.SPECULAR_STRENGTH="specularStrength",nc.SPECULAR_INTENSITY="specularIntensity",nc.SPECULAR_COLOR="specularColor",nc.REFLECTIVITY="reflectivity",nc.ROUGHNESS="roughness",nc.METALNESS="metalness",nc.NORMAL="normal",nc.CLEARCOAT="clearcoat",nc.CLEARCOAT_ROUGHNESS="clearcoatRoughness",nc.CLEARCOAT_NORMAL="clearcoatNormal",nc.EMISSIVE="emissive",nc.ROTATION="rotation",nc.SHEEN="sheen",nc.SHEEN_ROUGHNESS="sheenRoughness",nc.ANISOTROPY="anisotropy",nc.IRIDESCENCE="iridescence",nc.IRIDESCENCE_IOR="iridescenceIOR",nc.IRIDESCENCE_THICKNESS="iridescenceThickness",nc.IOR="ior",nc.TRANSMISSION="transmission",nc.THICKNESS="thickness",nc.ATTENUATION_DISTANCE="attenuationDistance",nc.ATTENUATION_COLOR="attenuationColor",nc.LINE_SCALE="scale",nc.LINE_DASH_SIZE="dashSize",nc.LINE_GAP_SIZE="gapSize",nc.LINE_WIDTH="linewidth",nc.LINE_DASH_OFFSET="dashOffset",nc.POINT_SIZE="size",nc.DISPERSION="dispersion",nc.LIGHT_MAP="light",nc.AO="ao";const ac=oa(nc,nc.ALPHA_TEST),oc=oa(nc,nc.COLOR),hc=oa(nc,nc.SHININESS),lc=oa(nc,nc.EMISSIVE),uc=oa(nc,nc.OPACITY),cc=oa(nc,nc.SPECULAR),dc=oa(nc,nc.SPECULAR_INTENSITY),pc=oa(nc,nc.SPECULAR_COLOR),mc=oa(nc,nc.SPECULAR_STRENGTH),gc=oa(nc,nc.REFLECTIVITY),fc=oa(nc,nc.ROUGHNESS),yc=oa(nc,nc.METALNESS),bc=oa(nc,nc.NORMAL),xc=oa(nc,nc.CLEARCOAT),_c=oa(nc,nc.CLEARCOAT_ROUGHNESS),vc=oa(nc,nc.CLEARCOAT_NORMAL),Tc=oa(nc,nc.ROTATION),wc=oa(nc,nc.SHEEN),Sc=oa(nc,nc.SHEEN_ROUGHNESS),Mc=oa(nc,nc.ANISOTROPY),Nc=oa(nc,nc.IRIDESCENCE),Ec=oa(nc,nc.IRIDESCENCE_IOR),Ac=oa(nc,nc.IRIDESCENCE_THICKNESS),Cc=oa(nc,nc.TRANSMISSION),Rc=oa(nc,nc.THICKNESS),Pc=oa(nc,nc.IOR),Fc=oa(nc,nc.ATTENUATION_DISTANCE),Ic=oa(nc,nc.ATTENUATION_COLOR),Bc=oa(nc,nc.LINE_SCALE),Lc=oa(nc,nc.LINE_DASH_SIZE),Dc=oa(nc,nc.LINE_GAP_SIZE);nc.LINE_WIDTH;const Oc=oa(nc,nc.LINE_DASH_OFFSET),kc=oa(nc,nc.POINT_SIZE),Uc=oa(nc,nc.DISPERSION),zc=oa(nc,nc.LIGHT_MAP),Vc=oa(nc,nc.AO),Gc=bo(new Ye).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))})),jc=la((e=>e.context.setupModelViewProjection()),"vec4").once()().toVarying("v_modelViewProjection");class Hc extends fn{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===Hc.VERTEX)i=e.getVertexIndex();else if(s===Hc.INSTANCE)i=e.getInstanceIndex();else if(s===Hc.DRAW)i=e.getDrawIndex();else if(s===Hc.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===Hc.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==Hc.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=il(this).build(e,t)}return r}}Hc.VERTEX="vertex",Hc.INSTANCE="instance",Hc.SUBGROUP="subgroup",Hc.INVOCATION_LOCAL="invocationLocal",Hc.INVOCATION_SUBGROUP="invocationSubgroup",Hc.DRAW="draw";const Wc=oa(Hc,Hc.VERTEX),$c=oa(Hc,Hc.INSTANCE);Hc.SUBGROUP,Hc.INVOCATION_SUBGROUP,Hc.INVOCATION_LOCAL;const qc=oa(Hc,Hc.DRAW);class Xc extends fn{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=an,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:s,instanceColor:i}=this;let{instanceMatrixNode:r,instanceColorNode:n}=this;if(null===r){if(t<=1e3)r=Gl(s.array,"mat4",Math.max(t,1)).element($c);else{const e=new jr(s.array,16,1);this.buffer=e;const t=s.usage===Be?xl:bl,i=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];r=Ia(...i)}this.instanceMatrixNode=r}if(i&&null===n){const e=new qi(i.array,3),t=i.usage===Be?xl:bl;this.bufferColor=e,n=wa(t(e,"vec3",3,0)),this.instanceColorNode=n}const a=r.mul(uu).xyz;if(uu.assign(a),e.hasGeometryAttribute("normal")){const e=Nu(xu,r);xu.assign(e)}null!==this.instanceColorNode&&Da("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==Be&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==Be&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}class Yc extends Xc{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const Kc=aa(Yc).setParameterLength(1);class Qc extends fn{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=$c:this.batchingIdNode=qc);const t=la((([e])=>{const t=fa(Ll(zl(this.batchMesh._indirectTexture),0).x),s=fa(e).mod(t),i=fa(e).div(t);return zl(this.batchMesh._indirectTexture,_a(s,i)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(fa(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=fa(Ll(zl(i),0).x),n=ga(s).mul(4).toInt().toVar(),a=n.mod(r),o=n.div(r),h=Ia(zl(i,_a(a,o)),zl(i,_a(a.add(1),o)),zl(i,_a(a.add(2),o)),zl(i,_a(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=la((([e])=>{const t=fa(Ll(zl(l),0).x),s=e,i=s.mod(t),r=s.div(t);return zl(l,_a(i,r)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);Da("vec3","vBatchColor").assign(t)}const u=Fa(h);uu.assign(h.mul(uu));const c=xu.div(wa(u[0].dot(u[0]),u[1].dot(u[1]),u[2].dot(u[2]))),d=u.mul(c).xyz;xu.assign(d),e.hasGeometryAttribute("tangent")&&$u.mulAssign(u)}}const Zc=aa(Qc).setParameterLength(1),Jc=new WeakMap;class ed extends fn{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=hn,this.skinIndexNode=Fl("skinIndex","uvec4"),this.skinWeightNode=Fl("skinWeight","vec4"),this.bindMatrixNode=Vu("bindMatrix","mat4"),this.bindMatrixInverseNode=Vu("bindMatrixInverse","mat4"),this.boneMatricesNode=Gu("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=uu,this.toPositionNode=uu,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=So(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}getSkinnedNormal(e=this.boneMatricesNode,t=xu){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);let u=So(i.x.mul(a),i.y.mul(o),i.z.mul(h),i.w.mul(l));return u=n.mul(u).mul(r),u.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=Gu("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,cu)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===sn(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&cu.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();xu.assign(t),e.hasGeometryAttribute("tangent")&&$u.assign(t)}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;Jc.get(t)!==e.frameId&&(Jc.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}class td extends fn{static get type(){return"LoopNode"}constructor(e=[]){super(),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]=Al(i,r)}const i=e.addStack();t.returnsNode=this.params[this.params.length-1](s,e),t.stackNode=i;const r=this.params[0];return!0!==r.isNode&&"function"==typeof r.update&&(t.updateNode=la(this.params[0].update)(s)),e.removeStack(),t}getNodeType(e){const{returnsNode:t}=this.getProperties(e);return t?t.getNodeType(e):"void"}setup(e){this.getProperties(e)}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):(console.error("THREE.TSL: 'Loop( { update: ... } )' is not a function, string or number."),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"),n=t.returnsNode?t.returnsNode.build(e):"";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();return e.addFlowTab(),n}}const sd=(...e)=>ia(new td(na(e,"int"))).toStack(),id=new WeakMap,rd=new gt,nd=la((({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const a=fa(Wc).mul(s).add(n),o=a.div(i),h=a.sub(o.mul(i));return zl(e,_a(h,o)).depth(r).xyz.mul(t)}));class ad extends fn{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=bo(1),this.updateType=hn}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=id.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 bt(m,c,d,n);g.type=z,g.needsUpdate=!0;const f=4*u;for(let b=0;b<n;b++){const x=o[b],_=h[b],v=l[b],T=c*d*4*b;for(let w=0;w<x.count;w++){const S=w*f;!0===t&&(rd.fromBufferAttribute(x,w),m[T+S+0]=rd.x,m[T+S+1]=rd.y,m[T+S+2]=rd.z,m[T+S+3]=0),!0===s&&(rd.fromBufferAttribute(_,w),m[T+S+4]=rd.x,m[T+S+5]=rd.y,m[T+S+6]=rd.z,m[T+S+7]=0),!0===i&&(rd.fromBufferAttribute(v,w),m[T+S+8]=rd.x,m[T+S+9]=rd.y,m[T+S+10]=rd.z,m[T+S+11]=4===v.itemSize?rd.w:1)}}function y(){g.dispose(),id.delete(e),e.removeEventListener("dispose",y)}a={count:n,texture:g,stride:u,size:new Ye(c,d)},id.set(e,a),e.addEventListener("dispose",y)}return a}(t);!0===s&&uu.mulAssign(this.morphBaseInfluence),!0===i&&xu.mulAssign(this.morphBaseInfluence);const l=fa(h.width);sd(n,(({i:e})=>{const t=ga(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(zl(this.mesh.morphTexture,_a(fa(e).add(1),fa($c))).r):t.assign(Vu("morphTargetInfluences","float").element(e).toVar()),da(t.notEqual(0),(()=>{!0===s&&uu.addAssign(nd({bufferMap:a,influence:t,stride:o,width:l,depth:e,offset:fa(0)})),!0===i&&xu.addAssign(nd({bufferMap:a,influence:t,stride:o,width:l,depth:e,offset:fa(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 od=aa(ad).setParameterLength(1);class hd extends fn{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class ld extends hd{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class ud extends Zh{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:wa().toVar("directDiffuse"),directSpecular:wa().toVar("directSpecular"),indirectDiffuse:wa().toVar("indirectDiffuse"),indirectSpecular:wa().toVar("indirectSpecular")};return{radiance:wa().toVar("radiance"),irradiance:wa().toVar("irradiance"),iblIrradiance:wa().toVar("iblIrradiance"),ambientOcclusion:ga(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 cd=aa(ud);class dd extends hd{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let pd,md;class gd extends fn{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===gd.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=nn;return this.scope!==gd.SIZE&&this.scope!==gd.VIEWPORT||(e=on),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===gd.VIEWPORT?null!==t?md.copy(t.viewport):(e.getViewport(md),md.multiplyScalar(e.getPixelRatio())):null!==t?(pd.width=t.width,pd.height=t.height):e.getDrawingBufferSize(pd)}setup(){const e=this.scope;let t=null;return t=e===gd.SIZE?bo(pd||(pd=new Ye)):e===gd.VIEWPORT?bo(md||(md=new gt)):xa(bd.div(yd)),t}generate(e){if(this.scope===gd.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(yd).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}gd.COORDINATE="coordinate",gd.VIEWPORT="viewport",gd.SIZE="size",gd.UV="uv";const fd=oa(gd,gd.UV),yd=oa(gd,gd.SIZE),bd=oa(gd,gd.COORDINATE),xd=oa(gd,gd.VIEWPORT);xd.zw,xd.xy;const _d=new Ye;class vd extends kl{static get type(){return"ViewportTextureNode"}constructor(e=fd,t=null,s=null){null===s&&((s=new ar).minFilter=I),super(s,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=an}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(_d);const s=this.value;s.image.width===_d.width&&s.image.height===_d.height||(s.image.width=_d.width,s.image.height=_d.height,s.needsUpdate=!0);const i=s.generateMipmaps;s.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(s),s.generateMipmaps=i}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Td=aa(vd,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let wd=null;class Sd extends vd{static get type(){return"ViewportDepthTextureNode"}constructor(e=fd,t=null){null===wd&&(wd=new or),super(e,t,wd)}}const Md=aa(Sd).setParameterLength(0,2);class Nd extends fn{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===Nd.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===Nd.DEPTH_BASE)null!==s&&(i=Pd().assign(s));else if(t===Nd.DEPTH)i=e.isPerspectiveCamera?Ad(mu.z,Xl,Yl):Ed(mu.z,Xl,Yl);else if(t===Nd.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=Cd(s,Xl,Yl);i=Ed(e,Xl,Yl)}else i=s;else i=Ed(mu.z,Xl,Yl);return i}}Nd.DEPTH_BASE="depthBase",Nd.DEPTH="depth",Nd.LINEAR_DEPTH="linearDepth";const Ed=(e,t,s)=>e.add(t).div(t.sub(s)),Ad=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),Cd=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),Rd=(e,t,s)=>{t=t.max(1e-6).toVar();const i=nh(e.negate().div(t)),r=nh(s.div(t));return i.div(r)},Pd=aa(Nd,Nd.DEPTH_BASE),Fd=oa(Nd,Nd.DEPTH);Md(),Fd.assign=e=>Pd(e);class Id extends fn{static get type(){return"ClippingNode"}constructor(e=Id.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===Id.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===Id.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return la((()=>{const s=ga().toVar("distanceToPlane"),i=ga().toVar("distanceToGradient"),r=ga(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=Wl(t);sd(n,(({i:t})=>{const n=e.element(t);s.assign(mu.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(qh(i.negate(),i,s))}))}const a=e.length;if(a>0){const t=Wl(e),n=ga(1).toVar("intersectionClipOpacity");sd(a,(({i:e})=>{const r=t.element(e);s.assign(mu.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(qh(i.negate(),i,s).oneMinus())})),r.mulAssign(n.oneMinus())}Oa.a.mulAssign(r),Oa.a.equal(0).discard()}))()}setupDefault(e,t){return la((()=>{const s=t.length;if(!1===this.hardwareClipping&&s>0){const e=Wl(t);sd(s,(({i:t})=>{const s=e.element(t);mu.dot(s.xyz).greaterThan(s.w).discard()}))}const i=e.length;if(i>0){const t=Wl(e),s=ba(!0).toVar("clipped");sd(i,(({i:e})=>{const i=t.element(e);s.assign(mu.dot(i.xyz).greaterThan(i.w).and(s))})),s.discard()}}))()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),la((()=>{const i=Wl(e),r=$l(t.getClipDistance());sd(s,(({i:e})=>{const t=i.element(e),s=mu.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)}))}))()}}Id.ALPHA_TO_COVERAGE="alphaToCoverage",Id.DEFAULT="default",Id.HARDWARE="hardware";const Bd=la((([e])=>ch(No(1e4,dh(No(17,e.x).add(No(.1,e.y)))).mul(So(.1,bh(dh(No(13,e.y).add(e.x)))))))),Ld=la((([e])=>Bd(xa(Bd(e.xy),e.z)))),Dd=la((([e])=>{const t=Ph(_h(wh(e.xyz)),_h(Sh(e.xyz))),s=ga(1).div(ga(.05).mul(t)).toVar("pixScale"),i=xa(ih(hh(nh(s))),ih(lh(nh(s)))),r=xa(Ld(hh(i.x.mul(e.xyz))),Ld(hh(i.y.mul(e.xyz)))),n=ch(nh(s)),a=So(No(n.oneMinus(),r.x),No(n,r.y)),o=Rh(n,n.oneMinus()),h=wa(a.mul(a).div(No(2,o).mul(Mo(1,o))),a.sub(No(.5,o)).div(Mo(1,o)),Mo(1,Mo(1,a).mul(Mo(1,a)).div(No(2,o).mul(Mo(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(h.x,h.y),h.z);return Wh(l,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Od extends Pl{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 gt(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}class kd extends Ws{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.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,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+Kr(this)}build(e){this.setup(e)}setupObserver(e){return new $r(e)}setup(e){e.context.setupNormal=()=>this.setupNormal(e),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();e.addStack();const i=this.vertexNode||this.setupVertex(e);let r;e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const n=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!==n&&e.stack.add(n);const a=Ea(i,Oa.a).max(0);r=this.setupOutput(e,a),to.assign(r);const o=null!==this.outputNode;if(o&&(r=this.outputNode),null!==s){const e=t.getMRT(),s=this.mrtNode;null!==e?(o&&to.assign(r),r=e,null!==s&&(r=e.merge(s))):null!==s&&(r=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=Ea(t)),r=this.setupOutput(e,t)}e.stack.outputNode=r,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.samples;this.alphaToCoverage&&t>1?i=ia(new Id(Id.ALPHA_TO_COVERAGE)):e.stack.add(ia(new Id))}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.add(ia(new Id(Id.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?Rd(mu.z,Xl,Yl):Ed(mu.z,Xl,Yl))}null!==i&&Fd.assign(i).toStack()}setupPositionView(){return nu.mul(uu).xyz}setupModelViewProjection(){return Kl.mul(mu)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),jc}setupPosition(e){const{object:t,geometry:s}=e;var i;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&od(t).toStack(),!0===t.isSkinnedMesh&&(i=t,ia(new ed(i))).toStack(),this.displacementMap){const e=Hu("displacementMap","texture"),t=Hu("displacementScale","float"),s=Hu("displacementBias","float");uu.addAssign(xu.normalize().mul(e.x.mul(t).add(s)))}return t.isBatchedMesh&&Zc(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Kc(t).toStack(),null!==this.positionNode&&uu.assign(this.positionNode.context({isPositionNodeInput:!0})),uu}setupDiffuseColor({object:e,geometry:t}){let s=this.colorNode?Ea(this.colorNode):oc;if(!0===this.vertexColors&&t.hasAttribute("color")&&(s=s.mul(((e=0)=>ia(new Od(e)))())),e.instanceColor){s=Da("vec3","vInstanceColor").mul(s)}if(e.isBatchedMesh&&e._colorsTexture){s=Da("vec3","vBatchColor").mul(s)}Oa.assign(s);const i=this.opacityNode?ga(this.opacityNode):uc;if(Oa.a.assign(Oa.a.mul(i)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?ga(this.alphaTestNode):ac;Oa.a.lessThanEqual(e).discard()}!0===this.alphaHash&&Oa.a.lessThan(Dd(uu)).discard(),!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage&&Oa.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?wa(0):Oa.rgb}setupNormal(){return this.normalNode?wa(this.normalNode):bc}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Hu("envMap","cubeTexture"):Hu("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new dd(zc)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Vc;t.push(new ld(e))}let r=this.lightsNode||e.lightsNode;return t.length>0&&(r=e.renderer.lighting.createNode([...r.getLights(),...t])),r}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=cd(n,t,s,i)}else null!==s&&(a=wa(null!==i?Hh(a,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(ka.assign(wa(r||lc)),a=a.add(ka)),a}setupFog(e,t){const s=e.fogNode;return s&&(to.assign(t),t=Ea(s)),t}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(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=Ws.prototype.toJSON.call(this,e),i=Qr(this);s.inputNodes={};for(const{property:t,childNode:r}of i)s.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(t){const t=r(e.textures),i=r(e.images),n=r(e.nodes);t.length>0&&(s.textures=t),i.length>0&&(s.images=i),n.length>0&&(s.nodes=n)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,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.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,super.copy(e)}}const Ud=new rr;class zd extends kd{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Ud),this.setValues(e)}}const Vd=new _r;class Gd extends kd{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Vd),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?ga(this.offsetNode):Oc,t=this.dashScaleNode?ga(this.dashScaleNode):Bc,s=this.dashSizeNode?ga(this.dashSizeNode):Lc,i=this.gapSizeNode?ga(this.gapSizeNode):Dc;so.assign(s),io.assign(i);const r=il(Fl("lineDistance").mul(t));(e?r.add(e):r).mod(so.add(io)).greaterThan(so).discard()}}const jd=new yr;class Hd extends kd{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(jd),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?ga(this.opacityNode):uc;Oa.assign(ll(Ea(ia(wu).mul(.5).add(.5),e),_e))}}class Wd extends xn{static get type(){return"EquirectUVNode"}constructor(e=pu){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,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 xa(t,s)}}const $d=aa(Wd).setParameterLength(0,1);class qd extends Oi{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!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 Ni(5,5,5),n=$d(pu),a=new kd;a.colorNode=Ul(t,n,0),a.side=1,a.blending=0;const o=new Si(r,a),h=new Vi;h.add(o),t.minFilter===I&&(t.minFilter=P);const l=new Li(1,10,this),u=e.getMRT();return e.setMRT(null),l.update(e,h),e.setMRT(u),t.minFilter=s,t.currentGenerateMipmaps=i,o.geometry.dispose(),o.material.dispose(),this}}const Xd=new WeakMap;class Yd extends xn{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=ku(null);const t=new Di;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=on}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(s===w||s===S){if(Xd.has(e)){const t=Xd.get(e);Qd(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new qd(s.height);i.fromEquirectangularTexture(t,e),Qd(i.texture,e.mapping),this._cubeTexture=i.texture,Xd.set(e,i.texture),e.addEventListener("dispose",Kd)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Kd(e){const t=e.target;t.removeEventListener("dispose",Kd);const s=Xd.get(t);void 0!==s&&(Xd.delete(t),s.dispose())}function Qd(e,t){t===w?e.mapping=v:t===S&&(e.mapping=T)}const Zd=aa(Yd).setParameterLength(1);class Jd extends hd{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Zd(this.envNode)}}class ep extends hd{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=ga(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class tp{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class sp extends tp{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(Ea(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(Ea(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Oa.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(Hh(i.rgb,i.rgb.mul(r.rgb),mc.mul(gc)));break;case 1:i.rgb.assign(Hh(i.rgb,r.rgb,mc.mul(gc)));break;case 2:i.rgb.addAssign(r.rgb.mul(mc.mul(gc)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const ip=new $s;class rp extends kd{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(ip),this.setValues(e)}setupNormal(){return vu}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Jd(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new ep(zc)),t}setupOutgoingLight(){return Oa.rgb}setupLightingModel(){return new sp}}const np=la((({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))})),ap=la((e=>e.diffuseColor.mul(1/Math.PI))),op=la((({dotNH:e})=>eo.mul(ga(.5)).add(1).mul(ga(1/Math.PI)).mul(e.pow(eo)))),hp=la((({lightDirection:e})=>{const t=e.add(gu).normalize(),s=wu.dot(t).clamp(),i=gu.dot(t).clamp(),r=np({f0:Za,f90:1,dotVH:i}),n=ga(.25),a=op({dotNH:s});return r.mul(n).mul(a)}));class lp extends sp{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=wu.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(ap({diffuseColor:Oa.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(hp({lightDirection:e})).mul(mc))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(ap({diffuseColor:Oa}))),i.indirectDiffuse.mulAssign(t)}}const up=new br;class cp extends kd{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(up),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Jd(t):null}setupLightingModel(){return new lp(!1)}}const dp=new gr;class pp extends kd{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(dp),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Jd(t):null}setupLightingModel(){return new lp}setupVariants(){const e=(this.shininessNode?ga(this.shininessNode):hc).max(1e-4);eo.assign(e);const t=this.specularNode||cc;Za.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const mp=la((e=>{if(!1===e.geometry.hasAttribute("normal"))return ga(0);const t=vu.dFdx().abs().max(vu.dFdy().abs());return t.x.max(t.y).max(t.z)})),gp=la((e=>{const{roughness:t}=e,s=mp();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i})),fp=la((({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 Eo(.5,r.add(n).max(Ko))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),yp=la((({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:a,dotNL:o})=>{const h=o.mul(wa(e.mul(s),t.mul(i),a).length()),l=a.mul(wa(e.mul(r),t.mul(n),o).length());return Eo(.5,h.add(l)).saturate()})).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"}]}),bp=la((({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"}]}),xp=ga(1/Math.PI),_p=la((({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),a=wa(t.mul(i),e.mul(r),n.mul(s)),o=a.dot(a),h=n.div(o);return xp.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"}]}),vp=la((e=>{const{lightDirection:t,f0:s,f90:i,roughness:r,f:n,USE_IRIDESCENCE:a,USE_ANISOTROPY:o}=e,h=e.normalView||wu,l=r.pow2(),u=t.add(gu).normalize(),c=h.dot(t).clamp(),d=h.dot(gu).clamp(),p=h.dot(u).clamp(),m=gu.dot(u).clamp();let g,f,y=np({f0:s,f90:i,dotVH:m});if(ta(a)&&(y=Wa.mix(y,n)),ta(o)){const e=Ka.dot(t),s=Ka.dot(gu),i=Ka.dot(u),r=Qa.dot(t),n=Qa.dot(gu),a=Qa.dot(u);g=yp({alphaT:Xa,alphaB:l,dotTV:s,dotBV:n,dotTL:e,dotBL:r,dotNV:d,dotNL:c}),f=_p({alphaT:Xa,alphaB:l,dotNH:p,dotTH:i,dotBH:a})}else g=fp({alpha:l,dotNL:c,dotNV:d}),f=bp({alpha:l,dotNH:p});return y.mul(g).mul(f)})),Tp=la((({roughness:e,dotNV:t})=>{const s=Ea(-1,-.0275,-.572,.022),i=Ea(1,.0425,1.04,-.04),r=e.mul(s).add(i),n=r.x.mul(r.x).min(t.mul(-9.28).exp2()).mul(r.x).add(r.y);return xa(-1.04,1.04).mul(n).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),wp=la((e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=Tp({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))})),Sp=la((({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(wa(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"}]}),Mp=la((({roughness:e,dotNH:t})=>{const s=e.pow2(),i=ga(1).div(s),r=t.pow2().oneMinus().max(.0078125);return ga(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"}]}),Np=la((({dotNV:e,dotNL:t})=>ga(1).div(ga(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),Ep=la((({lightDirection:e})=>{const t=e.add(gu).normalize(),s=wu.dot(e).clamp(),i=wu.dot(gu).clamp(),r=wu.dot(t).clamp(),n=Mp({roughness:Ha,dotNH:r}),a=Np({dotNV:i,dotNL:s});return ja.mul(n).mul(a)})),Ap=la((({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=xa(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"}]}),Cp=la((({f:e})=>{const t=e.length();return Ph(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Rp=la((({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,Ph(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"}]}),Pp=la((({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=wa().toVar();return da(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(Fa(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=wa(0).toVar();f.addAssign(Rp({v1:d,v2:p})),f.addAssign(Rp({v1:p,v2:m})),f.addAssign(Rp({v1:m,v2:g})),f.addAssign(Rp({v1:g,v2:d})),c.assign(wa(Cp({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"}]}),Fp=1/6,Ip=e=>No(Fp,No(e,No(e,e.negate().add(3)).sub(3)).add(1)),Bp=e=>No(Fp,No(e,No(e,No(3,e).sub(6))).add(4)),Lp=e=>No(Fp,No(e,No(e,No(-3,e).add(3)).add(3)).add(1)),Dp=e=>No(Fp,kh(e,3)),Op=e=>Ip(e).add(Bp(e)),kp=e=>Lp(e).add(Dp(e)),Up=e=>So(-1,Bp(e).div(Ip(e).add(Bp(e)))),zp=e=>So(1,Dp(e).div(Lp(e).add(Dp(e)))),Vp=(e,t,s)=>{const i=e.uvNode,r=No(i,t.zw).add(.5),n=hh(r),a=ch(r),o=Op(a.x),h=kp(a.x),l=Up(a.x),u=zp(a.x),c=Up(a.y),d=zp(a.y),p=xa(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),m=xa(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),g=xa(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),f=xa(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),y=Op(a.y).mul(So(o.mul(e.sample(p).level(s)),h.mul(e.sample(m).level(s)))),b=kp(a.y).mul(So(o.mul(e.sample(g).level(s)),h.mul(e.sample(f).level(s))));return y.add(b)},Gp=la((([e,t=ga(3)])=>{const s=xa(e.size(fa(t))),i=xa(e.size(fa(t.add(1)))),r=Eo(1,s),n=Eo(1,i),a=Vp(e,Ea(r,s),hh(t)),o=Vp(e,Ea(n,i),lh(t));return ch(t).mix(a,o)})),jp=la((([e,t,s,i,r])=>{const n=wa($h(t.negate(),uh(e),Eo(1,i))),a=wa(_h(r[0].xyz),_h(r[1].xyz),_h(r[2].xyz));return uh(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"}]}),Hp=la((([e,t])=>e.mul(Wh(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Wp=Td(),$p=Td(),qp=la((([e,t,s],{material:i})=>{const r=(1===i.side?Wp:$p).sample(e),n=nh(yd.x).mul(Hp(t,s));return Gp(r,n)})),Xp=la((([e,t,s])=>(da(s.notEqual(0),(()=>{const i=rh(t).negate().div(s);return sh(i.negate().mul(e))})),wa(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Yp=la((([e,t,s,i,r,n,a,o,h,l,u,c,d,p,m])=>{let g,f;if(m){g=Ea().toVar(),f=wa().toVar();const r=u.sub(1).mul(m.mul(.025)),n=wa(u.sub(r),u,u.add(r));sd({start:0,end:3},(({i:r})=>{const u=n.element(r),m=jp(e,t,c,u,o),y=a.add(m),b=l.mul(h.mul(Ea(y,1))),x=xa(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(xa(x.x,x.y.oneMinus()));const _=qp(x,s,u);g.element(r).assign(_.element(r)),g.a.addAssign(_.a),f.element(r).assign(i.element(r).mul(Xp(_h(m),d,p).element(r)))})),g.a.divAssign(3)}else{const r=jp(e,t,c,u,o),n=a.add(r),m=l.mul(h.mul(Ea(n,1))),y=xa(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(xa(y.x,y.y.oneMinus())),g=qp(y,s,u),f=i.mul(Xp(_h(r),d,p))}const y=f.rgb.mul(g.rgb),b=e.dot(t).clamp(),x=wa(wp({dotNV:b,specularColor:r,specularF90:n,roughness:s})),_=f.r.add(f.g,f.b).div(3);return Ea(x.oneMinus().mul(y),g.a.oneMinus().mul(_).oneMinus())})),Kp=Fa(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Qp=(e,t)=>e.sub(t).div(e.add(t)).pow2(),Zp=la((({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=Hh(e,t,qh(0,.03,i)),a=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();da(a.lessThan(0),(()=>wa(1)));const o=a.sqrt(),h=Qp(n,e),l=np({f0:h,f90:1,dotVH:s}),u=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=ga(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return wa(1).add(t).div(wa(1).sub(t))})(r.clamp(0,.9999)),m=Qp(p,n.toVec3()),g=np({f0:m,f90:1,dotVH:o}),f=wa(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=wa(d).add(f),x=l.mul(g).clamp(1e-5,.9999),_=x.sqrt(),v=u.pow2().mul(g).div(wa(1).sub(x)),T=l.add(v).toVar(),w=v.sub(u).toVar();return sd({start:1,end:2,condition:"<=",name:"m"},(({m:e})=>{w.mulAssign(_);const t=((e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=wa(54856e-17,44201e-17,52481e-17),r=wa(1681e3,1795300,2208400),n=wa(43278e5,93046e5,66121e5),a=ga(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=wa(o.x.add(a),o.y,o.z).div(1.0685e-7),Kp.mul(o)})(ga(e).mul(y),ga(e).mul(b)).mul(2);T.addAssign(w.mul(t))})),T.max(wa(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"}]}),Jp=la((({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.pow2(),n=Qh(s.lessThan(.25),ga(-339.2).mul(r).add(ga(161.4).mul(s)).sub(25.9),ga(-8.48).mul(r).add(ga(14.3).mul(s)).sub(9.95)),a=Qh(s.lessThan(.25),ga(44).mul(r).sub(ga(23.7).mul(s)).add(3.26),ga(1.97).mul(r).sub(ga(3.27).mul(s)).add(.72));return Qh(s.lessThan(.25),0,ga(.1).mul(s).sub(.025)).add(n.mul(i).add(a).exp()).mul(1/Math.PI).saturate()})),em=wa(.04),tm=ga(1);class sm extends tp{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}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=wa().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=wa().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=wa().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=wa().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=wa().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=wu.dot(gu).clamp();this.iridescenceFresnel=Zp({outsideIOR:ga(1),eta2:$a,cosTheta1:e,thinFilmThickness:qa,baseF0:Za}),this.iridescenceF0=Sp({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=du,s=Zl.sub(du).normalize(),i=Su,r=e.context;r.backdrop=Yp(i,s,Ua,Oa,Za,Ja,t,iu,Ql,Kl,ro,ao,ho,oo,this.dispersion?lo:null),r.backdropAlpha=no,Oa.a.mulAssign(Hh(1,r.backdrop.a,no))}super.start(e)}computeMultiscattering(e,t,s){const i=wu.dot(gu).clamp(),r=Tp({roughness:Ua,dotNV:i}),n=(this.iridescenceF0?Wa.mix(Za,this.iridescenceF0):Za).mul(r.x).add(s.mul(r.y)),a=r.x.add(r.y).oneMinus(),o=Za.add(Za.oneMinus().mul(.047619)),h=n.mul(o).div(a.mul(o).oneMinus());e.addAssign(n),t.addAssign(h.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=wu.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(Ep({lightDirection:e}))),!0===this.clearcoat){const s=Mu.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(vp({lightDirection:e,f0:em,f90:tm,roughness:Ga,normalView:Mu})))}s.directDiffuse.addAssign(i.mul(ap({diffuseColor:Oa.rgb}))),s.directSpecular.addAssign(i.mul(vp({lightDirection:e,f0:Za,f90:1,roughness:Ua,iridescence:this.iridescence,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=wu,d=gu,p=mu.toVar(),m=Ap({N:c,V:d,roughness:Ua}),g=n.sample(m).toVar(),f=a.sample(m).toVar(),y=Fa(wa(g.x,0,g.y),wa(0,1,0),wa(g.z,0,g.w)).toVar(),b=Za.mul(f.x).add(Za.oneMinus().mul(f.y)).toVar();r.directSpecular.addAssign(e.mul(b).mul(Pp({N:c,V:d,P:p,mInv:y,p0:o,p1:h,p2:l,p3:u}))),r.directDiffuse.addAssign(e.mul(Oa).mul(Pp({N:c,V:d,P:p,mInv:Fa(1,0,0,0,1,0,0,0,1),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;s.indirectDiffuse.addAssign(t.mul(ap({diffuseColor:Oa})))}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(s.mul(ja,Jp({normal:wu,viewDir:gu,roughness:Ha}))),!0===this.clearcoat){const e=Mu.dot(gu).clamp(),t=wp({dotNV:e,specularColor:em,specularF90:tm,roughness:Ga});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=wa().toVar("singleScattering"),n=wa().toVar("multiScattering"),a=s.mul(1/Math.PI);this.computeMultiscattering(r,n,Ja);const o=r.add(n),h=Oa.mul(o.r.max(o.g).max(o.b).oneMinus());i.indirectSpecular.addAssign(t.mul(r)),i.indirectSpecular.addAssign(n.mul(a)),i.indirectDiffuse.addAssign(h.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:s}=e.context,i=wu.dot(gu).clamp().add(t),r=Ua.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=Mu.dot(gu).clamp(),s=np({dotVH:e,f0:em,f90:tm}),i=t.mul(Va.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Va));t.assign(i)}if(!0===this.sheen){const e=ja.r.max(ja.g).max(ja.b).mul(.157).oneMinus(),s=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(s)}}}const im=ga(1),rm=ga(-2),nm=ga(.8),am=ga(-1),om=ga(.4),hm=ga(2),lm=ga(.305),um=ga(3),cm=ga(.21),dm=ga(4),pm=ga(4),mm=ga(16),gm=la((([e])=>{const t=wa(bh(e)).toVar(),s=ga(-1).toVar();return da(t.x.greaterThan(t.z),(()=>{da(t.x.greaterThan(t.y),(()=>{s.assign(Qh(e.x.greaterThan(0),0,3))})).Else((()=>{s.assign(Qh(e.y.greaterThan(0),1,4))}))})).Else((()=>{da(t.z.greaterThan(t.y),(()=>{s.assign(Qh(e.z.greaterThan(0),2,5))})).Else((()=>{s.assign(Qh(e.y.greaterThan(0),1,4))}))})),s})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),fm=la((([e,t])=>{const s=xa().toVar();return da(t.equal(0),(()=>{s.assign(xa(e.z,e.y).div(bh(e.x)))})).ElseIf(t.equal(1),(()=>{s.assign(xa(e.x.negate(),e.z.negate()).div(bh(e.y)))})).ElseIf(t.equal(2),(()=>{s.assign(xa(e.x.negate(),e.y).div(bh(e.z)))})).ElseIf(t.equal(3),(()=>{s.assign(xa(e.z.negate(),e.y).div(bh(e.x)))})).ElseIf(t.equal(4),(()=>{s.assign(xa(e.x.negate(),e.z).div(bh(e.y)))})).Else((()=>{s.assign(xa(e.x,e.y).div(bh(e.z)))})),No(.5,s.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),ym=la((([e])=>{const t=ga(0).toVar();return da(e.greaterThanEqual(nm),(()=>{t.assign(im.sub(e).mul(am.sub(rm)).div(im.sub(nm)).add(rm))})).ElseIf(e.greaterThanEqual(om),(()=>{t.assign(nm.sub(e).mul(hm.sub(am)).div(nm.sub(om)).add(am))})).ElseIf(e.greaterThanEqual(lm),(()=>{t.assign(om.sub(e).mul(um.sub(hm)).div(om.sub(lm)).add(hm))})).ElseIf(e.greaterThanEqual(cm),(()=>{t.assign(lm.sub(e).mul(dm.sub(um)).div(lm.sub(cm)).add(um))})).Else((()=>{t.assign(ga(-2).mul(nh(No(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),bm=la((([e,t])=>{const s=e.toVar();s.assign(No(2,s).sub(1));const i=wa(s,1).toVar();return da(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"}]}),xm=la((([e,t,s,i,r,n])=>{const a=ga(s),o=wa(t),h=Wh(ym(a),rm,n),l=ch(h),u=hh(h),c=wa(_m(e,o,u,i,r,n)).toVar();return da(l.notEqual(0),(()=>{const t=wa(_m(e,o,u.add(1),i,r,n)).toVar();c.assign(Hh(c,t,l))})),c})),_m=la((([e,t,s,i,r,n])=>{const a=ga(s).toVar(),o=wa(t),h=ga(gm(o)).toVar(),l=ga(Ph(pm.sub(a),0)).toVar();a.assign(Ph(a,pm));const u=ga(ih(a)).toVar(),c=xa(fm(o,h).mul(u.sub(2)).add(1)).toVar();return da(h.greaterThan(2),(()=>{c.y.addAssign(u),h.subAssign(3)})),c.x.addAssign(h.mul(u)),c.x.addAssign(l.mul(No(3,mm))),c.y.addAssign(No(4,ih(n).sub(u))),c.x.mulAssign(i),c.y.mulAssign(r),e.sample(c).grad(xa(),xa())})),vm=la((({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const h=ph(i),l=s.mul(h).add(r.cross(s).mul(dh(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return _m(e,l,t,n,a,o)})),Tm=la((({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=wa(Qh(t,s,Oh(s,i))).toVar();da(d.equal(wa(0)),(()=>{d.assign(wa(i.z,0,i.x.negate()))})),d.assign(uh(d));const p=wa().toVar();return p.addAssign(r.element(0).mul(vm({theta:0,axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),sd({start:fa(1),end:e},(({i:e})=>{da(e.greaterThanEqual(n),(()=>{Al("break").toStack()}));const t=ga(a.mul(ga(e))).toVar();p.addAssign(r.element(e).mul(vm({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(vm({theta:t,axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})))})),Ea(p,1)})),wm=[.125,.215,.35,.446,.526,.582],Sm=20,Mm=new Br(-1,1,1,-1,0,1),Nm=new Ii(90,1),Em=new Gs;let Am=null,Cm=0,Rm=0;const Pm=(1+Math.sqrt(5))/2,Fm=1/Pm,Im=[new _t(-Pm,Fm,0),new _t(Pm,Fm,0),new _t(-Fm,0,Pm),new _t(Fm,0,Pm),new _t(0,Pm,-Fm),new _t(0,Pm,Fm),new _t(-1,1,-1),new _t(1,1,-1),new _t(-1,1,1),new _t(1,1,1)],Bm=new _t,Lm=new WeakMap,Dm=[3,1,5,0,4,2],Om=bm(Il(),Fl("faceIndex")).normalize(),km=wa(Om.x,Om.y,Om.z);class Um{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=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=Bm,renderTarget:o=null}=r;if(this._setSize(n),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const n=o||this._allocateTargets();return r.renderTarget=n,this.fromSceneAsync(e,t,s,i,r),n}Am=this._renderer.getRenderTarget(),Cm=this._renderer.getActiveCubeFace(),Rm=this._renderer.getActiveMipmapLevel();const h=o||this._allocateTargets();return h.depthBuffer=!0,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!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,s,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTargets();return this.fromEquirectangularAsync(e,s),s}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTargets();return this.fromCubemapAsync(e,t),s}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=jm(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Hm(),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===v||e.mapping===T?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._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Am,Cm,Rm),e.scissorTest=!1,Vm(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Am=this._renderer.getRenderTarget(),Cm=this._renderer.getActiveCubeFace(),Rm=this._renderer.getActiveMipmapLevel();const s=t||this._allocateTargets();return this._textureToCubeUV(e,s),this._applyPMREM(s),this._cleanup(s),s}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,s={magFilter:P,minFilter:P,generateMipmaps:!1,type:V,format:H,colorSpace:ve},i=zm(e,t,s);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=zm(e,t,s);const{_lodMax:i}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas,lodMeshes:this._lodMeshes}=function(e){const t=[],s=[],i=[],r=[];let n=e;const a=e-4+1+wm.length;for(let o=0;o<a;o++){const a=Math.pow(2,n);s.push(a);let h=1/a;o>e-4?h=wm[o-e+4-1]:0===o&&(h=0),i.push(h);const l=1/(a-2),u=-l,c=1+l,d=[u,u,c,u,c,c,u,u,c,c,u,c],p=6,m=6,g=3,f=2,y=1,b=new Float32Array(g*m*p),x=new Float32Array(f*m*p),_=new Float32Array(y*m*p);for(let e=0;e<p;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=Dm[e];b.set(i,g*m*r),x.set(d,f*m*r);const n=[r,r,r,r,r,r];_.set(n,y*m*r)}const v=new di;v.setAttribute("position",new ei(b,g)),v.setAttribute("uv",new ei(x,f)),v.setAttribute("faceIndex",new ei(_,y)),t.push(v),r.push(new Si(v,null)),n>4&&n--}return{lodPlanes:t,sizeLods:s,sigmas:i,lodMeshes:r}}(i)),this._blurMaterial=function(e,t,s){const i=Wl(new Array(Sm).fill(0)),r=bo(new _t(0,1,0)),n=bo(0),a=ga(Sm),o=bo(0),h=bo(1),l=Ul(null),u=bo(0),c=ga(1/t),d=ga(1/s),p=ga(e),m={n:a,latitudinal:o,weights:i,poleAxis:r,outputDirection:km,dTheta:n,samples:h,envMap:l,mipInt:u,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=Gm("blur");return g.fragmentNode=Tm({...m,latitudinal:o.equal(1)}),Lm.set(g,m),g}(i,e,t)}return i}async _compileMaterial(e){const t=new Si(this._lodPlanes[0],e);await this._renderer.compile(t,Mm)}_sceneToCubeUV(e,t,s,i,r){const n=Nm;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(Em),h.autoClear=!1;let u=this._backgroundBox;if(null===u){const e=new $s({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1});u=new Si(new Ni,e)}let c=!1;const d=e.background;d?d.isColor&&(u.material.color.copy(d),e.background=null,c=!0):(u.material.color.copy(Em),c=!0),h.setRenderTarget(i),h.clear(),c&&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;Vm(i,s*l,t>2?l:0,l,l),h.render(e,n)}h.autoClear=l,e.background=d}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===v||e.mapping===T;i?null===this._cubemapMaterial&&(this._cubemapMaterial=jm(e)):null===this._equirectMaterial&&(this._equirectMaterial=Hm(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const a=this._cubeSize;Vm(t,0,0,3*a,2*a),s.setRenderTarget(t),s.render(n,Mm)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let t=1;t<i;t++){const s=Math.sqrt(this._sigmas[t]*this._sigmas[t]-this._sigmas[t-1]*this._sigmas[t-1]),r=Im[(i-t-1)%Im.length];this._blur(e,t-1,t,s,r)}t.autoClear=s}_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&&console.error("blur direction must be either latitudinal or longitudinal!");const l=this._lodMeshes[i];l.material=h;const u=Lm.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):Sm;m>Sm&&console.warn(`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<Sm;++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];Vm(t,3*b*(i>y-4?i-y+4:0),4*(this._cubeSize-b),3*b,2*b),o.setRenderTarget(t),o.render(l,Mm)}}function zm(e,t,s){const i=new ft(e,t,s);return i.texture.mapping=306,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function Vm(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function Gm(e){const t=new kd;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function jm(e){const t=Gm("cubemap");return t.fragmentNode=ku(e,km),t}function Hm(e){const t=Gm("equirect");return t.fragmentNode=Ul(e,$d(km),0),t}const Wm=new WeakMap;function $m(e,t,s){const i=function(e){let t=Wm.get(e);void 0===t&&(t=new WeakMap,Wm.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 qm extends xn{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 mt;i.isRenderTargetTexture=!0,this._texture=Ul(i),this._width=bo(0),this._height=bo(0),this._maxMip=bo(0),this.updateBeforeType=on}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:$m(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Um(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=Fu.mul(wa(t.x,t.y.negate(),t.z));let s=this.levelNode;return null===s&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),xm(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const Xm=aa(qm).setParameterLength(1,3),Ym=new WeakMap;class Km extends hd{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 e=s.isTextureNode?s.value:t[s.property];let i=Ym.get(e);void 0===i&&(i=Xm(e),Ym.set(e,i)),s=i}const i=!0===t.useAnisotropy||t.anisotropy>0?Ku:wu,r=s.context(Qm(Ua,i)).mul(Pu),n=s.context(Zm(Su)).mul(Math.PI).mul(Pu),a=Tl(r),o=Tl(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const h=e.context.lightingModel.clearcoatRadiance;if(h){const e=s.context(Qm(Ga,Mu)).mul(Pu),t=Tl(e);h.addAssign(t)}}}const Qm=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=gu.negate().reflect(t),s=e.mul(e).mix(s,t).normalize(),s=s.transformDirection(Ql)),s),getTextureLevel:()=>e}},Zm=e=>({getUV:()=>e,getTextureLevel:()=>ga(1)}),Jm=new pr;class eg extends kd{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(Jm),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Km(t):null}setupLightingModel(){return new sm}setupSpecular(){const e=Hh(wa(.04),Oa.rgb,za);Za.assign(e),Ja.assign(1)}setupVariants(){const e=this.metalnessNode?ga(this.metalnessNode):yc;za.assign(e);let t=this.roughnessNode?ga(this.roughnessNode):fc;t=gp({roughness:t}),Ua.assign(t),this.setupSpecular(),Oa.assign(Ea(Oa.rgb.mul(e.oneMinus()),Oa.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const tg=new mr;class sg extends eg{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(tg),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?ga(this.iorNode):Pc;ro.assign(e),Za.assign(Hh(Rh(Uh(ro.sub(1).div(ro.add(1))).mul(pc),wa(1)).mul(dc),Oa.rgb,za)),Ja.assign(Hh(dc,1,za))}setupLightingModel(){return new sm(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?ga(this.clearcoatNode):xc,t=this.clearcoatRoughnessNode?ga(this.clearcoatRoughnessNode):_c;Va.assign(e),Ga.assign(gp({roughness:t}))}if(this.useSheen){const e=this.sheenNode?wa(this.sheenNode):wc,t=this.sheenRoughnessNode?ga(this.sheenRoughnessNode):Sc;ja.assign(e),Ha.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?ga(this.iridescenceNode):Nc,t=this.iridescenceIORNode?ga(this.iridescenceIORNode):Ec,s=this.iridescenceThicknessNode?ga(this.iridescenceThicknessNode):Ac;Wa.assign(e),$a.assign(t),qa.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?xa(this.anisotropyNode):Mc).toVar();Ya.assign(e.length()),da(Ya.equal(0),(()=>{e.assign(xa(1,0))})).Else((()=>{e.divAssign(xa(Ya)),Ya.assign(Ya.saturate())})),Xa.assign(Ya.pow2().mix(Ua.pow2(),1)),Ka.assign(Yu[0].mul(e.x).add(Yu[1].mul(e.y))),Qa.assign(Yu[1].mul(e.x).sub(Yu[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?ga(this.transmissionNode):Cc,t=this.thicknessNode?ga(this.thicknessNode):Rc,s=this.attenuationDistanceNode?ga(this.attenuationDistanceNode):Fc,i=this.attenuationColorNode?wa(this.attenuationColorNode):Ic;if(no.assign(e),ao.assign(t),oo.assign(s),ho.assign(i),this.useDispersion){const e=this.dispersionNode?ga(this.dispersionNode):Uc;lo.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?wa(this.clearcoatNormalNode):vc}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),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.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 ig=la((({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=xa(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=Hu("gradientMap","texture").context({getUV:()=>r});return wa(e.r)}{const e=r.fwidth().mul(.5);return Hh(wa(.7),wa(1),qh(ga(.7).sub(e.x),ga(.7).add(e.x),r.x))}}));class rg extends tp{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const r=ig({normal:bu,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(r.mul(ap({diffuseColor:Oa.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(ap({diffuseColor:Oa}))),i.indirectDiffuse.mulAssign(t)}}const ng=new fr;class ag extends kd{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(ng),this.setValues(e)}setupLightingModel(){return new rg}}class og extends xn{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=wa(gu.z,0,gu.x.negate()).normalize(),t=gu.cross(e);return xa(e.dot(wu),t.dot(wu)).mul(.495).add(.5)}}const hg=oa(og),lg=new xr;class ug extends kd{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(lg),this.setValues(e)}setupVariants(e){const t=hg;let s;s=e.material.matcap?Hu("matcap","texture").context({getUV:()=>t}):wa(Hh(.2,.8,t.y)),Oa.rgb.mulAssign(s.rgb)}}class cg extends xn{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 Pa(e,i,i.negate(),e).mul(s)}{const e=t,i=Ia(Ea(1,0,0,0),Ea(0,ph(e.x),dh(e.x).negate(),0),Ea(0,dh(e.x),ph(e.x),0),Ea(0,0,0,1)),r=Ia(Ea(ph(e.y),0,dh(e.y),0),Ea(0,1,0,0),Ea(dh(e.y).negate(),0,ph(e.y),0),Ea(0,0,0,1)),n=Ia(Ea(ph(e.z),dh(e.z).negate(),0,0),Ea(dh(e.z),ph(e.z),0,0),Ea(0,0,1,0),Ea(0,0,0,1));return i.mul(r).mul(n).mul(Ea(s,1)).xyz}}}const dg=aa(cg).setParameterLength(2),pg=new Wi;class mg extends kd{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(pg),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,i=this.sizeAttenuation,{positionNode:r,rotationNode:n,scaleNode:a}=this,o=nu.mul(wa(r||0));let h=xa(iu[0].xyz.length(),iu[1].xyz.length());if(null!==a&&(h=h.mul(xa(a))),!1===i)if(s.isPerspectiveCamera)h=h.mul(o.z.negate());else{const e=ga(2).div(Kl.element(1).element(1));h=h.mul(e.mul(2))}let l=lu.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,s)=>ia(new cl(e,t,s)))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(h);const u=ga(n||Tc),c=dg(l,u);return Ea(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 gg=new nr;class fg extends mg{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(gg),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return nu.mul(wa(e||uu)).xyz}setupVertex(e){const t=super.setupVertex(e);if(!0!==e.material.isNodeMaterial)return t;const{rotationNode:s,scaleNode:i,sizeNode:r}=this,n=lu.xy.toVar(),a=xd.z.div(xd.w);if(s&&s.isNode){const e=ga(s);n.assign(dg(n,e))}let o=null!==r?xa(r):kc;return!0===this.sizeAttenuation&&(o=o.mul(o.div(mu.z.negate()))),i&&i.isNode&&(o=o.mul(xa(i))),n.mulAssign(o.mul(2)),n.assign(n.div(xd.z)),n.y.assign(n.y.mul(a)),n.assign(n.mul(t.w)),t.addAssign(Ea(n,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class yg extends tp{constructor(){super(),this.shadowNode=ga(1).toVar("shadowMask")}direct({lightNode:e}){this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Oa.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Oa.rgb)}}const bg=new dr;class xg extends kd{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(bg),this.setValues(e)}setupLightingModel(){return new yg}}La("vec3"),La("vec3"),La("vec3");class _g{constructor(e,t){this.nodes=e,this.info=t,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,null!==this._animationLoop&&this._animationLoop(t,s)};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 vg{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;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.weakMap;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.weakMap;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 Tg=0;class wg{constructor(e,t,s,i,r,n,a,o,h,l){this.id=Tg++,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.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.material.addEventListener("dispose",this.onMaterialDispose)}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)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set;for(const r of e){const e=r.node&&r.node.attribute?r.node.attribute:t.getAttribute(r.name);if(void 0===e)continue;s.push(e);const n=e.isInterleavedBufferAttribute?e.data:e;i.add(n)}return this.attributes=s,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}=this;let s=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 i=t[e];let r;if(null!==i){const e=typeof i;"number"===e?r=0!==i?"1":"0":"object"===e?(r="{",i.isTexture&&(r+=i.mapping),r+="}"):r=String(i)}else r=String(i);s+=r+","}return s+=this.clippingContextCacheKey+",",e.geometry&&(s+=this.getGeometryCacheKey()),e.skeleton&&(s+=e.skeleton.bones.length+","),e.isBatchedMesh&&(s+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(s+=e._colorsTexture.uuid+",")),e.count>1&&(s+=e.uuid+","),s+=e.receiveShadow+",",qr(s)}get needsGeometryUpdate(){return this.geometry.id!==this.object.geometry.id}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=Yr(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Yr(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const Sg=[];class Mg{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);Sg[0]=e,Sg[1]=t,Sg[2]=n,Sg[3]=r;let l=h.get(Sg);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,a,o),h.set(Sg,l)):(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)),Sg.length=0,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new vg)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,a,o,h,l,u){const c=this.getChainMap(u),d=new wg(e,t,s,i,r,n,a,o,h,l);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.delete(d),this.nodes.delete(d),c.delete(d.getChainArray())},d}}class Ng{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 Eg=1,Ag=2,Cg=3,Rg=4,Pg=16;class Fg extends Ng{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===Eg?this.backend.createAttribute(e):t===Ag?this.backend.createIndexAttribute(e):t===Cg?this.backend.createStorageAttribute(e):t===Rg&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version<t.version||t.usage===Be)&&(this.backend.updateAttribute(e),s.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function Ig(e){return null!==e.index?e.index.version:e.attributes.position.version}function Bg(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(Ze(t)?si:ti)(t,1);return r.version=Ig(e),r}class Lg extends Ng{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}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)};t.addEventListener("dispose",s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,Cg):this.updateAttribute(e,Eg);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,Ag);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,Rg)}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}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=Bg(t),e.set(t,s)):s.version!==Ig(t)&&(this.attributes.delete(s),s=Bg(t),e.set(t,s)),i=s}return i}}class Dg{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):console.error("THREE.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 Og{constructor(e){this.cacheKey=e,this.usedTimes=0}}class kg extends Og{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class Ug extends Og{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let zg=0;class Vg{constructor(e,t,s,i=null,r=null){this.id=zg++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=r,this.usedTimes=0}}class Gg extends Ng{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 Vg(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 Vg(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 Vg(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,h),s.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}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 Ug(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 kg(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 jg extends Ng{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))}_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.isStorageBuffer){const e=t.attribute,s=e.isIndirectStorageBufferAttribute?Rg:Cg;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(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,s=e.isIndirectStorageBufferAttribute?Rg:Cg;this.attributes.update(e,s)}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){const e=this.textures.get(t.texture);t.needsBindingsUpdate(e.generation)&&(i=!0);const o=t.update(),h=t.texture;o&&this.textures.updateTexture(h);const l=s.get(h);if(void 0!==l.externalTexture||e.isDefaultTexture?r=!1:(n=10*n+h.id,a+=h.version),!0===s.isWebGPUBackend&&void 0===l.texture&&void 0===l.externalTexture&&(console.error("Bindings._update: binding should be available:",t,o,h,t.textureNode.value,i),this.textures.updateTexture(h),i=!0),!0===h.isStorageTexture){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)}}}!0===i&&this.backend.updateBindings(e,t,r?n:0,a)}}function Hg(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 Wg(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 $g(e){return(e.transmission>0||e.transmissionNode)&&2===e.side&&!1===e.forceSinglePass}class qg{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?($g(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?($g(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||Hg),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Wg),this.transparent.length>1&&this.transparent.sort(t||Wg)}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 Xg=[];class Yg{constructor(e){this.lighting=e,this.lists=new vg}get(e,t){const s=this.lists;Xg[0]=e,Xg[1]=t;let i=s.get(Xg);return void 0===i&&(i=new qg(this.lighting,e,t),s.set(Xg,i)),Xg.length=0,i}dispose(){this.lists=new vg}}let Kg=0;class Qg{constructor(){this.id=Kg++,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 gt,this.scissor=!1,this.scissorValue=new gt,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.isRenderContext=!0}getCacheKey(){return Zg(this)}}function Zg(e){const{textures:t,activeCubeFace:s}=e,i=[s];for(const e of t)i.push(e.id);return Xr(i)}const Jg=[],ef=new Vi,tf=new Ci;class sf{constructor(){this.chainMaps={}}get(e,t,s=null){let i;if(Jg[0]=e,Jg[1]=t,null===s)i="default";else{const e=s.texture.format;i=`${s.textures.length}:${e}:${s.samples}:${s.depthBuffer}:${s.stencilBuffer}`}const r=this._getChainMap(i);let n=r.get(Jg);return void 0===n&&(n=new Qg,r.set(Jg,n)),Jg.length=0,null!==s&&(n.sampleCount=0===s.samples?1:s.samples),n}getForClear(e=null){return this.get(ef,tf,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new vg)}dispose(){this.chainMaps={}}}const rf=new _t;class nf extends Ng{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 l=e.depthTexture||r[t];const u=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===l&&u&&(l=!0===e.multiview&&a.depth>1?new hr:new or,l.format=e.stencilBuffer?$:W,l.type=e.stencilBuffer?G:U,l.image.width=o,l.image.height=h,l.image.depth=a.depth,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.isDepthArrayTexture?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 t=0;t<n.length;t++){const s=n[t];s.isTextureArray=!0===e.multiview&&a.depth>1,c&&(s.needsUpdate=!0),this.updateTexture(s,d)}l&&this.updateTexture(l,d)}if(!0!==s.initialized){s.initialized=!0;const t=()=>{e.removeEventListener("dispose",t);for(let e=0;e<n.length;e++)this._destroyTexture(n[e]);l&&this._destroyTexture(l),this.delete(e)};e.addEventListener("dispose",t)}}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.destroySampler(e),r.destroyTexture(e)),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:B}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,i||!0===e.isStorageTexture)r.createSampler(e),r.createTexture(e,t),s.generation=e.version;else{if(!0!==s.initialized&&r.createSampler(e),e.version>0){const i=e.image;if(void 0===i)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)console.warn("THREE.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),t.needsMipmaps&&0===e.mipmaps.length&&r.generateMipmaps(e)}}else r.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version}if(!0!==s.initialized){s.initialized=!0,s.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e)};e.addEventListener("dispose",t)}s.version=e.version}getSize(e,t=rf){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),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.isCompressedTexture?e.mipmaps?e.mipmaps.length:1:Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return!0===e.isCompressedTexture||e.generateMipmaps}_destroyTexture(e){!0===this.has(e)&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class af extends Gs{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 of extends Ba{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class hf extends fn{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const s=new sa(t);return this._currentCond=Qh(e,s),this.add(this._currentCond)}ElseIf(e,t){const s=new sa(t),i=Qh(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new sa(e),this}Switch(e){return this._expressionNode=ia(e),this}Case(...e){const t=[];if(!(e.length>=2))throw new Error("TSL: Invalid parameter length. Case() requires at least two parameters.");for(let s=0;s<e.length-1;s++)t.push(this._expressionNode.equal(ia(e[s])));const s=new sa(e[e.length-1]);let i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);const r=Qh(i,s);return null===this._currentCond?(this._currentCond=r,this.add(this._currentCond)):(this._currentCond.elseNode=r,this._currentCond=r,this)}Default(e){return this.Else(e),this}build(e,...t){const s=ca();ua(this);for(const t of this.nodes)t.build(e,"void");return ua(s),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("THREE.TSL: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("THREE.TSL: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const lf=aa(hf).setParameterLength(0,1);new Qi,new _t,new _t,new _t,new Kt,new _t(0,0,-1),new gt,new _t,new _t,new gt,new Ye;const uf=new ft;fd.flipX(),uf.depthTexture=new or(1,1);const cf=new Br(-1,1,1,-1,0,1);class df extends di{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 pf=new df;class mf extends Si{constructor(e=null){super(pf,e),this.camera=cf,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,cf)}render(e){e.render(this,cf)}}const gf=new as,ff=new Kt;class yf extends fn{static get type(){return"SceneNode"}constructor(e=yf.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=null!==this.scene?this.scene:e.scene;let i;return t===yf.BACKGROUND_BLURRINESS?i=Vu("backgroundBlurriness","float",s):t===yf.BACKGROUND_INTENSITY?i=Vu("backgroundIntensity","float",s):t===yf.BACKGROUND_ROTATION?i=bo("mat4").label("backgroundRotation").setGroup(go).onRenderUpdate((()=>{const e=s.background;return null!==e&&e.isTexture&&300!==e.mapping?(gf.copy(s.backgroundRotation),gf.x*=-1,gf.y*=-1,gf.z*=-1,ff.makeRotationFromEuler(gf)):ff.identity(),ff})):console.error("THREE.SceneNode: Unknown scope:",t),i}}yf.BACKGROUND_BLURRINESS="backgroundBlurriness",yf.BACKGROUND_INTENSITY="backgroundIntensity",yf.BACKGROUND_ROTATION="backgroundRotation";const bf=oa(yf,yf.BACKGROUND_BLURRINESS),xf=oa(yf,yf.BACKGROUND_INTENSITY),_f=oa(yf,yf.BACKGROUND_ROTATION),vf=la((({texture:e,uv:t})=>{const s=1e-4,i=wa().toVar();return da(t.x.lessThan(s),(()=>{i.assign(wa(1,0,0))})).ElseIf(t.y.lessThan(s),(()=>{i.assign(wa(0,1,0))})).ElseIf(t.z.lessThan(s),(()=>{i.assign(wa(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{i.assign(wa(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{i.assign(wa(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{i.assign(wa(0,0,-1))})).Else((()=>{const s=.01,r=e.sample(t.add(wa(-.01,0,0))).r.sub(e.sample(t.add(wa(s,0,0))).r),n=e.sample(t.add(wa(0,-.01,0))).r.sub(e.sample(t.add(wa(0,s,0))).r),a=e.sample(t.add(wa(0,0,-.01))).r.sub(e.sample(t.add(wa(0,0,s))).r);i.assign(wa(r,n,a))})),i.normalize()}));class Tf 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 wa(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return!e.isFlipY()||!0!==s.isRenderTargetTexture&&!0!==s.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(fa(Ll(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return vf({texture:this,uv:e})}}const wf=aa(Tf).setParameterLength(1,3),Sf=new Ye;class Mf extends kl{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Nf extends Mf{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class Ef extends xn{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 or;r.isRenderTargetTexture=!0,r.name="depth";const n=new ft(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:V,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=bo(0),this._cameraFar=bo(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=an}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}isGlobal(){return!0}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=ia(new Nf(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=ia(new Nf(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=Cd(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=Ed(r,s,i)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,!0===e.backend.isWebGLBackend&&(this.renderTarget.samples=0),this.renderTarget.texture.type=e.getColorBufferType(),this.scope===Ef.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),Sf.set(n.width,n.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(Sf)),this._pixelRatio=r,this.setSize(Sf.width,Sf.height);const a=t.getRenderTarget(),o=t.getMRT(),h=i.layers.mask;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);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(s,i),t.setRenderTarget(a),t.setMRT(o),i.layers.mask=h}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio*this._resolution,i=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Ef.COLOR="color",Ef.DEPTH="depth";const Af=la((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Cf=la((([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"}]}),Rf=la((([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"}]}),Pf=la((([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)})),Ff=la((([e,t])=>{const s=Fa(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Fa(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=Pf(e),(e=i.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),If=Fa(wa(1.6605,-.1246,-.0182),wa(-.5876,1.1329,-.1006),wa(-.0728,-.0083,1.1187)),Bf=Fa(wa(.6274,.0691,.0164),wa(.3293,.9195,.088),wa(.0433,.0113,.8956)),Lf=la((([e])=>{const t=wa(e).toVar(),s=wa(t.mul(t)).toVar(),i=wa(s.mul(s)).toVar();return ga(15.5).mul(i.mul(s)).sub(No(40.14,i.mul(t))).add(No(31.96,i).sub(No(6.868,s.mul(t))).add(No(.4298,s).add(No(.1191,t).sub(.00232))))})),Df=la((([e,t])=>{const s=wa(e).toVar(),i=Fa(wa(.856627153315983,.137318972929847,.11189821299995),wa(.0951212405381588,.761241990602591,.0767994186031903),wa(.0482516061458583,.101439036467562,.811302368396859)),r=Fa(wa(1.1271005818144368,-.1413297634984383,-.14132976349843826),wa(-.11060664309660323,1.157823702216272,-.11060664309660294),wa(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=ga(-12.47393),a=ga(4.026069);return s.mulAssign(t),s.assign(Bf.mul(s)),s.assign(i.mul(s)),s.assign(Ph(s,1e-10)),s.assign(nh(s)),s.assign(s.sub(n).div(a.sub(n))),s.assign(Wh(s,0,1)),s.assign(Lf(s)),s.assign(r.mul(s)),s.assign(kh(Ph(wa(0),s),wa(2.2))),s.assign(If.mul(s)),s.assign(Wh(s,0,1)),s})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Of=la((([e,t])=>{const s=ga(.76),i=ga(.15);e=e.mul(t);const r=Rh(e.r,Rh(e.g,e.b)),n=Qh(r.lessThan(.08),r.sub(No(6.25,r.mul(r))),.04);e.subAssign(n);const a=Ph(e.r,Ph(e.g,e.b));da(a.lessThan(s),(()=>e));const o=Mo(1,s),h=Mo(1,o.mul(o).div(a.add(o.sub(s))));e.mulAssign(h.div(a));const l=Mo(1,Eo(1,i.mul(a.sub(h)).add(1)));return Hh(e,wa(h),l)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class kf extends fn{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.code=e,this.includes=t,this.language=s}isGlobal(){return!0}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 Uf extends kf{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}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 zf(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||mu.z).negate()}const Vf=la((([e,t],s)=>{const i=zf(s);return qh(e,t,i)})),Gf=la((([e],t)=>{const s=zf(t);return e.mul(e,s,s).negate().exp().oneMinus()})),jf=la((([e,t])=>Ea(t.toFloat().mix(to.rgb,e.toVec3()),to.a)));aa(class extends fn{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 Hf extends fn{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 l=`${e.getMethod(i,r)}( ${h.join(", ")} )`;if(!(1===s.length&&!0===s[0].isStackNode))return void 0===t.constNode&&(t.constNode=Al(l,r).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}let Wf;function $f(e){Wf=Wf||new WeakMap;let t=Wf.get(e);return void 0===t&&Wf.set(e,t={}),t}function qf(e){const t=$f(e);return t.shadowMatrix||(t.shadowMatrix=bo("mat4").setGroup(go).onRenderUpdate((()=>(!0!==e.castShadow&&e.shadow.updateMatrices(e),e.shadow.matrix))))}function Xf(e){const t=$f(e);return t.position||(t.position=bo(new _t).setGroup(go).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld))))}function Yf(e){const t=$f(e);return t.viewPosition||(t.viewPosition=bo(new _t).setGroup(go).onRenderUpdate((({camera:t},s)=>{s.value=s.value||new _t,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)})))}Hf.ATOMIC_LOAD="atomicLoad",Hf.ATOMIC_STORE="atomicStore",Hf.ATOMIC_ADD="atomicAdd",Hf.ATOMIC_SUB="atomicSub",Hf.ATOMIC_MAX="atomicMax",Hf.ATOMIC_MIN="atomicMin",Hf.ATOMIC_AND="atomicAnd",Hf.ATOMIC_OR="atomicOr",Hf.ATOMIC_XOR="atomicXor",aa(Hf);const Kf=e=>Ql.transformDirection(Xf(e).sub(function(e){const t=$f(e);return t.targetPosition||(t.targetPosition=bo(new _t).setGroup(go).onRenderUpdate(((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld))))}(e))),Qf=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},Zf=new WeakMap;class Jf extends fn{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=wa().toVar(),this.totalSpecularNode=wa().toVar(),this.outgoingLightNode=wa().toVar(),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=[],t=this._lights;for(let s=0;s<t.length;s++){const i=t[s];if(e.push(i.id),!0===i.isSpotLight){const t=null!==i.map?i.map.id:-1;e.push(t)}}return Xr(e)}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getSelf().getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getDataFromNode(this);for(const s of t.nodes)s.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(ia(e));else{let i=null;if(null!==s&&(i=Qf(e.id,s)),null===i){const s=r.getLightNodeClass(e.constructor);if(null===s){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;Zf.has(e)?i=Zf.get(e):(i=ia(new s(e)),Zf.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.getDataFromNode(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=wa(null!==l?l.mix(m,h):h),i.material.transparent=!0),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 ey extends fn{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=on,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){ty.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||du)}dispose(){this.updateBeforeType=nn}}const ty=La("vec3","shadowPositionWorld");function sy(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 Gs),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 iy=new WeakMap,ry=la((({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=Ul(e,t.xy).label("t_basic");return e.isDepthArrayTexture&&(i=i.depth(s)),i.compare(t.z)})),ny=la((({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=Ul(e,t);return e.isDepthArrayTexture&&(r=r.depth(i)),r.compare(s)},n=Vu("mapSize","vec2",s).setGroup(go),a=Vu("radius","float",s).setGroup(go),o=xa(1).div(n),h=o.x.negate().mul(a),l=o.y.negate().mul(a),u=o.x.mul(a),c=o.y.mul(a),d=h.div(2),p=l.div(2),m=u.div(2),g=c.div(2);return So(r(t.xy.add(xa(h,l)),t.z),r(t.xy.add(xa(0,l)),t.z),r(t.xy.add(xa(u,l)),t.z),r(t.xy.add(xa(d,p)),t.z),r(t.xy.add(xa(0,p)),t.z),r(t.xy.add(xa(m,p)),t.z),r(t.xy.add(xa(h,0)),t.z),r(t.xy.add(xa(d,0)),t.z),r(t.xy,t.z),r(t.xy.add(xa(m,0)),t.z),r(t.xy.add(xa(u,0)),t.z),r(t.xy.add(xa(d,g)),t.z),r(t.xy.add(xa(0,g)),t.z),r(t.xy.add(xa(m,g)),t.z),r(t.xy.add(xa(h,c)),t.z),r(t.xy.add(xa(0,c)),t.z),r(t.xy.add(xa(u,c)),t.z)).mul(1/17)})),ay=la((({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=Ul(e,t);return e.isDepthArrayTexture&&(r=r.depth(i)),r.compare(s)},n=Vu("mapSize","vec2",s).setGroup(go),a=xa(1).div(n),o=a.x,h=a.y,l=t.xy,u=ch(l.mul(n).add(.5));return l.subAssign(u.mul(a)),So(r(l,t.z),r(l.add(xa(o,0)),t.z),r(l.add(xa(0,h)),t.z),r(l.add(a),t.z),Hh(r(l.add(xa(o.negate(),0)),t.z),r(l.add(xa(o.mul(2),0)),t.z),u.x),Hh(r(l.add(xa(o.negate(),h)),t.z),r(l.add(xa(o.mul(2),h)),t.z),u.x),Hh(r(l.add(xa(0,h.negate())),t.z),r(l.add(xa(0,h.mul(2))),t.z),u.y),Hh(r(l.add(xa(o,h.negate())),t.z),r(l.add(xa(o,h.mul(2))),t.z),u.y),Hh(Hh(r(l.add(xa(o.negate(),h.negate())),t.z),r(l.add(xa(o.mul(2),h.negate())),t.z),u.x),Hh(r(l.add(xa(o.negate(),h.mul(2))),t.z),r(l.add(xa(o.mul(2),h.mul(2))),t.z),u.x),u.y)).mul(1/9)})),oy=la((({depthTexture:e,shadowCoord:t,depthLayer:s})=>{const i=ga(1).toVar();let r=Ul(e).sample(t.xy);(e.isDepthArrayTexture||e.isDataArrayTexture)&&(r=r.depth(s)),r=r.rg;const n=Fh(t.z,r.x);return da(n.notEqual(ga(1)),(()=>{const e=t.z.sub(r.x),s=Ph(0,r.y.mul(r.y));let a=s.div(s.add(e.mul(e)));a=Wh(Mo(a,.3).div(.95-.3)),i.assign(Wh(Ph(n,a)))})),i})),hy=la((([e,t,s])=>{let i=du.sub(e).length();return i=i.sub(t).div(s.sub(t)),i=i.saturate(),i})),ly=e=>{let t=iy.get(e);if(void 0===t){const s=e.isPointLight?(e=>{const t=e.shadow.camera,s=Vu("near","float",t).setGroup(go),i=Vu("far","float",t).setGroup(go),r=tu(e);return hy(r,s,i)})(e):null;t=new kd,t.colorNode=Ea(0,0,0,1),t.depthNode=s,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,iy.set(e,t)}return t},uy=new vg,cy=[],dy=la((({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=ga(0).toVar("meanVertical"),a=ga(0).toVar("squareMeanVertical"),o=e.lessThanEqual(ga(1)).select(ga(0),ga(2).div(e.sub(1))),h=e.lessThanEqual(ga(1)).select(ga(0),ga(-1));sd({start:fa(0),end:fa(e),type:"int",condition:"<"},(({i:e})=>{const l=h.add(ga(e).mul(o));let u=i.sample(So(bd.xy,xa(0,l).mul(t)).div(s));(i.value.isDepthArrayTexture||i.value.isDataArrayTexture)&&(u=u.depth(r)),u=u.x,n.addAssign(u),a.addAssign(u.mul(u))})),n.divAssign(e),a.divAssign(e);const l=ah(a.sub(n.mul(n)));return xa(n,l)})),py=la((({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=ga(0).toVar("meanHorizontal"),a=ga(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(ga(1)).select(ga(0),ga(2).div(e.sub(1))),h=e.lessThanEqual(ga(1)).select(ga(0),ga(-1));sd({start:fa(0),end:fa(e),type:"int",condition:"<"},(({i:e})=>{const l=h.add(ga(e).mul(o));let u=i.sample(So(bd.xy,xa(l,0).mul(t)).div(s));(i.value.isDepthArrayTexture||i.value.isDataArrayTexture)&&(u=u.depth(r)),n.addAssign(u.x),a.addAssign(So(u.y.mul(u.y),u.x.mul(u.x)))})),n.divAssign(e),a.divAssign(e);const l=ah(a.sub(n.mul(n)));return xa(n,l)})),my=[ry,ny,ay,oy];let gy;const fy=new mf;class yy extends ey{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._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,ga(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=Vu("bias","float",s).setGroup(go);let n,a=t;if(s.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z,i.coordinateSystem===De&&(n=n.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=Vu("near","float",s.camera).setGroup(go),i=Vu("far","float",s.camera).setGroup(go);n=Rd(e.negate(),t,i)}return a=wa(a.x,a.y.oneMinus(),n.add(r)),a}getShadowFilterFn(e){return my[e]}setupRenderTarget(e,t){const s=new or(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=513;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}=e,{light:s,shadow:i}=this,r=t.shadowMap.type,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(i,e);if(i.camera.updateProjectionMatrix(),3===r){n.compareFunction=null,a.isRenderTargetArray?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTargetArray(i.mapSize.width,i.mapSize.height,a.depth,{format:Y,type:V,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTargetArray(i.mapSize.width,i.mapSize.height,a.depth,{format:Y,type:V,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:Y,type:V,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:Y,type:V,depthBuffer:!1}));let t=Ul(n);n.isDepthArrayTexture&&(t=t.depth(this.depthLayer));let s=Ul(this.vsmShadowMapVertical.texture);n.isDepthArrayTexture&&(s=s.depth(this.depthLayer));const r=Vu("blurSamples","float",i).setGroup(go),o=Vu("radius","float",i).setGroup(go),h=Vu("mapSize","vec2",i).setGroup(go);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new kd);l.fragmentNode=dy({samples:r,radius:o,size:h,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new kd),l.fragmentNode=py({samples:r,radius:o,size:h,shadowPass:s,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const o=Vu("intensity","float",i).setGroup(go),h=Vu("normalBias","float",i).setGroup(go),l=qf(s).mul(ty.add(Su.mul(h))),u=this.setupShadowCoord(e,l),c=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===c)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const d=3===r?this.vsmShadowMapHorizontal.texture:n,p=this.setupShadowFilter(e,{filterFn:c,shadowTexture:a.texture,depthTexture:d,shadowCoord:u,shadow:i,depthLayer:this.depthLayer});let m=Ul(a.texture,u);n.isDepthArrayTexture&&(m=m.depth(this.depthLayer));const g=Hh(1,p.rgb.mix(m,1),o.mul(m.a)).toVar();return this.shadowMap=a,this.shadow.map=a,g}setup(e){if(!1!==e.renderer.shadowMap.enabled)return la((()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t}))()}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),r.render(n,t.camera)}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");gy=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=sy(e,s)),s}(r,n,gy),n.overrideMaterial=ly(s),r.setRenderObjectFunction(((e,t,s,i)=>{cy[0]=e,cy[1]=t;let r=uy.get(cy);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&&(sn(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,uy.set(cy,r)),cy[0]=null,cy[1]=null,r})(r,i,o,d)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(u),!0!==s.isPointLight&&3===o&&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,gy)}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),fy.material=this.vsmMaterialVertical,fy.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),fy.material=this.vsmMaterialHorizontal,fy.render(e)}dispose(){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),super.dispose()}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 by=new Gs,xy=la((([e,t])=>{const s=e.toVar(),i=bh(s),r=Eo(1,Ph(i.x,Ph(i.y,i.z)));i.mulAssign(r),s.mulAssign(r.mul(t.mul(2).oneMinus()));const n=xa(s.xy).toVar(),a=t.mul(1.5).oneMinus();return da(i.z.greaterThanEqual(a),(()=>{da(s.z.greaterThan(0),(()=>{n.x.assign(Mo(4,s.x))}))})).ElseIf(i.x.greaterThanEqual(a),(()=>{const e=xh(s.x);n.x.assign(s.z.mul(e).add(e.mul(2)))})).ElseIf(i.y.greaterThanEqual(a),(()=>{const e=xh(s.y);n.x.assign(s.x.add(e.mul(2)).add(2)),n.y.assign(s.z.mul(e).sub(2))})),xa(.125,.25).mul(n).add(xa(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),_y=la((({depthTexture:e,bd3D:t,dp:s,texelSize:i})=>Ul(e,xy(t,i.y)).compare(s))),vy=la((({depthTexture:e,bd3D:t,dp:s,texelSize:i,shadow:r})=>{const n=Vu("radius","float",r).setGroup(go),a=xa(-1,1).mul(n).mul(i.y);return Ul(e,xy(t.add(a.xyy),i.y)).compare(s).add(Ul(e,xy(t.add(a.yyy),i.y)).compare(s)).add(Ul(e,xy(t.add(a.xyx),i.y)).compare(s)).add(Ul(e,xy(t.add(a.yyx),i.y)).compare(s)).add(Ul(e,xy(t,i.y)).compare(s)).add(Ul(e,xy(t.add(a.xxy),i.y)).compare(s)).add(Ul(e,xy(t.add(a.yxy),i.y)).compare(s)).add(Ul(e,xy(t.add(a.xxx),i.y)).compare(s)).add(Ul(e,xy(t.add(a.yxx),i.y)).compare(s)).mul(1/9)})),Ty=la((({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i})=>{const r=s.xyz.toVar(),n=r.length(),a=bo("float").setGroup(go).onRenderUpdate((()=>i.camera.near)),o=bo("float").setGroup(go).onRenderUpdate((()=>i.camera.far)),h=Vu("bias","float",i).setGroup(go),l=bo(i.mapSize).setGroup(go),u=ga(1).toVar();return da(n.sub(o).lessThanEqual(0).and(n.sub(a).greaterThanEqual(0)),(()=>{const s=n.sub(a).div(o.sub(a)).toVar();s.addAssign(h);const c=r.normalize(),d=xa(1).div(l.mul(xa(4,2)));u.assign(e({depthTexture:t,bd3D:c,dp:s,texelSize:d,shadow:i}))})),u})),wy=new gt,Sy=new Ye,My=new Ye;class Ny extends yy{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?_y:vy}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:r,shadow:n}){return Ty({filterFn:t,shadowTexture:s,depthTexture:i,shadowCoord:r,shadow:n})}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:r,scene:n}=e,a=t.getFrameExtents();My.copy(t.mapSize),My.multiply(a),s.setSize(My.width,My.height),Sy.copy(t.mapSize);const o=r.autoClear,h=r.getClearColor(by),l=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha),r.clear();const u=t.getViewportCount();for(let e=0;e<u;e++){const a=t.getViewport(e),o=Sy.x*a.x,h=My.y-Sy.y-Sy.y*a.y;wy.set(o,h,Sy.x*a.z,Sy.y*a.w),s.viewport.copy(wy),t.updateMatrices(i,e),r.render(n,t.camera)}r.autoClear=o,r.setClearColor(h,l)}}class Ey extends hd{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Gs,this.colorNode=e&&e.colorNode||bo(this.color).setGroup(go),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=an}customCacheKey(){return Yr(this.light.id,this.light.castShadow?1:0)}getHash(){return this.light.uuid}getLightVector(e){return Yf(this.light).sub(e.context.positionView||mu)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>ia(new yy(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?ia(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=s=this.colorNode.mul(t),this.baseColorNode=this.colorNode}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 Ay=la((({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 Cy extends Ey{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=bo(0).setGroup(go),this.decayExponentNode=bo(2).setGroup(go)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>ia(new Ny(e,t)))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:s,decayExponent:i})=>{const r=t.normalize(),n=t.length(),a=Ay({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})}}la((([e=Il()],{renderer:t,material:s})=>{const i=ga(1).toVar(),r=jh(e.mul(2).sub(1));if(s.alphaToCoverage&&t.samples>1){const e=ga(r.fwidth()).toVar();i.assign(qh(e.oneMinus(),e.add(1),r).oneMinus())}else r.greaterThan(1).discard();return i}));const Ry=la((([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(No(s,s).sub(No(i,i)))),n})),Py=new af;class Fy extends Ng{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(Py),Py.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(Py),Py.a=1,n=!0;else if(!0===r.isNode){const o=this.get(e),h=r;Py.copy(i._clearColor);let l=o.backgroundMesh;if(void 0===l){const c=Jh(Ea(h).mul(xf),{getUV:()=>_f.mul(Tu),getTextureLevel:()=>bf});let d=jc;d=d.setZ(d.w);const p=new kd;function m(){r.removeEventListener("dispose",m),l.material.dispose(),l.geometry.dispose()}p.name="Background.material",p.side=1,p.depthTest=!1,p.depthWrite=!1,p.allowOverride=!1,p.fog=!1,p.lights=!1,p.vertexNode=d,p.colorNode=c,o.backgroundMeshNode=c,o.backgroundMesh=l=new Si(new cr(1,32,32),p),l.frustumCulled=!1,l.name="Background.mesh",l.onBeforeRender=function(e,t,s){this.matrixWorld.copyPosition(s.matrixWorld)},r.addEventListener("dispose",m)}const u=h.getCacheKey();o.backgroundCacheKey!==u&&(o.backgroundMeshNode.node=Ea(h).mul(xf),o.backgroundMeshNode.needsUpdate=!0,l.material.needsUpdate=!0,o.backgroundCacheKey=u),t.unshift(l,l.geometry,l.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",r);const a=i.xr.getEnvironmentBlendMode();if("additive"===a?Py.set(0,0,0,1):"alpha-blend"===a&&Py.set(0,0,0,0),!0===i.autoClear||!0===n){const g=s.clearColorValue;g.r=Py.r,g.g=Py.g,g.b=Py.b,g.a=Py.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(g.r*=g.a,g.g*=g.a,g.b*=g.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,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 Iy=0;class By{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=Iy++}}class Ly{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 By(t.name,[],t.index,t);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}class Dy{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class Oy{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s.getSelf()}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 ky{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class Uy extends ky{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class zy{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let Vy=0;class Gy{constructor(e=null){this.id=Vy++,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 jy{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class Hy{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class Wy extends Hy{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class $y extends Hy{constructor(e,t=new Ye){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class qy extends Hy{constructor(e,t=new _t){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class Xy extends Hy{constructor(e,t=new gt){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class Yy extends Hy{constructor(e,t=new Gs){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class Ky extends Hy{constructor(e,t=new Hr){super(e,t),this.isMatrix2Uniform=!0,this.boundary=16,this.itemSize=4}}class Qy extends Hy{constructor(e,t=new Ke){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class Zy extends Hy{constructor(e,t=new Kt){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Jy extends Wy{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class eb extends $y{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class tb extends qy{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class sb extends Xy{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ib extends Yy{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class rb extends Ky{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class nb extends Qy{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ab extends Zy{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const ob=new WeakMap,hb=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),lb=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class ub{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.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=lf(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Gy,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null}getBindGroupsCache(){let e=ob.get(this.renderer);return void 0===e&&(e=new vg,ob.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new ft(e,t,s)}createRenderTargetArray(e,t,s,i){return new Gr(e,t,s,i)}createCubeRenderTarget(e,t){return new qd(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let r,n=!0;for(const e of t)i.push(e),n=n&&!0!==e.groupNode.shared;return n?(r=s.get(i),void 0===r&&(r=new By(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new By(e,i,this.bindingsIndexes[e].group,i),r}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 pn)for(const i in s[e]){const r=s[e][i];(t[i]||(t[i]=[])).push(...r)}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){!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==nn&&this.updateNodes.push(e.getSelf())}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==nn&&this.updateBeforeNodes.push(e.getSelf()),s!==nn&&this.updateAfterNodes.push(e.getSelf())}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===P||e.magFilter===F||e.magFilter===R||e.magFilter===I||e.minFilter===P||e.minFilter===F||e.minFilter===R||e.minFilter===I}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}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}getSharedContext(){return this.context,this.context}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 Gy(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){console.warn("Abstract function.")}getInstanceIndex(){console.warn("Abstract function.")}getDrawIndex(){console.warn("Abstract function.")}getFrontFacing(){console.warn("Abstract function.")}getFragCoord(){console.warn("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(){console.warn("Abstract function.")}generateTextureLod(){console.warn("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 Gs:"vec2"===e?t=new Ye:"vec3"===e?t=new _t:"vec4"===e&&(t=new gt)),"float"===e)return lb(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")}( ${lb(t.r)}, ${lb(t.g)}, ${lb(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 Dy(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===k)return"int";if(t===U)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=function(e){return Zr.get(e)}(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return hb.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 ii||!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")}addStack(){return this.stack=lf(this.stack),this.stacks.push(ca()||this.stack),ua(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,ua(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);return void 0===i&&(i={},s.setData(e,i)),void 0===i[t]&&(i[t]={}),i[t]}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);let i=s.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new Dy("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}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 e=this.structs.index++;null===s&&(s="StructType"+e),n=new jy(s,t),this.structs[i].push(n),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 Oy(i||"nodeUniform"+a,t,e),this.uniforms[s].push(n),this.registerDeclaration(n),r.uniform=n}return n}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage,r=!1){const n=this.getDataFromNode(e,i);let a=n.variable;if(void 0===a){const o=r?"_const":"_var",h=this.vars[i]||(this.vars[i]=[]),l=this.vars[o]||(this.vars[o]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+l,this.vars[o]++);const u=this.getArrayCount(e);a=new ky(t,s,r,u),r||h.push(a),this.registerDeclaration(a),n.variable=a}return a}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");let a=n.varying;if(void 0===a){const e=this.varyings,o=e.length;null===t&&(t="nodeVarying"+o),a=new Uy(t,s,i,r),e.push(a),this.registerDeclaration(a),n.varying=a}return a}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,console.warn(`THREE.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 zy("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 Uf,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 of(e.type,e.name);e.layout=null;const i=e.call(s),r=this.flowStagesNode(i,t.type);return e.layout=t,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 Gy,this.stack=lf();for(const s of dn)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(){console.warn("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.shaderStage;this.setShaderStage(e);const n=this.flowChildNode(t,s);return null!==i&&(n.code+=`${this.tab+i} = ${n.result};\n`),this.flowCode[e]=this.flowCode[e]+n.code,this.setShaderStage(r),n}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("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(){console.warn("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(){console.warn("Abstract function.")}build(){const{object:e,material:t,renderer:s}=this;if(null!==t){let e=s.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new kd),e.build(this)}else this.addFlow("compute",e);for(const e of dn){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of pn){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}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new Jy(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new eb(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new tb(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new sb(e);if("color"===t)return new ib(e);if("mat2"===t)return new rb(e);if("mat3"===t)return new nb(e);if("mat4"===t)return new ab(e);throw new Error(`Uniform "${t}" not declared.`)}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`}*[Symbol.iterator](){}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}}class cb{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={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===an){const{frameMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(s,this.frameId)}else if(t===on){const{renderMap:t}=this._getMaps(this.updateBeforeMap,s);t.get(s)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(s,this.renderId)}else t===hn&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===an){const{frameMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(s,this.frameId)}else if(t===on){const{renderMap:t}=this._getMaps(this.updateAfterMap,s);t.get(s)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(s,this.renderId)}else t===hn&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===an){const{frameMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.frameId&&!1!==e.update(this)&&t.set(s,this.frameId)}else if(t===on){const{renderMap:t}=this._getMaps(this.updateMap,s);t.get(s)!==this.renderId&&!1!==e.update(this)&&t.set(s,this.renderId)}else t===hn&&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 db{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}db.isNodeFunctionInput=!0;class pb extends Ey{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:Kf(this.light),lightColor:e}}}const mb=new Kt,gb=new Kt;let fb=null;class yb extends Ey{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=bo(new _t).setGroup(go),this.halfWidth=bo(new _t).setGroup(go),this.updateType=on}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;gb.identity(),mb.copy(t.matrixWorld),mb.premultiply(s),gb.extractRotation(mb),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(gb),this.halfHeight.value.applyMatrix4(gb)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=Ul(fb.LTC_FLOAT_1),s=Ul(fb.LTC_FLOAT_2)):(t=Ul(fb.LTC_HALF_1),s=Ul(fb.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:Yf(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){fb=e}}class bb extends Ey{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=bo(0).setGroup(go),this.penumbraCosNode=bo(0).setGroup(go),this.cutoffDistanceNode=bo(0).setGroup(go),this.decayExponentNode=bo(0).setGroup(go)}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){const{coneCosNode:t,penumbraCosNode:s}=this;return qh(t,s,e)}setupDirect(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:r}=this,n=this.getLightVector(e),a=n.normalize(),o=a.dot(Kf(r)),h=this.getSpotAttenuation(o),l=n.length(),u=Ay({lightDistance:l,cutoffDistance:s,decayExponent:i});let c=t.mul(h).mul(u);if(r.map){const t=function(e,t=du){const s=qf(e).mul(t);return s.xyz.div(s.w)}(r,e.context.positionWorld),s=Ul(r.map,t.xy).onRenderUpdate((()=>r.map));c=t.mul(2).sub(1).abs().lessThan(1).all().select(c.mul(s),c)}return{lightColor:c,lightDirection:a}}}class xb extends bb{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e){const t=this.light.iesMap;let s=null;if(t&&!0===t.isTexture){const i=e.acos().mul(1/Math.PI);s=Ul(t,xa(i,0),0).r}else s=super.getSpotAttenuation(e);return s}}class _b extends Ey{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class vb extends Ey{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Xf(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=bo(new Gs).setGroup(go)}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=vu.dot(i).mul(.5).add(.5),n=Hh(s,t,r);e.context.irradiance.addAssign(n)}}class Tb extends Ey{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new _t);this.lightProbe=Wl(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=Ry(Tu,this.lightProbe);e.context.irradiance.addAssign(t)}}class wb{parseFunction(){console.warn("Abstract function.")}}class Sb{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){console.warn("Abstract function.")}}Sb.isNodeFunction=!0;const Mb=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,Nb=/[a-z_0-9]+/gi,Eb="#pragma main";class Ab extends Sb{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(Eb),s=-1!==t?e.slice(t+12):e,i=s.match(Mb);if(null!==i&&5===i.length){const r=i[4],n=[];let a=null;for(;null!==(a=Nb.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 db(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 Cb extends wb{parseFunction(e){return new Ab(e)}}const Rb=new WeakMap,Pb=[],Fb=[];class Ib extends Ng{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new cb,this.nodeBuilderCache=new Map,this.callHashCache=new vg,this.groupsData=new vg,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===fo.name)return!0;if(s===go.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===mo.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}Pb[0]=t,Pb[1]=e;let i=this.groupsData.get(Pb);return void 0===i&&this.groupsData.set(Pb,i={}),Pb.length=0,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=this.backend.createNodeBuilder(e.object,this.renderer);t.scene=e.scene,t.material=e.material,t.camera=e.camera,t.context.material=e.material,t.lightsNode=e.lightsNode,t.environmentNode=this.getEnvironmentNode(e.scene),t.fogNode=this.getFogNode(e.scene),t.clippingContext=e.clippingContext,this.renderer.getRenderTarget()&&this.renderer.getRenderTarget().multiview&&t.enableMultiview(),t.build(),s=this._createNodeBuilderState(t),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 Ly(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){Pb[0]=e,Pb[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(Pb)||{};if(i.callId!==s){const r=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&Fb.push(t.getCacheKey(!0)),r&&Fb.push(r.getCacheKey()),n&&Fb.push(n.getCacheKey()),Fb.push(this.renderer.shadowMap.enabled?1:0),i.callId=s,i.cacheKey=Xr(Fb),this.callHashCache.set(Pb,i),Fb.length=0}return Pb.length=0,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||s.mapping===w||s.mapping===S||306===s.mapping){if(e.backgroundBlurriness>0||306===s.mapping)return Xm(s);{let e;return e=!0===s.isCubeTexture?ku(s):Ul(s),Zd(e)}}if(!0===s.isTexture)return Ul(s,fd.flipY()).setUpdateMatrix(!0);!0!==s.isColor&&console.error("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=Vu("color","color",s).setGroup(go),t=Vu("density","float",s).setGroup(go);return jf(e,Gf(t))}if(s.isFog){const e=Vu("color","color",s).setGroup(go),t=Vu("near","float",s).setGroup(go),i=Vu("far","float",s).setGroup(go);return jf(e,Vf(t,i))}console.error("THREE.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?ku(s):!0===s.isTexture?Ul(s):void console.error("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 Rb.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=e.isTextureArray?wf(e,wa(fd,$l("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):Ul(e,fd).renderOutput(t.toneMapping,t.currentColorSpace);return Rb.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 cb,this.nodeBuilderCache=new Map,this.cacheLib={}}}const Bb=new Qi;class Lb{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Ke,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++){Bb.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=Bb.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=Bb.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 gt;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 Lb(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class Db{constructor(e,t){this.bundleGroup=e,this.camera=t}}const Ob=[];class kb{constructor(){this.bundles=new vg}get(e,t){const s=this.bundles;Ob[0]=e,Ob[1]=t;let i=s.get(Ob);return void 0===i&&(i=new Db(e,t),s.set(Ob,i)),Ob.length=0,i}dispose(){this.bundles=new vg}}class Ub{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))console.warn(`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))console.warn(`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 zb=new Jf,Vb=[];class Gb extends vg{constructor(){super()}createNode(e=[]){return(new Jf).setLights(e)}getNode(e,t){if(e.isQuadMesh)return zb;Vb[0]=e,Vb[1]=t;let s=this.get(Vb);return void 0===s&&(s=this.createNode(),this.set(Vb,s)),Vb.length=0,s}}class jb extends ft{constructor(e=1,t=1,s={}){super(e,t,s),this.isXRRenderTarget=!0,this.hasExternalTextures=!1,this.autoAllocateDepthBuffer=!0}copy(e){return super.copy(e),this.hasExternalTextures=e.hasExternalTextures,this.autoAllocateDepthBuffer=e.autoAllocateDepthBuffer,this}}const Hb=new _t,Wb=new _t;class $b extends Oe{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Ii,this._cameraL.viewport=new gt,this._cameraR=new Ii,this._cameraR.viewport=new gt,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Vr,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._supportsLayers=!1,this._createXRLayer=Qb.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new Ye,this._onSessionEvent=Xb.bind(this),this._onSessionEnd=Yb.bind(this),this._onInputSourcesChange=Kb.bind(this),this._onAnimationFrame=Zb.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._useLayers="undefined"!=typeof XRWebGLBinding&&"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&&console.warn("THREE.XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&console.warn("THREE.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}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,s,i,r,n,a,h=[]){const l=new ur(e,t),c=new jb(r,n,{format:H,type:B,depthTexture:new or(r,n,h.stencil?G:U,void 0,void 0,void 0,void 0,void 0,void 0,h.stencil?$:W),stencilBuffer:h.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),d=new $s({color:16777215,side:0});d.map=c.texture,d.map.offset.y=1,d.map.repeat.y=-1;const p=new Si(l,d);p.position.copy(s),p.quaternion.copy(i);const m={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:r,pixelheight:n,plane:p,material:d,rendercall:a,renderTarget:c};if(this._layers.push(m),null!==this._session){m.plane.material=new $s({color:16777215,side:0}),m.plane.material.blending=5,m.plane.material.blendEquation=o,m.plane.material.blendSrc=u,m.plane.material.blendDst=u,m.xrlayer=this._createXRLayer(m);const e=this._session.renderState.layers;e.unshift(m.xrlayer),this._session.updateRenderState({layers:e})}else c.isXRRenderTarget=!1;return p}createCylinderLayer(e,t,s,i,r,n,a,h,l=[]){const c=new lr(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),d=new jb(n,a,{format:H,type:B,depthTexture:new or(n,a,l.stencil?G:U,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?$:W),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),p=new $s({color:16777215,side:1});p.map=d.texture,p.map.offset.y=1,p.map.repeat.y=-1;const m=new Si(c,p);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:p,rendercall:h,renderTarget:d};if(this._layers.push(g),null!==this._session){g.plane.material=new $s({color:16777215,side:1}),g.plane.material.blending=5,g.plane.material.blendEquation=o,g.plane.material.blendSrc=u,g.plane.material.blendDst=u,g.xrlayer=this._createXRLayer(g);const e=this._session.renderState.layers;e.unshift(g.xrlayer),this._session.updateRenderState({layers:e})}else d.isXRRenderTarget=!1;return m}renderLayers(){const e=new _t,t=new xt,s=this.isPresenting;this.isPresenting=!1;for(const s of this._layers){if(s.renderTarget.isXRRenderTarget=null!==this._session,s.renderTarget.hasExternalTextures=s.renderTarget.isXRRenderTarget,s.renderTarget.autoAllocateDepthBuffer=!s.renderTarget.isXRRenderTarget,s.renderTarget.isXRRenderTarget&&this._supportsLayers){s.xrlayer.transform=new XRRigidTransform(s.plane.getWorldPosition(e),s.plane.getWorldQuaternion(t));const i=this._glBinding.getSubImage(s.xrlayer,this._xrFrame);this._renderer.backend.setXRRenderTargetTextures(s.renderTarget,i.colorTexture,i.depthStencilTexture)}this._renderer.setRenderTarget(s.renderTarget),s.rendercall()}this.isPresenting=s,this._renderer.setRenderTarget(null)}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._useLayers){let s=null,n=null,a=null;t.depth&&(a=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,s=t.stencil?$:W,n=t.stencil?G:U);const h={colorFormat:i.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(h.textureType="texture-array",this._useMultiview=!0);const l=new XRWebGLBinding(e,i),c=l.createProjectionLayer(h),d=[c];let p;if(this._glBinding=l,this._glProjLayer=c,t.setPixelRatio(1),t.setSize(c.textureWidth,c.textureHeight,!1),this._useMultiview?(p=new hr(c.textureWidth,c.textureHeight,2),p.type=n,p.format=s):p=new or(c.textureWidth,c.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,s),this._xrRenderTarget=new jb(c.textureWidth,c.textureHeight,{format:H,type:B,colorSpace:t.outputColorSpace,depthTexture:p,stencilBuffer:t.stencil,samples:r.antialias?4:0,resolveDepthBuffer:!1===c.ignoreDepthValues,resolveStencilBuffer:!1===c.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget.hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._supportsLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._supportsLayers)for(const e of this._layers)e.plane.material=new $s({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=o,e.plane.material.blendSrc=u,e.plane.material.blendDst=u,e.xrlayer=this._createXRLayer(e),d.unshift(e.xrlayer);e.updateRenderState({layers:d})}else{const s={antialias:t.samples>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.setSize(r.framebufferWidth,r.framebufferHeight,!1),this._xrRenderTarget=new jb(r.framebufferWidth,r.framebufferHeight,{format:H,type:B,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===r.ignoreDepthValues,resolveStencilBuffer:!1===r.ignoreDepthValues}),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),n.layers.mask=2|e.layers.mask,a.layers.mask=4|e.layers.mask,r.layers.mask=n.layers.mask|a.layers.mask;const o=e.parent,h=r.cameras;qb(r,o);for(let e=0;e<h.length;e++)qb(h[e],o);2===h.length?function(e,t,s){Hb.setFromMatrixPosition(t.matrixWorld),Wb.setFromMatrixPosition(s.matrixWorld);const i=Hb.distanceTo(Wb),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*Ve*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 zi,this._controllers[e]=t),t}}function qb(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function Xb(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 Yb(){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.backend.setXRTarget(null),t.setOutputRenderTarget(null),t.setRenderTarget(null),this._session=null,this._xrRenderTarget=null,!0===this._supportsLayers)for(const e of this._layers)e.renderTarget=new jb(e.pixelwidth,e.pixelheight,{format:H,type:B,depthTexture:new or(e.pixelwidth,e.pixelheight,e.stencilBuffer?G:U,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?$:W),stencilBuffer:e.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,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 Kb(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 Qb(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),depthFormat:this._gl.DEPTH_COMPONENT,width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),depthFormat:this._gl.DEPTH_COMPONENT,radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight})}function Zb(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._useLayers){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 Ii,h.layers.enable(i),h.viewport=new gt,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}const Jb=new Vi,ex=new Ye,tx=new gt,sx=new er,ix=new ir,rx=new Kt,nx=new gt;class ax{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:r=!0,stencil:n=!1,antialias:a=!1,samples:o=0,getFallback:h=null,colorBufferType:l=V,multiview:u=!1}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=o||!0===a?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=_e,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=r,this.stencil=n,this.info=new Dg,this.overrideNodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new Ub,this.lighting=new Gb,this._getFallback=h,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new gt(0,0,this._width,this._height),this._scissor=new gt(0,0,this._width,this._height),this._scissorTest=!1,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 mf(new kd),this._quad.material.name="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const c=!0===this.alpha?0:1;this._clearColor=new af(0,0,0,c),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._colorBufferType=l,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr=new $b(this,u),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(e,t,this._renderTarget),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(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");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 Ib(this,s),this._animation=new _g(this._nodes,this.info),this._attributes=new Fg(s),this._background=new Fy(this,this._nodes),this._geometries=new Lg(this._attributes,this.info),this._textures=new nf(this,s,this.info),this._pipelines=new Gg(s,this._nodes),this._bindings=new jg(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Mg(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Yg(this.lighting),this._bundles=new kb,this._renderContexts=new sf,this._animation.start(),this._initialized=!0,e(this)}))),this._initPromise}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._compilationPromises,h=!0===e.isScene?e:Jb;null===s&&(s=e);const l=this._renderTarget,u=this._renderContexts.get(s,t,l),c=this._activeMipmapLevel,d=[];this._currentRenderContext=u,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),u.depth=this.depth,u.stencil=this.stencil,u.clippingContext||(u.clippingContext=new Lb),u.clippingContext.updateGlobal(h,t),h.onBeforeRender(this,e,t,l);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,u.clippingContext),s!==e&&s.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==l){this._textures.updateRenderTarget(l,c);const e=this._textures.get(l);u.textures=e.textures,u.depthTexture=e.depthTexture}else u.textures=null,u.depthTexture=null;this._background.update(h,p,u);const m=p.opaque,g=p.transparent,f=p.transparentDoublePass,y=p.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,h,y),!0===this.transparent&&g.length>0&&this._renderTransparents(g,f,t,h,y),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){!0===e?(this.overrideNodes.modelViewMatrix=ou,this.overrideNodes.modelNormalViewMatrix=hu):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===ou&&this.overrideNodes.modelNormalViewMatrix===hu}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(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 l=i.version!==h.version,u=!1===h.renderContexts.has(a)||l;if(h.renderContexts.add(a),u){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)return console.warn("THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead."),this.renderAsync(e,t);this._renderScene(e,t)}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this;if(!1===(0!==e)&&!1===(t!==ve))return null;const{width:s,height:i}=this.getDrawingBufferSize(ex),{depth:r,stencil:n}=this;let a=this._frameBufferTarget;null===a&&(a=new ft(s,i,{depthBuffer:r,stencilBuffer:n,type:this._colorBufferType,format:H,colorSpace:ve,generateMipmaps:!1,minFilter:P,magFilter:P,samples:this.samples}),a.isPostProcessingRenderTarget=!0,this._frameBufferTarget=a);const o=this.getOutputRenderTarget();return a.depthBuffer=r,a.stencilBuffer=n,a.setSize(s,i,null!==o?o.depth:1),a.viewport.copy(this._viewport),a.scissor.copy(this._scissor),a.viewport.multiplyScalar(this._pixelRatio),a.scissor.multiplyScalar(this._pixelRatio),a.scissorTest=this._scissorTest,a.multiview=null!==o&&o.multiview,a}_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=!0===e.isScene?e:Jb,l=this._renderTarget||this._outputRenderTarget,u=this._activeCubeFace,c=this._activeMipmapLevel;let d;null!==i?(d=i,this.setRenderTarget(d)):d=l;const p=this._renderContexts.get(e,t,d);this._currentRenderContext=p,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls;const m=this.coordinateSystem,g=this.xr;if(t.coordinateSystem!==m&&!1===g.isPresenting&&(t.coordinateSystem=m,t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.coordinateSystem=m,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());let f=this._viewport,y=this._scissor,b=this._pixelRatio;null!==d&&(f=d.viewport,y=d.scissor,b=1),this.getDrawingBufferSize(ex),tx.set(0,0,ex.width,ex.height);const x=void 0===f.minDepth?0:f.minDepth,_=void 0===f.maxDepth?1:f.maxDepth;p.viewportValue.copy(f).multiplyScalar(b).floor(),p.viewportValue.width>>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=x,p.viewportValue.maxDepth=_,p.viewport=!1===p.viewportValue.equals(tx),p.scissorValue.copy(y).multiplyScalar(b).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(tx),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new Lb),p.clippingContext.updateGlobal(h,t),h.onBeforeRender(this,e,t,d);const v=t.isArrayCamera?ix:sx;t.isArrayCamera||(rx.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(rx,m));const T=this._renderLists.get(e,t);if(T.begin(),this._projectObject(e,t,0,T,p.clippingContext),T.finish(),!0===this.sortObjects&&T.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,c);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=u,p.activeMipmapLevel=c,p.occlusionQueryCount=T.occlusionQueryCount,this._background.update(h,T,p),p.camera=t,this.backend.beginRender(p);const{bundles:w,lightsNode:S,transparentDoublePass:M,transparent:N,opaque:E}=T;return w.length>0&&this._renderBundles(w,h,S),!0===this.opaque&&E.length>0&&this._renderObjects(E,t,h,S),!0===this.transparent&&N.length>0&&this._renderTransparents(N,M,t,h,S),this.backend.finishRender(p),r.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==i&&(this.setRenderTarget(l,u,c),this._renderOutput(d)),h.onAfterRender(this,e,t,d),p}_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)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}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._initialized&&this.backend.updateSize())}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._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}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,this.backend.setScissorTest(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}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 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)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,s);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.getForClear(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,r.clearColorValue=this.backend.getClearColor(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){!1===this._initialized&&await this.init(),this.clear(e,t,s)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:ve}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.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}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,s=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,r=this._pipelines,n=this._bindings,a=this._nodes,o=Array.isArray(e)?e:[e];if(void 0===o[0]||!0!==o[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const t of o){if(!1===r.has(t)){const e=()=>{t.removeEventListener("dispose",e),r.delete(t),n.delete(t),a.delete(t)};t.addEventListener("dispose",e);const s=t.onInitFunction;null!==s&&s.call(t,{renderer:this})}a.updateForCompute(t),n.updateForCompute(t);const s=n.getForCompute(t),o=r.getForCompute(t,s);i.compute(e,t,s,o)}i.finishCompute(e),t.renderId=s}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=nx.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=nx.copy(t).floor()}else t=nx.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)}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)}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?ix:sx;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&nx.setFromMatrixPosition(e.matrixWorld).applyMatrix4(rx);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,nx.z,null,r)}}else if(e.isLineLoop)console.error("THREE.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?ix:sx;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),nx.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(rx)),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,nx.z,h,r)}}else n.visible&&i.push(e,t,n,s,nx.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)}}renderObject(e,t,s,i,r,n,a,o=null,h=null){let l,u,c;if(e.onBeforeRender(this,t,s,i,r,n),!0===r.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;r.positionNode&&r.positionNode.isNode&&(l=e.positionNode,e.positionNode=r.positionNode),e.alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.transparent=r.transparent||r.transmission>0,e.isShadowPassMaterial&&(e.side=null===r.shadowSide?r.side:r.shadowSide,r.depthNode&&r.depthNode.isNode&&(c=e.depthNode,e.depthNode=r.depthNode),r.castShadowNode&&r.castShadowNode.isNode&&(u=e.colorNode,e.colorNode=r.castShadowNode),r.castShadowPositionNode&&r.castShadowPositionNode.isNode&&(l=e.positionNode,e.positionNode=r.castShadowPositionNode)),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),void 0!==l&&(t.overrideMaterial.positionNode=l),void 0!==c&&(t.overrideMaterial.depthNode=c),void 0!==u&&(t.overrideMaterial.colorNode=u),e.onAfterRender(this,t,s,i,r,n)}_renderObjectDirect(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;const l=this._nodes.needsRefresh(h);if(l&&(this._nodes.updateBefore(h),this._geometries.updateForRender(h),this._nodes.updateForRender(h),this._bindings.updateForRender(h)),this._pipelines.updateForRender(h),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(h),h.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(h,this.info),l&&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)}get compile(){return this.compileAsync}}class ox{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class hx extends ox{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(Pg-e%Pg)%Pg;var e}get buffer(){return this._buffer}update(){return!0}}class lx extends hx{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let ux=0;class cx extends lx{constructor(e,t){super("UniformBuffer_"+ux++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class dx extends lx{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}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(){let e=0;for(let t=0,s=this.uniforms.length;t<s;t++){const s=this.uniforms[t],{boundary:i,itemSize:r}=s,n=e%Pg;0!==n&&Pg-n-i<0?e+=Pg-n:n%i!=0&&(e+=n%i),s.offset=e/this.bytesPerElement,e+=r*this.bytesPerElement}return Math.ceil(e/Pg)*Pg}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 console.error("THREE.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}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 e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,t=!0}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 e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,e[r+2]=s[r+2]=i.z,t=!0}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 e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,e[r+2]=s[r+2]=i.z,e[r+3]=s[r+3]=i.w,t=!0}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 e=this.buffer;e[r+0]=s[r+0]=i.r,e[r+1]=s[r+1]=i.g,e[r+2]=s[r+2]=i.b,t=!0}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 e=this.buffer;e[r+0]=s[r+0]=i[0],e[r+1]=s[r+1]=i[1],e[r+2]=s[r+2]=i[2],e[r+4]=s[r+4]=i[3],e[r+5]=s[r+5]=i[4],e[r+6]=s[r+6]=i[5],e[r+8]=s[r+8]=i[6],e[r+9]=s[r+9]=i[7],e[r+10]=s[r+10]=i[8],t=!0}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}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 px=0;class mx extends dx{constructor(e,t){super(e),this.id=px++,this.groupNode=t,this.isNodeUniformsGroup=!0}}let gx=0;class fx extends ox{constructor(e,t){super(e),this.id=gx++,this.texture=t,this.version=t?t.version:0,this.store=!1,this.generation=null,this.isSampledTexture=!0}needsBindingsUpdate(e){const{texture:t}=this;return e!==this.generation?(this.generation=e,!0):t.isVideoTexture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}}class yx extends fx{constructor(e,t,s,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s,this.access=i}needsBindingsUpdate(e){return this.textureNode.value!==this.texture||super.needsBindingsUpdate(e)}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class bx extends yx{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class xx extends yx{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const _x={textureDimensions:"textureSize",equals:"equal"},vx={low:"lowp",medium:"mediump",high:"highp"},Tx={swizzleAssign:!0,storageBuffer:!1},wx={perspective:"smooth",linear:"noperspective"},Sx={centroid:"centroid","flat first":"flat","flat either":"flat"},Mx="\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 lowp sampler2DShadow;\nprecision lowp sampler2DArrayShadow;\nprecision lowp samplerCubeShadow;\n";class Nx extends ub{constructor(e,t){super(e,t,new Cb),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==xe}getMethod(e){return _x[e]||e}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?X:q;2===i?n=r?K:Y:3===i?n=r?1032:j:4===i&&(n=r?Q:H);const a={Float32Array:z,Uint8Array:B,Uint16Array:O,Uint32Array:U,Int8Array:L,Int16Array:D,Int32Array:k,Uint8ClampedArray:B},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 $i(t.array,o,h,n,a[t.array.constructor.name]||z);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.label)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?t.charAt(0)+"_"+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.label),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="."+mn.join("").slice(0,u),d=`ivec2(${a} % ${l}, ${a} / ${l})`,p=this.generateTextureLoad(null,n,d,null,"0");let m="vec4";i.pbo.type===U?m="uvec4":i.pbo.type===k&&(m="ivec4"),this.addLineFlowCode(`${h} = ${m}(${p})${c}`,e),o.propertyName=h}return h}generateTextureLoad(e,t,s,i,r="0"){return i?`texelFetch( ${t}, ivec3( ${s}, ${i} ), ${r} )`:`texelFetch( ${t}, ${s}, ${r} )`}generateTexture(e,t,s,i){return e.isDepthTexture?(i&&(s=`vec4( ${s}, ${i} )`),`texture( ${t}, ${s} ).x`):(i&&(s=`vec3( ${s}, ${i} )`),`texture( ${t}, ${s} )`)}generateTextureLevel(e,t,s,i){return`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i){return`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i){return`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return r?`texture( ${t}, vec4( ${s}, ${r}, ${i} ) )`:`texture( ${t}, vec3( ${s}, ${i} ) )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} 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 r of t){let t=null,n=!1;if("texture"===r.type||"texture3D"===r.type){const e=r.node.value;let s="";!0!==e.isDataTexture&&!0!==e.isData3DTexture||(e.type===U?s="u":e.type===k&&(s="i")),t="texture3D"===r.type&&!1===e.isTextureArray?`${s}sampler3D ${r.name};`:e.compareFunction?!0===e.isDepthArrayTexture?`sampler2DArrayShadow ${r.name};`:`sampler2DShadow ${r.name};`:!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture||!0===e.isTextureArray?`${s}sampler2DArray ${r.name};`:`${s}sampler2D ${r.name};`}else if("cubeTexture"===r.type)t=`samplerCube ${r.name};`;else if("buffer"===r.type){const e=r.node,s=this.getType(e.bufferType),i=e.bufferCount,n=i>0?i:"";t=`${e.name} {\n\t${s} ${r.name}[${n}];\n};\n`}else{t=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,n=!0}const a=r.node.precision;if(null!==a&&(t=vx[a]+" "+t),n){t="\t"+t;const e=r.groupNode.name;(i[e]||(i[e]=[])).push(t)}else t="uniform "+t,s.push(t)}let r="";for(const t in i){const s=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,s.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==k){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+=`${wx[i.interpolationType]||i.interpolationType} ${Sx[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+=`${wx[e.interpolationType]||e.interpolationType} ${Sx[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`}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=Tx[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)}Tx[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${Mx}\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${Mx}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\n// structs\n${e.structs}\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 yx(r.name,r.node,i),h.push(a);else if("cubeTexture"===t)a=new bx(r.name,r.node,i),h.push(a);else if("texture3D"===t)a=new xx(r.name,r.node,i),h.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,r.name=`buffer${e.id}`;const t=new cx(e,i);t.name=e.name,h.push(t),a=t}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[o];void 0===n&&(n=new mx(s+"_"+o,i),e[o]=n,h.push(n)),a=this.getNodeUniform(r,t),n.addUniform(a)}n.uniformGPU=a}return r}}let Ex=null,Ax=null;class Cx{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute: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(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void tt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void tt(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const s=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=s,s}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return Ex=Ex||new Ye,this.renderer.getDrawingBufferSize(Ex)}setScissorTest(){}getClearColor(){const e=this.renderer;return Ax=Ax||new af,e.getClearColor(Ax),Ax.getRGB(Ax),Ax}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=Je("canvas");return e.style.display="block",e}(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${a} webgpu`),this.domElement=e),e}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)}dispose(){}}let Rx,Px,Fx=0;class Ix{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 Bx{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(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===k,id:Fx++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);u=new Ix(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){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 Lx{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.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;Rx={[o]:e.FUNC_ADD,[h]:e.FUNC_SUBTRACT,[l]:e.FUNC_REVERSE_SUBTRACT},Px={[u]:e.ZERO,[c]:e.ONE,[d]:e.SRC_COLOR,[m]:e.SRC_ALPHA,[_]:e.SRC_ALPHA_SATURATE,[b]:e.DST_COLOR,[f]:e.DST_ALPHA,[p]:e.ONE_MINUS_SRC_COLOR,[g]:e.ONE_MINUS_SRC_ALPHA,[x]:e.ONE_MINUS_DST_COLOR,[y]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=(new gt).fromArray(t),this.currentViewport=(new gt).fromArray(s),this._tempVec4=new gt}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)}setBlending(e,t,s,i,r,n,a,h){const{gl:l}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,n=n||s,a=a||i,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(l.blendEquationSeparate(Rx[t],Rx[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(l.blendFuncSeparate(Px[s],Px[i],Px[n],Px[a]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=n,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||h!==this.currentPremultipledAlpha){if(this.currentBlendEquation===o&&this.currentBlendEquationAlpha===o||(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=o,this.currentBlendEquationAlpha=o),h)switch(e){case 1:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFunc(l.ONE,l.ONE);break;case 3:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case 4:l.blendFuncSeparate(l.ZERO,l.SRC_COLOR,l.ZERO,l.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}else switch(e){case 1:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFunc(l.SRC_ALPHA,l.ONE);break;case 3:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case 4:l.blendFunc(l.ZERO,l.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=h}}else!0===this.currentBlendingEnabled&&(this.disable(l.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)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(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?t.enable(t.SCISSOR_TEST):t.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.samples>1?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 Dx{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;if(e===B)return s.UNSIGNED_BYTE;if(1017===e)return s.UNSIGNED_SHORT_4_4_4_4;if(1018===e)return s.UNSIGNED_SHORT_5_5_5_1;if(35902===e)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===L)return s.BYTE;if(e===D)return s.SHORT;if(e===O)return s.UNSIGNED_SHORT;if(e===k)return s.INT;if(e===U)return s.UNSIGNED_INT;if(e===z)return s.FLOAT;if(e===V)return s.HALF_FLOAT;if(1021===e)return s.ALPHA;if(e===j)return s.RGB;if(e===H)return s.RGBA;if(e===W)return s.DEPTH_COMPONENT;if(e===$)return s.DEPTH_STENCIL;if(e===q)return s.RED;if(e===X)return s.RED_INTEGER;if(e===Y)return s.RG;if(e===K)return s.RG_INTEGER;if(e===Q)return s.RGBA_INTEGER;if(e===Z||e===J||e===ee||e===te)if(t===_e){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===Z)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===J)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===ee)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===te)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===Z)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===J)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===ee)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===te)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===e||35841===e||35842===e||35843===e){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(35840===e)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===e)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===e)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===e)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===e||e===se||e===ie){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(36196===e||e===se)return t===_e?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===ie)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}if(e===re||e===ne||e===ae||e===oe||e===he||e===le||e===ue||e===ce||e===de||e===pe||e===me||e===ge||e===fe||e===ye){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===re)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===ne)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===ae)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===oe)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===he)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===le)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===ue)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===ce)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===de)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===pe)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===me)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===ge)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===fe)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===ye)return t===_e?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===be){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===be)return t===_e?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(36283===e||36284===e||36285===e||36286===e){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===be)return r.COMPRESSED_RED_RGTC1_EXT;if(36284===e)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(36285===e)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(36286===e)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===G?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 Ox,kx,Ux,zx=!1;class Vx{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===zx&&(this._init(),zx=!0)}_init(){const e=this.gl;Ox={[M]:e.REPEAT,[N]:e.CLAMP_TO_EDGE,[E]:e.MIRRORED_REPEAT},kx={[A]:e.NEAREST,[C]:e.NEAREST_MIPMAP_NEAREST,[R]:e.NEAREST_MIPMAP_LINEAR,[P]:e.LINEAR,[F]:e.LINEAR_MIPMAP_NEAREST,[I]:e.LINEAR_MIPMAP_LINEAR},Ux={[Me]:e.NEVER,[Fe]:e.ALWAYS,[Ne]:e.LESS,[Ae]:e.LEQUAL,[Ee]:e.EQUAL,[Pe]:e.GEQUAL,[Ce]:e.GREATER,[Re]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDepthArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture||!0===e.isTextureArray?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];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;return 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&&(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=i===_e&&!1===r?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)),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&&(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=i===_e&&!1===r?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)),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;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,s.NONE),s.texParameteri(e,s.TEXTURE_WRAP_S,Ox[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,Ox[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||!0!==t.isDepthArrayTexture&&!1===t.isTextureArray&&s.texParameteri(e,s.TEXTURE_WRAP_R,Ox[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,kx[t.magFilter]);const n=void 0!==t.mipmaps&&t.mipmaps.length>0,a=t.minFilter===P&&n?I:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,kx[a]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,Ux[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===A)return;if(t.minFilter!==R&&t.minFilter!==I)return;if(t.type===z&&!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,isDefault:!0})}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.colorSpace,e.isVideoTexture),c=s.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,c),this.setTextureParameters(d,e),e.isDepthArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture||e.isTextureArray?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,{textureGPU:r,glTextureType:n,glFormat:a,glType:o}=i.get(t),{width:h,height:l}=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,l,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:l}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===n)return;const u=e=>e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||e instanceof OffscreenCanvas?e:e.data;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):console.warn("THREE.WebGLRenderer: 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):console.warn("Unsupported compressed texture format")}}else if(e.isCubeTexture){const e=t.images;for(let t=0;t<6;t++){const n=u(e[t]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,i,r,o,h,n)}}else if(e.isDataArrayTexture||e.isDepthArrayTexture){const e=t.image;s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,e.width,e.height,e.depth,o,h,e.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{const e=u(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){const{gl:t,backend:s}=this,{textureGPU:i,renderTarget:r}=s.get(e);this.deallocateRenderBuffers(r),t.deleteTexture(i),s.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.isDepthArrayTexture?T.depth:e.isData3DTexture?Math.floor(T.depth*t):1,f=0,y=0,b=0}null!==i?(x=i.x,_=i.y,v=i.z):(x=0,_=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 w=a.getParameter(a.UNPACK_ROW_LENGTH),S=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=t.isDataArrayTexture||t.isData3DTexture||t.isDepthArrayTexture;if(e.isRenderTargetTexture||e.isDepthTexture){const s=o.get(e),i=o.get(t),r=o.get(s.renderTarget),n=o.get(i.renderTarget),l=r.framebuffers[s.cacheKey],u=n.framebuffers[i.cacheKey];h.bindFramebuffer(a.READ_FRAMEBUFFER,l),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,u);let c=a.COLOR_BUFFER_BIT;e.isDepthTexture&&(c=a.DEPTH_BUFFER_BIT),a.blitFramebuffer(f,y,p,m,x,_,p,m,c,a.NEAREST),h.bindFramebuffer(a.READ_FRAMEBUFFER,null),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else A?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(u,n,x,_,p,m,d,c,T.data):e.isCompressedTexture?a.compressedTexSubImage2D(u,n,x,_,T.width,T.height,d,T.data):a.texSubImage2D(u,n,x,_,p,m,d,c,T);a.pixelStorei(a.UNPACK_ROW_LENGTH,w),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,S),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(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))}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();o.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),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}}class Gx{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 jx{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 Hx={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",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class Wx{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 $x{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.pendingResolve=!1}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class qx extends $x{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 console.warn("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 tt(`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.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);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){console.error("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.id);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){console.error("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=[];for(const[t,s]of this.queryStates)if("ended"===s){const s=this.queries[t];e.push(this.resolveQuery(s))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce(((e,t)=>e+t),0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("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){console.error("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 Xx extends Cx{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.samples>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 Gx(this),this.capabilities=new jx(this),this.attributeUtils=new Bx(this),this.textureUtils=new Vx(this),this.bufferRenderer=new Wx(this),this.state=new Lx(this),this.utils=new Dx(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.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return Le}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}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&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e.autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new qx(this.gl,t,2048));const s=this.timestampQueryPool[t];null!==s.allocateQueriesForContext(e)&&s.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t,gl:s}=this,i=this.get(e);if(e.viewport?this.updateViewport(e):t.viewport(0,0,s.drawingBufferWidth,s.drawingBufferHeight),e.scissor){const{x:s,y:i,width:r,height:n}=e.scissorValue;t.scissor(s,e.height-n-i,r,n)}this.initTimestampQuery(e),i.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const r=e.occlusionQueryCount;r>0&&(i.currentOcclusionQueries=i.occlusionQueries,i.currentOcclusionQueryObjects=i.occlusionQueryObjects,i.lastOcclusionObject=null,i.occlusionQueries=new Array(r),i.occlusionQueryObjects=new Array(r),i.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,null!==e.textures&&e.renderTarget){const i=this.get(e.renderTarget),{samples:r}=e.renderTarget;if(r>0&&!1===this._useMultisampledExtension(e.renderTarget)){const r=i.framebuffers[e.getCacheKey()],n=t.COLOR_BUFFER_BIT,a=i.msaaFrameBuffer,o=e.textures;s.bindFramebuffer(t.READ_FRAMEBUFFER,a),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,r);for(let s=0;s<o.length;s++)if(e.scissor){const{x:s,y:r,width:a,height:o}=e.scissorValue,h=e.height-o-r;t.blitFramebuffer(s,h,s+a,h+o,s,h,s+a,h+o,n,t.NEAREST),!0===this._supportsInvalidateFramebuffer&&t.invalidateSubFramebuffer(t.READ_FRAMEBUFFER,i.invalidationArray,s,h,a,o)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,n,t.NEAREST),!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,i.invalidationArray)}}null!==r&&(this._setFramebuffer(r),r.viewport?this.updateViewport(r):s.viewport(0,0,t.drawingBufferWidth,t.drawingBufferHeight)),this.prepareTimestampBuffer(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)}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){const{gl:n,renderer:a}=this;if(null===i){i={textures:null,clearColorValue:this.getClearColor()}}let o=0;if(e&&(o|=n.COLOR_BUFFER_BIT),t&&(o|=n.DEPTH_BUFFER_BIT),s&&(o|=n.STENCIL_BUFFER_BIT),0!==o){let h;h=i.clearColorValue?i.clearColorValue:this.getClearColor();const l=a.getClearDepth(),u=a.getClearStencil();if(t&&this.state.setDepthMask(!0),null===i.textures)n.clearColor(h.r,h.g,h.b,h.a),n.clear(o);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++)0===e?n.clearBufferfv(n.COLOR,e,[h.r,h.g,h.b,h.a]):n.clearBufferfv(n.COLOR,e,[0,0,0,1]);t&&s?n.clearBufferfi(n.DEPTH_STENCIL,0,l,u):t?n.clearBufferfv(n.DEPTH,0,[l]):s&&n.clearBufferiv(n.STENCIL,0,[u])}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(e)}compute(e,t,s,i){const{state:r,gl:n}=this;!1===this.discard&&(n.enable(n.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:a,transformBuffers:o,attributes:h}=this.get(i),l=this._getVaoKey(h),u=this.vaoCache[l];void 0===u?this._createVao(h):r.setVertexState(u),r.useProgram(a),this._bindUniforms(s);const c=this._getTransformFeedback(o);n.bindTransformFeedback(n.TRANSFORM_FEEDBACK,c),n.beginTransformFeedback(n.POINTS),h[0].isStorageInstancedBufferAttribute?n.drawArraysInstanced(n.POINTS,0,1,t.count):n.drawArrays(n.POINTS,0,t.count),n.endTransformFeedback(),n.bindTransformFeedback(n.TRANSFORM_FEEDBACK,null);for(let e=0;e<o.length;e++){const t=o[e];t.pbo&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const t=this.gl;this.discard=!1,t.disable(t.RASTERIZER_DISCARD),this.prepareTimestampBuffer(e),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isDepthArrayTexture&&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,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),h.useProgram(a);const d=this.get(e);let p=d.staticVao;if(void 0===p||d.geometryId!==e.geometry.id){const t=this._getVaoKey(e.getAttributes());if(p=this.vaoCache[t],void 0===p){let t;({vaoGPU:p,staticVao:t}=this._createVao(e.getAttributes())),t&&(d.staticVao=p,d.geometryId=e.geometry.id)}}const m=e.getIndex(),g=null!==m?this.get(m).bufferGPU:null;h.setVertexState(p,g);const f=l.lastOcclusionObject;if(f!==t&&void 0!==f){if(null!==f&&!0===f.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 y=this.bufferRenderer;t.isPoints?y.mode=o.POINTS:t.isLineSegments?y.mode=o.LINES:t.isLine?y.mode=o.LINE_STRIP:t.isLineLoop?y.mode=o.LINE_LOOP:!0===i.wireframe?(h.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),y.mode=o.LINES):y.mode=o.TRIANGLES;const{vertexCount:b,instanceCount:x}=u;let{firstVertex:_}=u;if(y.object=t,null!==m){_*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);y.index=m.count,y.type=e.type}else y.index=0;const v=()=>{t.isBatchedMesh?null!==t._multiDrawInstances?(tt("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),y.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?y.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):tt("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):x>1?y.renderInstances(_,b,x):y.render(_,b)};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(),l=this._currentContext.renderTarget,u=this._isRenderCameraDepthArray(this._currentContext),c=this._currentContext.activeCubeFace;if(u){const e=this.get(l.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=l;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);this.renderer._activeCubeFace=c,this._currentContext.activeCubeFace=c}}for(let r=0,l=i.length;r<l;r++){const l=i[r];if(t.layers.test(l.layers)){u&&(this.renderer._activeCubeFace=r,this._currentContext.activeCubeFace=r,this._setFramebuffer(this._currentContext));const t=l.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]),v()}this._currentContext.activeCubeFace=c,this.renderer._activeCubeFace=c}}else v()}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){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new Nx(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()}));t.push(r)}else 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");console.error("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&&console.warn("THREE.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,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,s=this.get(e);let i=s.uniformBuffers,r=s.textures;for(const s of e.bindings)if(s.isUniformsGroup||s.isUniformBuffer){const e=s.buffer,r=t.createBuffer();t.bindBuffer(t.UNIFORM_BUFFER,r),t.bufferData(t.UNIFORM_BUFFER,e,t.DYNAMIC_DRAW),this.set(s,{index:i++,bufferGPU:r})}else if(s.isSampledTexture){const{textureGPU:e,glTextureType:t}=this.get(s.texture);this.set(s,{index:r++,textureGPU:e,glTextureType:t})}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const s=this.get(e).bufferGPU,i=e.buffer;t.bindBuffer(t.UNIFORM_BUFFER,s),t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW)}}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(Hx).filter((t=>Hx[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)}_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.isWebGLCubeRenderTarget,u=!0===r.isRenderTarget3D,c=!0===r.isRenderTargetArray,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),x=Zg(e);let _;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),_=n.cubeFramebuffers[x]):d&&!1===p?_=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),_=n.framebuffers[x]),void 0===_){_=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,_);const i=e.textures;if(l){n.cubeFramebuffers[x]=_;const{textureGPU:e}=this.get(i[0]),s=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+s,e,0)}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=x;const h=t.COLOR_ATTACHMENT0+s;if(u||c){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,h,o.textureGPU,0,e)}else r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,h,o.textureGPU,0,a,0,2):p&&b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,h,t.TEXTURE_2D,o.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,h,t.TEXTURE_2D,o.textureGPU,0)}s.drawBuffers(e,_)}if(r.isXRRenderTarget&&!0===r.autoAllocateDepthBuffer){const s=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(s,e,0,b),n.xrDepthRenderbuffer=s}else if(null!==e.depthTexture){const s=this.get(e.depthTexture),i=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(s.renderTarget=e.renderTarget,s.cacheKey=x,r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,i,s.textureGPU,0,a,0,2);else if(p&&b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,i,t.TEXTURE_2D,s.textureGPU,0,a);else if(e.depthTexture.isDepthArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,i,s.textureGPU,0,e)}else t.framebufferTexture2D(t.FRAMEBUFFER,i,t.TEXTURE_2D,s.textureGPU,0)}}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,_);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&&p||r.multiview){s.bindFramebuffer(t.FRAMEBUFFER,_);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++){if(r[s]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,r[s]),i.push(t.COLOR_ATTACHMENT0+s),o){const e=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;i.push(e)}const n=e.textures[s],l=this.get(n);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,l.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+s,t.RENDERBUFFER,r[s])}if(n.msaaFrameBuffer=m,n.msaaRenderbuffers=r,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=_}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();let i="",r=!0;t.bindVertexArray(s);for(let s=0;s<e.length;s++){const n=e[s],a=this.get(n);let o,h;i+=":"+a.id,t.bindBuffer(t.ARRAY_BUFFER,a.bufferGPU),t.enableVertexAttribArray(s),(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&(r=!1),!0===n.isInterleavedBufferAttribute?(o=n.data.stride*a.bytesPerElement,h=n.offset*a.bytesPerElement):(o=0,h=0),a.isInteger?t.vertexAttribIPointer(s,n.itemSize,a.type,o,h):t.vertexAttribPointer(s,n.itemSize,a.type,n.normalized,o,h),n.isInstancedBufferAttribute&&!n.isInterleavedBufferAttribute?t.vertexAttribDivisor(s,n.meshPerAttribute):n.isInterleavedBufferAttribute&&n.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(s,n.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),this.vaoCache[i]=s,{vaoGPU:s,staticVao:r}}_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)}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e.autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const Yx="point-list",Kx="line-list",Qx="line-strip",Zx="triangle-list",Jx="triangle-strip",e_="never",t_="less",s_="equal",i_="less-equal",r_="greater",n_="not-equal",a_="greater-equal",o_="always",h_="store",l_="load",u_="clear",c_="ccw",d_="none",p_="front",m_="back",g_="uint16",f_="uint32",y_="r8unorm",b_="r8snorm",x_="r8uint",__="r8sint",v_="r16uint",T_="r16sint",w_="r16float",S_="rg8unorm",M_="rg8snorm",N_="rg8uint",E_="rg8sint",A_="r32uint",C_="r32sint",R_="r32float",P_="rg16uint",F_="rg16sint",I_="rg16float",B_="rgba8unorm",L_="rgba8unorm-srgb",D_="rgba8snorm",O_="rgba8uint",k_="rgba8sint",U_="bgra8unorm",z_="bgra8unorm-srgb",V_="rgb9e5ufloat",G_="rgb10a2unorm",j_="rgb10a2unorm",H_="rg32uint",W_="rg32sint",$_="rg32float",q_="rgba16uint",X_="rgba16sint",Y_="rgba16float",K_="rgba32uint",Q_="rgba32sint",Z_="rgba32float",J_="depth16unorm",ev="depth24plus",tv="depth24plus-stencil8",sv="depth32float",iv="depth32float-stencil8",rv="bc1-rgba-unorm",nv="bc1-rgba-unorm-srgb",av="bc2-rgba-unorm",ov="bc2-rgba-unorm-srgb",hv="bc3-rgba-unorm",lv="bc3-rgba-unorm-srgb",uv="bc4-r-unorm",cv="bc4-r-snorm",dv="bc5-rg-unorm",pv="bc5-rg-snorm",mv="bc6h-rgb-ufloat",gv="bc6h-rgb-float",fv="bc7-rgba-unorm",yv="bc7-rgba-srgb",bv="etc2-rgb8unorm",xv="etc2-rgb8unorm-srgb",_v="etc2-rgb8a1unorm",vv="etc2-rgb8a1unorm-srgb",Tv="etc2-rgba8unorm",wv="etc2-rgba8unorm-srgb",Sv="eac-r11unorm",Mv="eac-r11snorm",Nv="eac-rg11unorm",Ev="eac-rg11snorm",Av="astc-4x4-unorm",Cv="astc-4x4-unorm-srgb",Rv="astc-5x4-unorm",Pv="astc-5x4-unorm-srgb",Fv="astc-5x5-unorm",Iv="astc-5x5-unorm-srgb",Bv="astc-6x5-unorm",Lv="astc-6x5-unorm-srgb",Dv="astc-6x6-unorm",Ov="astc-6x6-unorm-srgb",kv="astc-8x5-unorm",Uv="astc-8x5-unorm-srgb",zv="astc-8x6-unorm",Vv="astc-8x6-unorm-srgb",Gv="astc-8x8-unorm",jv="astc-8x8-unorm-srgb",Hv="astc-10x5-unorm",Wv="astc-10x5-unorm-srgb",$v="astc-10x6-unorm",qv="astc-10x6-unorm-srgb",Xv="astc-10x8-unorm",Yv="astc-10x8-unorm-srgb",Kv="astc-10x10-unorm",Qv="astc-10x10-unorm-srgb",Zv="astc-12x10-unorm",Jv="astc-12x10-unorm-srgb",eT="astc-12x12-unorm",tT="astc-12x12-unorm-srgb",sT="clamp-to-edge",iT="repeat",rT="mirror-repeat",nT="linear",aT="nearest",oT="zero",hT="one",lT="src",uT="one-minus-src",cT="src-alpha",dT="one-minus-src-alpha",pT="dst",mT="one-minus-dst",gT="dst-alpha",fT="one-minus-dst-alpha",yT="src-alpha-saturated",bT="constant",xT="one-minus-constant",_T="add",vT="subtract",TT="reverse-subtract",wT="min",ST="max",MT=0,NT=15,ET="keep",AT="zero",CT="replace",RT="invert",PT="increment-clamp",FT="decrement-clamp",IT="increment-wrap",BT="decrement-wrap",LT="storage",DT="read-only-storage",OT="write-only",kT="read-only",UT="read-write",zT="non-filtering",VT="comparison",GT="float",jT="unfilterable-float",HT="depth",WT="sint",$T="uint",qT="2d",XT="3d",YT="2d",KT="2d-array",QT="cube",ZT="3d",JT="all",ew="vertex",tw="instance",sw={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class iw extends ox{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class rw extends iw{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){this.texture=this.textureNode.value}}class nw extends hx{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let aw=0;class ow extends nw{constructor(e,t){super("StorageBuffer_"+aw++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:cn,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class hw extends Ng{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:nT}),this.flipYSampler=e.createSampler({minFilter:aT}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4<f32>,\n\t@location( 0 ) vTex : vec2<f32>\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( -1.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 ),\n\t\tvec2<f32>( -1.0, -1.0 ),\n\t\tvec2<f32>( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( 0.0, 0.0 ),\n\t\tvec2<f32>( 1.0, 0.0 ),\n\t\tvec2<f32>( 0.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:Jx,stripIndexFormat:f_},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:Jx,stripIndexFormat:f_},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,a=this.getTransferPipeline(i),o=this.getFlipYPipeline(i),h=this.device.createTexture({size:{width:r,height:n,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:YT,baseArrayLayer:s}),u=h.createView({baseMipLevel:0,mipLevelCount:1,dimension:YT,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),d=(e,t,s)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:s,loadOp:u_,storeOp:h_,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,r),n.draw(4,1,0,0),n.end()};d(a,l,u),d(o,u,l),this.device.queue.submit([c.finish()]),h.destroy()}generateMipmaps(e,t,s=0){const i=this.get(e);void 0===i.useCount&&(i.useCount=0,i.layers=[]);const r=i.layers[s]||this._mipmapCreateBundles(e,t,s),n=this.device.createCommandEncoder({});this._mipmapRunBundles(n,r),this.device.queue.submit([n.finish()]),0!==i.useCount&&(i.layers[s]=r),i.useCount++}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),r=i.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:YT,baseArrayLayer:s});const a=[];for(let o=1;o<t.mipLevelCount;o++){const h=this.device.createBindGroup({layout:r,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:n}]}),l=e.createView({baseMipLevel:o,mipLevelCount:1,dimension:YT,baseArrayLayer:s}),u={colorAttachments:[{view:l,loadOp:u_,storeOp:h_,clearValue:[0,0,0,0]}]},c=this.device.createRenderBundleEncoder({colorFormats:[t.format]});c.setPipeline(i),c.setBindGroup(0,h),c.draw(4,1,0,0),a.push({renderBundles:[c.finish()],passDescriptor:u}),n=l}return a}_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 lw={[Me]:"never",[Ne]:"less",[Ee]:"equal",[Ae]:"less-equal",[Ce]:"greater",[Pe]:"greater-equal",[Fe]:"always",[Re]:"not-equal"},uw=[0,1,3,2,4,5];class cw{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this.colorBuffer=null,this.depthTexture=new or,this.depthTexture.name="depthBuffer"}createSampler(e){const t=this.backend,s=t.device,i=t.get(e),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};r.magFilter===nT&&r.minFilter===nT&&r.mipmapFilter===nT&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&(r.compare=lw[e.compareFunction]),i.sampler=s.createSampler(r)}createDefaultTexture(e){let t;const s=dw(e);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(s):e.isVideoTexture?this.backend.get(e).externalTexture=this._getDefaultVideoFrame():t=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.");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||dw(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&&(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(e.isVideoTexture){const t=e.source.data,s=new VideoFrame(t);m.size.width=s.displayWidth,m.size.height=s.displayHeight,s.close(),i.externalTexture=t}else{if(void 0===l)return console.warn("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(m.textureBindingViewDimension=QT),i.texture=s.device.createTexture(m)}if(d){const e=Object.assign({},m);e.label=e.label+"-msaa",e.sampleCount=u,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e){const t=this.backend,s=t.get(e);void 0!==s.texture&&s.texture.destroy(),void 0!==s.msaaTexture&&s.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else{const s=e.image.depth||1;for(let e=0;e<s;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e)}}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:s}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:s,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.samples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!1){const s=this.backend,{width:i,height:r}=s.getDrawingBufferSize(),n=this.depthTexture,a=s.get(n).texture;let o,h;if(t?(o=$,h=G):e&&(o=W,h=U),void 0!==a){if(n.image.width===i&&n.image.height===r&&n.format===o&&n.type===h)return a;this.destroyTexture(n)}return n.name="depthBuffer",n.format=o,n.type=h,n.image.width=i,n.image.height=r,this.createTexture(n,{width:i,height:r}),s.get(n).texture}updateTexture(e,t){const s=this.backend.get(e),{textureDescriptorGPU:i}=s;if(!e.isRenderTargetTexture&&void 0!==i){if(e.isDataTexture)this._copyBufferToTexture(t.image,s.texture,i,0,e.flipY);else if(e.isDataArrayTexture||e.isDepthArrayTexture||e.isData3DTexture)for(let r=0;r<t.image.depth;r++)this._copyBufferToTexture(t.image,s.texture,i,r,e.flipY,r);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,s.texture,i);else if(e.isCubeTexture)this._copyCubeMapToTexture(t.images,s.texture,i,e.flipY);else if(e.isVideoTexture){const t=e.source.data;s.externalTexture=t}else this._copyImageToTexture(t.image,s.texture,i,0,e.flipY);s.version=e.version,e.onUpdate&&e.onUpdate(e)}}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:i*r*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);return new m(d.getMappedRange())}_isEnvironmentTexture(e){const t=e.mapping;return t===w||t===S||t===v||t===T}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const s=new mt;s.minFilter=A,s.magFilter=A,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.defaultTexture[e];if(void 0===t){const s=new Di;s.minFilter=A,s.magFilter=A,this.createTexture(s,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultVideoFrame(){let e=this.defaultVideoFrame;if(null===e){const t={timestamp:0,codedWidth:1,codedHeight:1,format:"RGBA"};this.defaultVideoFrame=e=new VideoFrame(new Uint8Array([0,0,0,255]),t)}return e}_copyCubeMapToTexture(e,t,s,i){for(let r=0;r<6;r++){const n=e[r],a=!0===i?uw[r]:r;n.isDataTexture?this._copyBufferToTexture(n.image,t,s,a,i):this._copyImageToTexture(n,t,s,a,i)}}_copyImageToTexture(e,t,s,i,r){this.backend.device.queue.copyExternalImageToTexture({source:e,flipY:r},{texture:t,mipLevel:0,origin:{x:0,y:0,z:i}},{width:e.width,height:e.height,depthOrArrayLayers:1})}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new hw(this.backend.device)),e}_generateMipmaps(e,t,s=0){this._getPassUtils().generateMipmaps(e,t,s)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,r,n=0){const a=this.backend.device,o=e.data,h=this._getBytesPerTexel(s.format),l=e.width*h;a.queue.writeTexture({texture:t,mipLevel:0,origin:{x:0,y:0,z:i}},o,{offset:e.width*e.height*h*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,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===rv||e===nv?{byteLength:8,width:4,height:4}:e===av||e===ov||e===hv||e===lv?{byteLength:16,width:4,height:4}:e===uv||e===cv?{byteLength:8,width:4,height:4}:e===dv||e===pv||e===mv||e===gv||e===fv||e===yv?{byteLength:16,width:4,height:4}:e===bv||e===xv||e===_v||e===vv?{byteLength:8,width:4,height:4}:e===Tv||e===wv?{byteLength:16,width:4,height:4}:e===Sv||e===Mv?{byteLength:8,width:4,height:4}:e===Nv||e===Ev||e===Av||e===Cv?{byteLength:16,width:4,height:4}:e===Rv||e===Pv?{byteLength:16,width:5,height:4}:e===Fv||e===Iv?{byteLength:16,width:5,height:5}:e===Bv||e===Lv?{byteLength:16,width:6,height:5}:e===Dv||e===Ov?{byteLength:16,width:6,height:6}:e===kv||e===Uv?{byteLength:16,width:8,height:5}:e===zv||e===Vv?{byteLength:16,width:8,height:6}:e===Gv||e===jv?{byteLength:16,width:8,height:8}:e===Hv||e===Wv?{byteLength:16,width:10,height:5}:e===$v||e===qv?{byteLength:16,width:10,height:6}:e===Xv||e===Yv?{byteLength:16,width:10,height:8}:e===Kv||e===Qv?{byteLength:16,width:10,height:10}:e===Zv||e===Jv?{byteLength:16,width:12,height:10}:e===eT||e===tT?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=sT;return e===M?t=iT:e===E&&(t=rT),t}_convertFilterMode(e){let t=nT;return e!==A&&1004!==e&&e!==R||(t=aT),t}_getBytesPerTexel(e){return e===y_||e===b_||e===x_||e===__?1:e===v_||e===T_||e===w_||e===S_||e===M_||e===N_||e===E_?2:e===A_||e===C_||e===R_||e===P_||e===F_||e===I_||e===B_||e===L_||e===D_||e===O_||e===k_||e===U_||e===z_||e===V_||e===G_||e===j_||e===sv||e===ev||e===tv||e===iv?4:e===H_||e===W_||e===$_||e===q_||e===X_||e===Y_?8:e===K_||e===Q_||e===Z_?16:void 0}_getTypedArrayType(e){return e===x_?Uint8Array:e===__?Int8Array:e===y_?Uint8Array:e===b_?Int8Array:e===N_?Uint8Array:e===E_?Int8Array:e===S_?Uint8Array:e===M_?Int8Array:e===O_?Uint8Array:e===k_?Int8Array:e===B_?Uint8Array:e===D_?Int8Array:e===v_?Uint16Array:e===T_?Int16Array:e===P_?Uint16Array:e===F_?Int16Array:e===q_?Uint16Array:e===X_?Int16Array:e===w_||e===I_||e===Y_?Uint16Array:e===A_?Uint32Array:e===C_?Int32Array:e===R_?Float32Array:e===H_?Uint32Array:e===W_?Int32Array:e===$_?Float32Array:e===K_?Uint32Array:e===Q_?Int32Array:e===Z_?Float32Array:e===U_||e===z_?Uint8Array:e===G_||e===V_||e===j_?Uint32Array:e===sv?Float32Array:e===ev||e===tv?Uint32Array:e===iv?Float32Array:void 0}_getDimension(e){let t;return t=e.isData3DTexture?XT:qT,t}}function dw(e,t=null){const s=e.format,i=e.type,r=e.colorSpace;let n;if(!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(s){case J:n=r===_e?nv:rv;break;case ee:n=r===_e?ov:av;break;case te:n=r===_e?lv:hv;break;case se:n=r===_e?xv:bv;break;case ie:n=r===_e?wv:Tv;break;case re:n=r===_e?Cv:Av;break;case ne:n=r===_e?Pv:Rv;break;case ae:n=r===_e?Iv:Fv;break;case oe:n=r===_e?Lv:Bv;break;case he:n=r===_e?Ov:Dv;break;case le:n=r===_e?Uv:kv;break;case ue:n=r===_e?Vv:zv;break;case ce:n=r===_e?jv:Gv;break;case de:n=r===_e?Wv:Hv;break;case pe:n=r===_e?qv:$v;break;case me:n=r===_e?Yv:Xv;break;case ge:n=r===_e?Qv:Kv;break;case fe:n=r===_e?Jv:Zv;break;case ye:n=r===_e?tT:eT;break;case H:n=r===_e?L_:B_;break;default:console.error("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case H:switch(i){case L:n=D_;break;case D:n=X_;break;case O:n=q_;break;case U:n=K_;break;case k:n=Q_;break;case B:n=r===_e?L_:B_;break;case V:n=Y_;break;case z:n=Z_;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case j:if(35902===i)n=V_;else console.error("WebGPURenderer: Unsupported texture type with RGBFormat.",i);break;case q:switch(i){case L:n=b_;break;case D:n=T_;break;case O:n=v_;break;case U:n=A_;break;case k:n=C_;break;case B:n=y_;break;case V:n=w_;break;case z:n=R_;break;default:console.error("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case Y:switch(i){case L:n=M_;break;case D:n=F_;break;case O:n=P_;break;case U:n=H_;break;case k:n=W_;break;case B:n=S_;break;case V:n=I_;break;case z:n=$_;break;default:console.error("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case W:switch(i){case O:n=J_;break;case U:n=ev;break;case z:n=sv;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case $:switch(i){case G:n=tv;break;case z:t&&!1===t.features.has(sw.Depth32FloatStencil8)&&console.error('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),n=iv;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case X:switch(i){case k:n=C_;break;case U:n=A_;break;default:console.error("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case K:switch(i){case k:n=W_;break;case U:n=H_;break;default:console.error("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case Q:switch(i){case k:n=Q_;break;case U:n=K_;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:console.error("WebGPURenderer: Unsupported texture format.",s)}return n}const pw=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,mw=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,gw={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 fw extends Sb{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(pw);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=mw.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=gw[r]),n.push(new db(r,t))}const a=e.substring(t[0].length),o=t[3]||"void",h=void 0!==t[1]?t[1]:"";return{type:gw[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 yw extends wb{parseFunction(e){return new fw(e)}}const bw="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},xw={[ln]:"read",[un]:"write",[cn]:"read_write"},_w={[M]:"repeat",[N]:"clamp",[E]:"mirror"},vw={vertex:bw?bw.VERTEX:1,fragment:bw?bw.FRAGMENT:2,compute:bw?bw.COMPUTE:4},Tw={instance:!0,swizzleAssign:!1,storageBuffer:!0},ww={"^^":"tsl_xor"},Sw={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>"},Mw={},Nw={tsl_xor:new kf("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new kf("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new kf("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new kf("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new kf("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new kf("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new kf("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new kf("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 kf("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 kf("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new kf("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 kf("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new kf("\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")},Ew={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>"};"undefined"!=typeof navigator&&/Windows/g.test(navigator.userAgent)&&(Nw.pow_float=new kf("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),Nw.pow_vec2=new kf("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[Nw.pow_float]),Nw.pow_vec3=new kf("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[Nw.pow_float]),Nw.pow_vec4=new kf("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[Nw.pow_float]),Ew.pow_float="tsl_pow_float",Ew.pow_vec2="tsl_pow_vec2",Ew.pow_vec3="tsl_pow_vec3",Ew.pow_vec4="tsl_pow_vec4");let Aw="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(Aw+="diagnostic( off, derivative_uniformity );\n");class Cw extends ub{constructor(e,t){super(e,t,new yw),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==xe}_generateTextureSample(e,t,s,i,r=this.shaderStage){return"fragment"===r?i?`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s):this.generateTextureLod(e,t,s,i,"0")}_generateVideoSample(e,t,s=this.shaderStage){if("fragment"===s)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2<f32>( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${s} shader.`)}_generateTextureSampleLevel(e,t,s,i,r,n=this.shaderStage){return"fragment"!==n&&"compute"!==n||!1!==this.isUnfilterable(e)?this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,i):this.generateTextureLod(e,t,s,r,i):`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`}generateWrapFunction(e){const t=`tsl_coord_${_w[e.wrapS]}S_${_w[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let s=Mw[t];if(void 0===s){const i=[],r=e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const a=(e,t)=>{e===M?(i.push(Nw.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===N?(i.push(Nw.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===E?(i.push(Nw.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",Mw[t]=s=new kf(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.isData3DTexture?"vec3<u32>":"vec2<u32>",n=h||e.isVideoTexture||e.isStorageTexture?t:`${t}${s?`, u32( ${s} )`:""}`,r=new el(new El(`textureDimensions( ${n} )`,a)),i.dimensionsSnippet[s]=r,(e.isDataArrayTexture||e.isDepthArrayTexture||e.isData3DTexture)&&(i.arrayLayerCount=new el(new El(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new el(new El("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,s,i="0u"){this._include("biquadraticTexture");return`tsl_biquadraticTexture( ${t}, ${this.generateWrapFunction(e)}( ${s} ), ${this.generateTextureDimension(e,t,i)}, u32( ${i} ) )`}generateTextureLod(e,t,s,i,r="0u"){const n=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,r),o=e.isData3DTexture?"vec3":"vec2",h=`${o}<u32>( ${n}( ${s} ) * ${o}<f32>( ${a} ) )`;return this.generateTextureLoad(e,t,h,i,r)}generateTextureLoad(e,t,s,i,r="0u"){let n;return!0===e.isVideoTexture||!0===e.isStorageTexture?n=`textureLoad( ${t}, ${s} )`:i?n=`textureLoad( ${t}, ${s}, ${i}, u32( ${r} ) )`:(n=`textureLoad( ${t}, ${s}, u32( ${r} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(n+=".x")),n}generateTextureStore(e,t,s,i){return`textureStore( ${t}, ${s}, ${i} )`}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===z||!1===this.isSampleCompare(e)&&e.minFilter===A&&e.magFilter===A||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,s,i,r=this.shaderStage){let n=null;return n=!0===e.isVideoTexture?this._generateVideoSample(t,s,r):this.isUnfilterable(e)?this.generateTextureLod(e,t,s,i,"0",r):this._generateTextureSample(e,t,s,i,r),n}generateTextureGrad(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${n} shader.`)}generateTextureCompare(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return e.isDepthArrayTexture?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${n} shader.`)}generateTextureLevel(e,t,s,i,r,n=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,s,n):this._generateTextureSampleLevel(e,t,s,i,r,n),a}generateTextureBias(e,t,s,i,r,n=this.shaderStage){if("fragment"===n)return`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${n} 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||"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=ww[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?ln:e.access}getStorageAccess(e,t){return xw[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||"storageTexture"===t||"texture3D"===t){let i=null;const n=this.getNodeAccess(e,s);if("texture"===t||"storageTexture"===t?i=new yx(r.name,r.node,o,n):"cubeTexture"===t?i=new bx(r.name,r.node,o,n):"texture3D"===t&&(i=new xx(r.name,r.node,o,n)),i.store=!0===e.isStorageTextureNode,i.setVisibility(vw[s]),"fragment"!==s&&"compute"!==s||!1!==this.isUnfilterable(e.value)||!1!==i.store)l.push(i),a=[i];else{const e=new rw(`${r.name}_sampler`,r.node,o);e.setVisibility(vw[s]),l.push(e,i),a=[e,i]}}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=new("buffer"===t?cx:ow)(e,o);n.setVisibility(vw[s]),l.push(n),a=n,r.name=i||"NodeBuffer_"+r.id}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let i=e[h];void 0===i&&(i=new mx(h,o),i.setVisibility(vw[s]),e[h]=i,l.push(i)),a=this.getNodeUniform(r,t),i.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","Vertex","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( ${this.renderer.backend.compatibilityMode?"flat, either":"flat"} )`);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||"storageTexture"===r.type||"texture3D"===r.type){const t=r.node.value;let i;"fragment"!==e&&"compute"!==e||!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)i="texture_cube<f32>";else if(!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture||!0===t.isTextureArray)i="texture_2d_array<f32>";else if(!0===t.isDepthTexture)i=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${n}_2d<f32>`:`texture_depth${n}_2d${!0===t.isDepthArrayTexture?"_array":""}`;else if(!0===t.isVideoTexture)i="texture_external";else if(!0===t.isData3DTexture)i="texture_3d<f32>";else if(!0===r.node.isStorageTextureNode){i=`texture_storage_2d<${dw(t)}, ${this.getStorageAccess(r.node,e)}>`}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=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(n[t]||(n[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}}for(const e in n){const t=n[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=s.join("\n");return a+=i.join("\n"),a+=r.join("\n"),a}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.Vertex = ${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}this.shaderStage=null,null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getType(e){return Sw[e]||e}isAvailable(e){let t=Tw[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),Tw[e]=t),t}_getWGSLMethod(e){return void 0!==Nw[e]&&this._include(e),Ew[e]}_include(e){const t=Nw[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(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${Aw}\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){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( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\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 Rw{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=tv:e.depth&&(t=ev),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.samples}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}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?Yx:e.isLineSegments||e.isMesh&&!0===t.wireframe?Kx:e.isLine?Qx:e.isMesh?Zx:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===B)return U_;if(e===V)return Y_;throw new Error("Unsupported outputType")}}const Pw=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),Fw=new Map([[ii,["float16"]]]),Iw=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class Bw{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+(4-o.byteLength%4)%4;n=a.createBuffer({label:s.name,size:h,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=this._isTypedArray(a),h=t.updateRanges;if(0===h.length)i.queue.writeBuffer(n,0,a,0);else{const e=o?1:a.BYTES_PER_ELEMENT;for(let t=0,s=h.length;t<s;t++){const s=h[t];let l,u;if(!0===r._force3to4BytesAlignment){l=4*Math.floor(s.start/3)*e,u=4*Math.ceil(s.count/3)*e}else l=s.start*e,u=s.count*e;const c=l*(o?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?tw:ew):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?tw:ew),!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(),l=new e.array.constructor(h.slice(0));return n.unmap(),l.buffer}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,r=e.constructor;let n;if(1===t)n=Iw.get(i);else{const e=(Fw.get(r)||Pw.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||console.error("THREE.WebGPUAttributeUtils: Vertex format not supported yet."),n}_isTypedArray(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class Lw{constructor(e){this.backend=e,this.bindGroupLayoutCache=new WeakMap}createBindingsLayout(e){const t=this.backend,s=t.device,i=[];let r=0;for(const s of e.bindings){const e={binding:r++,visibility:s.visibility};if(s.isUniformBuffer||s.isStorageBuffer){const t={};s.isStorageBuffer&&(4&s.visibility&&(s.access===cn||s.access===un)?t.type=LT:t.type=DT),e.buffer=t}else if(s.isSampler){const i={};s.texture.isDepthTexture&&(null!==s.texture.compareFunction?i.type=VT:t.compatibilityMode&&(i.type=zT)),e.sampler=i}else if(s.isSampledTexture&&s.texture.isVideoTexture)e.externalTexture={};else if(s.isSampledTexture&&s.store){const t={};t.format=this.backend.get(s.texture).texture.format;const i=s.access;t.access=i===cn?UT:i===un?OT:kT,e.storageTexture=t}else if(s.isSampledTexture){const i={},{primarySamples:r}=t.utils.getTextureSampleData(s.texture);if(r>1&&(i.multisampled=!0,s.texture.isDepthTexture||(i.sampleType=jT)),s.texture.isDepthTexture)t.compatibilityMode&&null===s.texture.compareFunction?i.sampleType=jT:i.sampleType=HT;else if(s.texture.isDataTexture||s.texture.isDataArrayTexture||s.texture.isData3DTexture){const e=s.texture.type;e===k?i.sampleType=WT:e===U?i.sampleType=$T:e===z&&(this.backend.hasFeature("float32-filterable")?i.sampleType=GT:i.sampleType=jT)}s.isSampledCubeTexture?i.viewDimension=QT:s.texture.isDataArrayTexture||s.texture.isDepthArrayTexture||s.texture.isCompressedArrayTexture?i.viewDimension=KT:s.isSampledTexture3D&&(i.viewDimension=ZT),e.texture=i}else console.error(`WebGPUBindingUtils: Unsupported binding "${s}".`);i.push(e)}return s.createBindGroupLayout({entries:i})}createBindings(e,t,s,i=0){const{backend:r,bindGroupLayoutCache:n}=this,a=r.get(e);let o,h=n.get(e.bindingsReference);void 0===h&&(h=this.createBindingsLayout(e),n.set(e.bindingsReference,h)),s>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[s]===i&&(o=a.groups[s])),void 0===o&&(o=this.createBindGroup(e,h),s>0&&(a.groups[s]=o,a.versions[s]=i)),a.group=o,a.layout=h}updateBinding(e){const t=this.backend,s=t.device,i=e.buffer,r=t.get(e).buffer;s.queue.writeBuffer(r,0,i,0)}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=i.createBuffer({label:"bindingBuffer_"+t.name,size:s,usage:r});e.buffer=n}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=s.get(t);if(void 0===e.buffer){const i=t.attribute;e.buffer=s.get(i).buffer}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isSampler){const e=s.get(t.texture);n.push({binding:r,resource:e.sampler})}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=`view-${e.texture.width}-${e.texture.height}-${s}`;if(a=e[i],void 0===a){const r=JT;let n;n=t.isSampledCubeTexture?QT:t.isSampledTexture3D?ZT:t.texture.isDataArrayTexture||t.texture.isDepthArrayTexture||t.texture.isCompressedArrayTexture?KT:YT,a=e[i]=e.texture.createView({aspect:r,dimension:n,mipLevelCount:s})}}n.push({binding:r,resource:a})}r++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}}class Dw{constructor(e){this.backend=e}_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);d.push(e.layout)}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;for(let e=0;e<t.length;e++){const s=u.getTextureFormatGPU(t[e]);y.push({format:s,blend:m,writeMask:f})}}else{const t=u.getCurrentColorFormat(e.context);y.push({format:t,blend:m,writeMask:f})}const b=h.get(a).module,x=h.get(o).module,_=this._getPrimitiveState(s,r,i),v=this._getDepthCompare(i),T=u.getCurrentDepthStencilFormat(e.context),w=this._getSampleCount(e.context),S={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},b,{buffers:p}),fragment:Object.assign({},x,{targets:y}),primitive:_,multisample:{count:w,alphaToCoverageEnabled:i.alphaToCoverage&&w>1},layout:l.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={},M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(M.depthBias=i.polygonOffsetUnits,M.depthBiasSlopeScale=i.polygonOffsetFactor,M.depthBiasClamp=0),S.depthStencil=M),null===t)c.pipeline=l.createRenderPipeline(S);else{const e=new Promise((e=>{l.createRenderPipelineAsync(S).then((t=>{c.pipeline=t,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.getCurrentColorFormat(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);a.push(t.layout)}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:_T},s={srcFactor:r,dstFactor:n,operation:_T}};if(e.premultipliedAlpha)switch(i){case 1:r(hT,dT,hT,dT);break;case 2:r(hT,hT,hT,hT);break;case 3:r(oT,uT,oT,hT);break;case 4:r(oT,lT,oT,cT)}else switch(i){case 1:r(cT,dT,hT,dT);break;case 2:r(cT,hT,cT,hT);break;case 3:r(oT,uT,oT,hT);break;case 4:r(oT,lT,oT,lT)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case u:t=oT;break;case 201:t=hT;break;case 202:t=lT;break;case 203:t=uT;break;case m:t=cT;break;case g:t=dT;break;case 208:t=pT;break;case 209:t=mT;break;case 206:t=gT;break;case 207:t=fT;break;case 210:t=yT;break;case 211:t=bT;break;case 212:t=xT;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=e_;break;case 519:t=o_;break;case 513:t=t_;break;case 515:t=i_;break;case 514:t=s_;break;case 518:t=a_;break;case 516:t=r_;break;case 517:t=n_;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case Se:t=ET;break;case 0:t=AT;break;case 7681:t=CT;break;case 5386:t=RT;break;case 7682:t=PT;break;case 7683:t=FT;break;case 34055:t=IT;break;case 34056:t=BT;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case o:t=_T;break;case 101:t=vT;break;case 102:t=TT;break;case 103:t=wT;break;case 104:t=ST;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},r=this.backend.utils;switch(i.topology=r.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?g_:f_),s.side){case 0:i.frontFace=c_,i.cullMode=m_;break;case 1:i.frontFace=c_,i.cullMode=p_;break;case 2:i.frontFace=c_,i.cullMode=d_;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",s.side)}return i}_getColorWriteMask(e){return!0===e.colorWrite?NT:MT}_getDepthCompare(e){let t;if(!1===e.depthTest)t=o_;else{const s=e.depthFunc;switch(s){case 0:t=e_;break;case 1:t=o_;break;case 2:t=t_;break;case 3:t=i_;break;case 4:t=s_;break;case 5:t=a_;break;case 6:t=r_;break;case 7:t=n_;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class Ow extends $x{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 tt(`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.id,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));let a=0;for(const[,t]of e){const e=n[t],s=n[t+1];a+=Number(s-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("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){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("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 kw extends Cx{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new Rw(this),this.attributeUtils=new Bw(this),this.bindingUtils=new Lw(this),this.pipelineUtils=new Dw(this),this.textureUtils=new cw(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},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(sw),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;s.lost.then((t=>{const s={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(s)}));const i=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=s,this.context=i;const r=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(sw.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r}),this.updateSize()}get coordinateSystem(){return De}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const s=e.colorAttachments[0];this.renderer.samples>0?s.view=this.colorBuffer.createView():s.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isDepthArrayTexture&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const s=e.renderTarget,i=this.get(s);let r=i.descriptors;if(void 0===r||i.width!==s.width||i.height!==s.height||i.dimensions!==s.dimensions||i.activeMipmapLevel!==e.activeMipmapLevel||i.activeCubeFace!==e.activeCubeFace||i.samples!==s.samples){r={},i.descriptors=r;const e=()=>{s.removeEventListener("dispose",e),this.delete(s)};!1===s.hasEventListener("dispose",e)&&s.addEventListener("dispose",e)}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:YT};if(s.isRenderTarget3D)h=e.activeCubeFace,n.baseArrayLayer=0,n.dimension=ZT,n.depthOrArrayLayers=t[i].image.depth;else if(s.isRenderTargetArray)if(!0===l){const t=e.camera.cameras;for(let e=0;e<t.length;e++){const t={...n,baseArrayLayer:e,arrayLayerCount:1,dimension:YT},s=r.texture.createView(t);o.push({view:s,resolveTarget:void 0,depthSlice:void 0})}}else n.dimension=KT,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.isDepthArrayTexture&&(s.dimension=YT,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,i.dimensions=s.dimensions}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||l_,storeOp:t.storeOp||h_,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:l_}),this.initTimestampQuery(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=u_):i.loadOp=l_,i.storeOp=h_}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=u_):t.loadOp=l_,t.storeOp=h_}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=u_):a.depthLoadOp=l_,a.depthStoreOp=h_),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=u_):a.stencilLoadOp=l_,a.stencilStoreOp=h_);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);if(t.currentPass=s,e.viewport&&this.updateViewport(e),e.scissor){const{x:t,y:i,width:r,height:n}=e.scissorValue;s.setScissorRect(t,i,r,n)}}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:YT,baseArrayLayer:a,arrayLayerCount:1})),i.depthStencilAttachment={view:n.viewCache[t],depthLoadOp:r.depthLoadOp||u_,depthStoreOp:r.depthStoreOp||h_,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=u_):t.depthLoadOp=l_),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=u_):t.stencilLoadOp=l_)}}}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)}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,u=[];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,l=n.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){u=t.colorAttachments;const e=u[0];e.clearValue=o,e.loadOp=u_,e.storeOp=h_}(h||l)&&(a=t.depthStencilAttachment)}else{h=i.depth,l=i.stencil;const r={loadOp:e?u_:l_,clearValue:e?o:void 0};h&&(r.depthLoadOp=t?u_:l_,r.depthClearValue=t?n.getClearDepth():void 0,r.depthStoreOp=h_),l&&(r.stencilLoadOp=s?u_:l_,r.stencilClearValue=s?n.getClearStencil():void 0,r.stencilStoreOp=h_);const c=this._getRenderPassDescriptor(i,r);u=c.colorAttachments,a=c.depthStencilAttachment}h&&a&&void 0===a.depthLoadOp&&(t?(a.depthLoadOp=u_,a.depthClearValue=n.getClearDepth(),a.depthStoreOp=h_):(a.depthLoadOp=l_,a.depthStoreOp=h_)),l&&a&&void 0===a.stencilLoadOp&&(s?(a.stencilLoadOp=u_,a.stencilClearValue=n.getClearStencil(),a.stencilStoreOp=h_):(a.stencilLoadOp=l_,a.stencilStoreOp=h_));const c=r.createCommandEncoder({label:"clear"});c.beginRenderPass({colorAttachments:u,depthStencilAttachment:a}).end(),r.queue.submit([c.finish()])}beginCompute(e){const t=this.get(e),s={label:"computeGroup_"+e.id};this.initTimestampQuery(e,s),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(s)}compute(e,t,s,i){const{passEncoderGPU:r}=this.get(e),n=this.get(i).pipeline;r.setPipeline(n);for(let e=0,t=s.length;e<t;e++){const t=s[e],i=this.get(t);r.setBindGroup(e,i.group)}const a=this.device.limits.maxComputeWorkgroupsPerDimension,o=this.get(t);void 0===o.dispatchSize&&(o.dispatchSize={x:0,y:1,z:1});const{dispatchSize:h}=o;t.dispatchCount>a?(h.x=Math.min(t.dispatchCount,a),h.y=Math.ceil(t.dispatchCount/a)):h.x=t.dispatchCount,r.dispatchWorkgroups(h.x,h.y,h.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:s,material:i,context:r,pipeline:n}=e,a=e.getBindings(),o=this.get(r),h=this.get(n).pipeline,l=e.getIndex(),u=null!==l,c=e.getDrawParameters();if(null===c)return;const d=(t,s)=>{t.setPipeline(h),s.pipeline=h;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===u&&s.index!==l){const e=this.get(l).buffer,i=l.array instanceof Uint16Array?g_:f_;t.setIndexBuffer(e,i),s.index=l}const c=e.getVertexBuffers();for(let e=0,i=c.length;e<i;e++){const i=c[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)},p=(i,r)=>{if(d(i,r),!0===s.isBatchedMesh){const e=s._multiDrawStarts,r=s._multiDrawCounts,n=s._multiDrawCount,a=s._multiDrawInstances;null!==a&&tt("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o<n;o++){const n=a?a[o]:1,h=n>1?0:o;!0===u?i.drawIndexed(r[o],n,e[o]/l.array.BYTES_PER_ELEMENT,0,h):i.draw(r[o],n,e[o],h),t.update(s,r[o],n)}}else if(!0===u){const{vertexCount:r,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;i.drawIndexedIndirect(e,0)}else i.drawIndexed(r,n,a,0,0);t.update(s,r,n)}else{const{vertexCount:r,instanceCount:n,firstVertex:a}=c,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;i.drawIndirect(e,0)}else i.draw(r,n,a,0);t.update(s,r,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 i=this.bindingUtils.createBindGroupIndex(r,e.layout);s.push(i)}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,l=o.currentSets;if(o.bundleEncoders){i=o.bundleEncoders[e],l=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]),l.bindingGroups[n.index]=n.id),p(i,l)}}}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)}p(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),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;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,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,s),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}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){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const s=e.isComputeNode?"compute":"render";this.timestampQueryPool[s]||(this.timestampQueryPool[s]=new Ow(this.device,s,2048));const i=this.timestampQueryPool[s],r=i.allocateQueriesForContext(e);t.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:r,endOfPassWriteIndex:r+1}}createNodeBuilder(e,t){return new Cw(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)}createIndexAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}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.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return 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 console.error("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),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=l_;if(t.depth&&(e.depthStencilAttachment.depthLoadOp=l_),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=l_),i.currentPass=a.beginRenderPass(e),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor){const{x:e,y:s,width:r,height:n}=t.scissorValue;i.currentPass.setScissorRect(e,s,r,n)}}else this.device.queue.submit([a.finish()])}}class Uw extends Ar{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 zw extends Ub{constructor(){super(),this.addMaterial(pp,"MeshPhongMaterial"),this.addMaterial(eg,"MeshStandardMaterial"),this.addMaterial(sg,"MeshPhysicalMaterial"),this.addMaterial(ag,"MeshToonMaterial"),this.addMaterial(rp,"MeshBasicMaterial"),this.addMaterial(cp,"MeshLambertMaterial"),this.addMaterial(Hd,"MeshNormalMaterial"),this.addMaterial(ug,"MeshMatcapMaterial"),this.addMaterial(zd,"LineBasicMaterial"),this.addMaterial(Gd,"LineDashedMaterial"),this.addMaterial(fg,"PointsMaterial"),this.addMaterial(mg,"SpriteMaterial"),this.addMaterial(xg,"ShadowMaterial"),this.addLight(Cy,Ir),this.addLight(pb,Dr),this.addLight(yb,kr),this.addLight(bb,Ar),this.addLight(_b,Or),this.addLight(vb,Tr),this.addLight(Tb,zr),this.addLight(xb,Uw),this.addToneMapping(Af,1),this.addToneMapping(Cf,2),this.addToneMapping(Rf,3),this.addToneMapping(Ff,4),this.addToneMapping(Df,6),this.addToneMapping(Of,7)}}class Vw extends ax{constructor(e={}){let t;e.forceWebGL?t=Xx:(t=kw,e.getFallback=()=>(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new Xx(e)));super(new t(e),e),this.library=new zw,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const Gw={type:"change"},jw={type:"start"},Hw={type:"end"},Ww=1e-6,$w=-1,qw=0,Xw=1,Yw=2,Kw=3,Qw=4,Zw=new e.Vector2,Jw=new e.Vector2,eS=new e.Vector3,tS=new e.Vector3,sS=new e.Vector3,iS=new e.Quaternion,rS=new e.Vector3,nS=new e.Vector3,aS=new e.Vector3,oS=new e.Vector3;class hS 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=$w,this.keyState=$w,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=uS.bind(this),this._onPointerDown=lS.bind(this),this._onPointerUp=cS.bind(this),this._onPointerCancel=dS.bind(this),this._onContextMenu=xS.bind(this),this._onMouseWheel=bS.bind(this),this._onKeyDown=mS.bind(this),this._onKeyUp=pS.bind(this),this._onTouchStart=_S.bind(this),this._onTouchMove=vS.bind(this),this._onTouchEnd=TS.bind(this),this._onMouseDown=gS.bind(this),this._onMouseMove=fS.bind(this),this._onMouseUp=yS.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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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)>Ww&&(this.dispatchEvent(Gw),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>Ww||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(Gw),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=$w,this.keyState=$w,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(Gw),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(Jw.copy(this._panEnd).sub(this._panStart),Jw.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;Jw.x*=e,Jw.y*=t}Jw.multiplyScalar(this._eye.length()*this.panSpeed),tS.copy(this._eye).cross(this.object.up).setLength(Jw.x),tS.add(eS.copy(this.object.up).setLength(Jw.y)),this.object.position.add(tS),this.target.add(tS),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(Jw.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){oS.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=oS.length();e?(this._eye.copy(this.object.position).sub(this.target),rS.copy(this._eye).normalize(),nS.copy(this.object.up).normalize(),aS.crossVectors(nS,rS).normalize(),nS.setLength(this._moveCurr.y-this._movePrev.y),aS.setLength(this._moveCurr.x-this._movePrev.x),oS.copy(nS.add(aS)),sS.crossVectors(oS,this._eye).normalize(),e*=this.rotateSpeed,iS.setFromAxisAngle(sS,e),this._eye.applyQuaternion(iS),this.object.up.applyQuaternion(iS),this._lastAxis.copy(sS),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),iS.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(iS),this.object.up.applyQuaternion(iS)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let t;this.state===Qw?(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 Zw.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),Zw}_getMouseOnCircle(e,t){return Zw.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),Zw}_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 lS(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e))}function uS(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function cS(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.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp)))}function dS(e){this._removePointer(e)}function pS(){!1!==this.enabled&&(this.keyState=$w,window.addEventListener("keydown",this._onKeyDown))}function mS(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===$w&&(e.code!==this.keys[qw]||this.noRotate?e.code!==this.keys[Xw]||this.noZoom?e.code!==this.keys[Yw]||this.noPan||(this.keyState=Yw):this.keyState=Xw:this.keyState=qw))}function gS(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=Xw;break;case e.MOUSE.ROTATE:this.state=qw;break;case e.MOUSE.PAN:this.state=Yw;break;default:this.state=$w}const i=this.keyState!==$w?this.keyState:this.state;i!==qw||this.noRotate?i!==Xw||this.noZoom?i!==Yw||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(jw)}function fS(e){const t=this.keyState!==$w?this.keyState:this.state;t!==qw||this.noRotate?t!==Xw||this.noZoom?t!==Yw||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 yS(){this.state=$w,this.dispatchEvent(Hw)}function bS(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(jw),this.dispatchEvent(Hw)}}function xS(e){!1!==this.enabled&&e.preventDefault()}function _S(e){if(this._trackPointer(e),1===this._pointers.length)this.state=Kw,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=Qw;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(jw)}function vS(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 TS(e){switch(this._pointers.length){case 0:this.state=$w;break;case 1:this.state=Kw,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=Qw;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(Hw)}const wS={type:"change"},SS={type:"start"},MS={type:"end"},NS=new e.Ray,ES=new e.Plane,AS=Math.cos(70*e.MathUtils.DEG2RAD),CS=new e.Vector3,RS=2*Math.PI,PS=-1,FS=0,IS=1,BS=2,LS=3,DS=4,OS=5,kS=6,US=1e-6;class zS extends e.Controls{constructor(t,s=null){super(t,s),this.state=PS,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._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=GS.bind(this),this._onPointerDown=VS.bind(this),this._onPointerUp=jS.bind(this),this._onContextMenu=KS.bind(this),this._onMouseWheel=$S.bind(this),this._onKeyDown=qS.bind(this),this._onTouchStart=XS.bind(this),this._onTouchMove=YS.bind(this),this._onMouseDown=HS.bind(this),this._onMouseMove=WS.bind(this),this._interceptControlDown=QS.bind(this),this._interceptControlUp=ZS.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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(wS),this.update(),this.state=PS}update(t=null){const s=this.object.position;CS.copy(s).sub(this.target),CS.applyQuaternion(this._quat),this._spherical.setFromVector3(CS),this.autoRotate&&this.state===PS&&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+=RS:i>Math.PI&&(i-=RS),r<-Math.PI?r+=RS:r>Math.PI&&(r-=RS),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(CS.setFromSpherical(this._spherical),CS.applyQuaternion(this._quatInverse),s.copy(this.target).add(CS),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=CS.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=CS.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):(NS.origin.copy(this.object.position),NS.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(NS.direction))<AS?this.object.lookAt(this.target):(ES.setFromNormalAndCoplanarPoint(this.object.up,this.target),NS.intersectPlane(ES,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)>US||8*(1-this._lastQuaternion.dot(this.object.quaternion))>US||this._lastTargetPosition.distanceToSquared(this.target)>US)&&(this.dispatchEvent(wS),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?RS/60*this.autoRotateSpeed*e:RS/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){CS.setFromMatrixColumn(t,0),CS.multiplyScalar(-e),this._panOffset.add(CS)}_panUp(e,t){!0===this.screenSpacePanning?CS.setFromMatrixColumn(t,1):(CS.setFromMatrixColumn(t,0),CS.crossVectors(this.object.up,CS)),CS.multiplyScalar(e),this._panOffset.add(CS)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;CS.copy(i).sub(this.target);let r=CS.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(RS*this._rotateDelta.x/t.clientHeight),this._rotateUp(RS*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(RS*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(-RS*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(RS*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(-RS*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(RS*this._rotateDelta.x/t.clientHeight),this._rotateUp(RS*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 VS(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e)))}function GS(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function jS(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(MS),this.state=PS;break;case 1:const t=this._pointers[0],s=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:s.x,pageY:s.y})}}function HS(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=IS;break;case e.MOUSE.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=BS}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=FS}break;case e.MOUSE.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=FS}else{if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=BS}break;default:this.state=PS}this.state!==PS&&this.dispatchEvent(SS)}function WS(e){switch(this.state){case FS:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case IS:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case BS:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function $S(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===PS&&(e.preventDefault(),this.dispatchEvent(SS),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(MS))}function qS(e){!1!==this.enabled&&this._handleKeyDown(e)}function XS(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=LS;break;case e.TOUCH.PAN:if(!1===this.enablePan)return;this._handleTouchStartPan(t),this.state=DS;break;default:this.state=PS}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=OS;break;case e.TOUCH.DOLLY_ROTATE:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(t),this.state=kS;break;default:this.state=PS}break;default:this.state=PS}this.state!==PS&&this.dispatchEvent(SS)}function YS(e){switch(this._trackPointer(e),this.state){case LS:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case DS:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case OS:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case kS:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=PS}}function KS(e){!1!==this.enabled&&e.preventDefault()}function QS(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function ZS(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const JS={type:"change"},eM=1e-6,tM=new e.Quaternion;class sM 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=iM.bind(this),this._onKeyUp=rM.bind(this),this._onPointerMove=aM.bind(this),this._onPointerDown=nM.bind(this),this._onPointerUp=oM.bind(this),this._onPointerCancel=hM.bind(this),this._onContextMenu=lM.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),tM.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(tM),(this._lastPosition.distanceToSquared(t.position)>eM||8*(1-this._lastQuaternion.dot(t.quaternion))>eM)&&(this.dispatchEvent(JS),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 iM(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 rM(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 nM(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 aM(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 oM(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 hM(){!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 lM(e){!1!==this.enabled&&e.preventDefault()}const uM={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 cM{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 dM=new e.OrthographicCamera(-1,1,1,-1,0,1);class pM 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 mM=new pM;class gM{constructor(t){this._mesh=new e.Mesh(mM,t)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,dM)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class fM extends cM{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 gM(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 yM extends cM{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 bM extends cM{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class xM{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 fM(uM),this.copyPass.material.blending=e.NoBlending,this.clock=new e.Clock}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){void 0===e&&(e=this.clock.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!==yM&&(i instanceof yM?s=!0:i instanceof bM&&(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 _M extends cM{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._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 vM(){return vM=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},vM.apply(null,arguments)}function TM(e,t){return TM=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},TM(e,t)}function wM(e){return wM=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},wM(e)}function SM(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(SM=function(){return!!e})()}function MM(e){var t="function"==typeof Map?new Map:void 0;return MM=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(SM())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return s&&TM(r,s.prototype),r}(e,arguments,wM(this).constructor)}return s.prototype=Object.create(e.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),TM(s,e)},MM(e)}var NM={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 EM(){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 AM=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,EM.apply(void 0,[NM[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,TM(e,t)}(t,e),t}(MM(Error));function CM(e){return Math.round(255*e)}function RM(e,t,s){return CM(e)+","+CM(t)+","+CM(s)}function PM(e,t,s,i){if(void 0===i&&(i=RM),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 FM={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 IM=/^#[a-fA-F0-9]{6}$/,BM=/^#[a-fA-F0-9]{8}$/,LM=/^#[a-fA-F0-9]{3}$/,DM=/^#[a-fA-F0-9]{4}$/,OM=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,kM=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,UM=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,zM=/^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 VM(e){if("string"!=typeof e)throw new AM(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return FM[t]?"#"+FM[t]:e}(e);if(t.match(IM))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(BM)){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(LM))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(DM)){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=OM.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var n=kM.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=UM.exec(t);if(a){var o="rgb("+PM(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",h=OM.exec(o);if(!h)throw new AM(4,t,o);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10)}}var l=zM.exec(t.substring(0,50));if(l){var u="rgb("+PM(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",c=OM.exec(u);if(!c)throw new AM(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 AM(5)}function GM(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}}(VM(e))}var jM=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 HM(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function WM(e){return HM(Math.round(255*e))}function $M(e,t,s){return jM("#"+WM(e)+WM(t)+WM(s))}function qM(e,t,s){return PM(e,t,s,$M)}function XM(e,t,s){if("number"==typeof e&&"number"==typeof t&&"number"==typeof s)return jM("#"+HM(e)+HM(t)+HM(s));if("object"==typeof e&&void 0===t&&void 0===s)return jM("#"+HM(e.red)+HM(e.green)+HM(e.blue));throw new AM(6)}function YM(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?XM(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new AM(7)}function KM(e){if("object"!=typeof e)throw new AM(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return YM(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 XM(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?qM(e.hue,e.saturation,e.lightness):"rgba("+PM(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new AM(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 qM(e.hue,e.saturation,e.lightness);throw new AM(1)}(e);throw new AM(8)}function QM(e,t,s){return function(){var i=s.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):QM(e,t,i)}}function ZM(e){return QM(e,e.length,[])}function JM(e,t,s){return Math.max(e,Math.min(t,s))}ZM((function(e,t){if("transparent"===t)return t;var s=GM(t);return KM(vM({},s,{hue:s.hue+parseFloat(e)}))})),ZM((function(e,t){if("transparent"===t)return t;var s=GM(t);return KM(vM({},s,{lightness:JM(0,1,s.lightness-parseFloat(e))}))})),ZM((function(e,t){if("transparent"===t)return t;var s=GM(t);return KM(vM({},s,{saturation:JM(0,1,s.saturation-parseFloat(e))}))})),ZM((function(e,t){if("transparent"===t)return t;var s=GM(t);return KM(vM({},s,{lightness:JM(0,1,s.lightness+parseFloat(e))}))}));var eN=ZM((function(e,t,s){if("transparent"===t)return s;if("transparent"===s)return t;if(0===e)return s;var i=VM(t),r=vM({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),n=VM(s),a=vM({},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 YM({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))})})),tN=eN;var sN=ZM((function(e,t){if("transparent"===t)return t;var s=VM(t);return YM(vM({},s,{alpha:JM(0,1,(100*("number"==typeof s.alpha?s.alpha:1)+100*parseFloat(e))/100)}))})),iN=sN;ZM((function(e,t){if("transparent"===t)return t;var s=GM(t);return KM(vM({},s,{saturation:JM(0,1,s.saturation+parseFloat(e))}))})),ZM((function(e,t){return"transparent"===t?t:KM(vM({},GM(t),{hue:parseFloat(e)}))})),ZM((function(e,t){return"transparent"===t?t:KM(vM({},GM(t),{lightness:parseFloat(e)}))})),ZM((function(e,t){return"transparent"===t?t:KM(vM({},GM(t),{saturation:parseFloat(e)}))})),ZM((function(e,t){return"transparent"===t?t:tN(parseFloat(e),"rgb(0, 0, 0)",t)})),ZM((function(e,t){return"transparent"===t?t:tN(parseFloat(e),"rgb(255, 255, 255)",t)})),ZM((function(e,t){if("transparent"===t)return t;var s=VM(t);return YM(vM({},s,{alpha:JM(0,1,+(100*("number"==typeof s.alpha?s.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}));var rN=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-rN.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*rN.Bounce.In(2*e):.5*rN.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}}}}),nN=function(){return performance.now()},aN=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=nN()),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}(),oN={Linear:function(e,t){var s=e.length-1,i=s*t,r=Math.floor(i),n=oN.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}}},hN=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),lN=new aN,uN=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=rN.Linear.None,this._interpolationFunction=oN.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=hN.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=lN,lN.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=nN()),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=nN()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=nN()),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=rN.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=oN.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=nN()),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}();hN.nextId;var cN=lN;cN.getAll.bind(cN),cN.removeAll.bind(cN),cN.add.bind(cN),cN.remove.bind(cN),cN.update.bind(cN);function dN(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var pN="object"==typeof global&&global&&global.Object===Object&&global,mN="object"==typeof self&&self&&self.Object===Object&&self,gN=pN||mN||Function("return this")(),fN=function(){return gN.Date.now()},yN=/\s/;var bN=/^\s+/;function xN(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&yN.test(e.charAt(t)););return t}(e)+1).replace(bN,""):e}var _N=gN.Symbol,vN=Object.prototype,TN=vN.hasOwnProperty,wN=vN.toString,SN=_N?_N.toStringTag:void 0;var MN=Object.prototype.toString;var NN=_N?_N.toStringTag:void 0;function EN(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":NN&&NN in Object(e)?function(e){var t=TN.call(e,SN),s=e[SN];try{e[SN]=void 0;var i=!0}catch(e){}var r=wN.call(e);return i&&(t?e[SN]=s:delete e[SN]),r}(e):function(e){return MN.call(e)}(e)}var AN=/^[-+]0x[0-9a-f]+$/i,CN=/^0b[01]+$/i,RN=/^0o[0-7]+$/i,PN=parseInt;function FN(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]"==EN(e)}(e))return NaN;if(dN(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=dN(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=xN(e);var s=CN.test(e);return s||RN.test(e)?PN(e.slice(2),s?2:8):AN.test(e)?NaN:+e}var IN=Math.max,BN=Math.min;function LN(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=fN();if(m(e))return f(e);o=setTimeout(g,function(e){var s=t-(e-h);return c?BN(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=fN(),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=FN(t)||0,dN(s)&&(u=!!s.leading,n=(c="maxWait"in s)?IN(FN(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(fN())},y}function DN(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 ON(e,t,s){return Object.defineProperty(e,"prototype",{writable:!1}),e}function kN(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 DN(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)?DN(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 UN=ON((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 zN(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 UN(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=LN((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=kN(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 VN="http://www.w3.org/1999/xhtml",GN={svg:"http://www.w3.org/2000/svg",xhtml:VN,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function jN(e){var t=e+="",s=t.indexOf(":");return s>=0&&"xmlns"!==(t=e.slice(0,s))&&(e=e.slice(s+1)),GN.hasOwnProperty(t)?{space:GN[t],local:e}:e}function HN(e){return function(){var t=this.ownerDocument,s=this.namespaceURI;return s===VN&&t.documentElement.namespaceURI===VN?t.createElement(e):t.createElementNS(s,e)}}function WN(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function $N(e){var t=jN(e);return(t.local?WN:HN)(t)}function qN(){}function XN(e){return null==e?qN:function(){return this.querySelector(e)}}function YN(){return[]}function KN(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function QN(e){return function(t){return t.matches(e)}}var ZN=Array.prototype.find;function JN(){return this.firstElementChild}var eE=Array.prototype.filter;function tE(){return Array.from(this.children)}function sE(e){return new Array(e.length)}function iE(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function rE(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 iE(e,n[o]);for(;o<h;++o)(a=t[o])&&(r[o]=a)}function nE(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 iE(e,n[o]);for(o=0;o<c;++o)(h=t[o])&&u.get(p[o])===h&&(r[o]=h)}function aE(e){return e.__data__}function oE(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function hE(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function lE(e){return function(){this.removeAttribute(e)}}function uE(e){return function(){this.removeAttributeNS(e.space,e.local)}}function cE(e,t){return function(){this.setAttribute(e,t)}}function dE(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function pE(e,t){return function(){var s=t.apply(this,arguments);null==s?this.removeAttribute(e):this.setAttribute(e,s)}}function mE(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 gE(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function fE(e){return function(){this.style.removeProperty(e)}}function yE(e,t,s){return function(){this.style.setProperty(e,t,s)}}function bE(e,t,s){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,s)}}function xE(e){return function(){delete this[e]}}function _E(e,t){return function(){this[e]=t}}function vE(e,t){return function(){var s=t.apply(this,arguments);null==s?delete this[e]:this[e]=s}}function TE(e){return e.trim().split(/^|\s+/)}function wE(e){return e.classList||new SE(e)}function SE(e){this._node=e,this._names=TE(e.getAttribute("class")||"")}function ME(e,t){for(var s=wE(e),i=-1,r=t.length;++i<r;)s.add(t[i])}function NE(e,t){for(var s=wE(e),i=-1,r=t.length;++i<r;)s.remove(t[i])}function EE(e){return function(){ME(this,e)}}function AE(e){return function(){NE(this,e)}}function CE(e,t){return function(){(t.apply(this,arguments)?ME:NE)(this,e)}}function RE(){this.textContent=""}function PE(e){return function(){this.textContent=e}}function FE(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function IE(){this.innerHTML=""}function BE(e){return function(){this.innerHTML=e}}function LE(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function DE(){this.nextSibling&&this.parentNode.appendChild(this)}function OE(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function kE(){return null}function UE(){var e=this.parentNode;e&&e.removeChild(this)}function zE(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function VE(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function GE(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 jE(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 HE(e,t,s){var i=gE(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 WE(e,t){return function(){return HE(this,e,t)}}function $E(e,t){return function(){return HE(this,e,t.apply(this,arguments))}}iE.prototype={constructor:iE,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)}},SE.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 qE=[null];function XE(e,t){this._groups=e,this._parents=t}XE.prototype={constructor:XE,select:function(e){"function"!=typeof e&&(e=XN(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 XE(i,this._parents)},selectAll:function(e){e="function"==typeof e?KN(e):function(e){return null==e?YN: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 XE(i,r)},selectChild:function(e){return this.select(null==e?JN:function(e){return function(){return ZN.call(this.children,e)}}("function"==typeof e?e:QN(e)))},selectChildren:function(e){return this.selectAll(null==e?tE:function(e){return function(){return eE.call(this.children,e)}}("function"==typeof e?e:QN(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 XE(i,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,aE);var s=t?nE:rE,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=oE(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,x=0,_=0;x<m;++x)if(y=g[x]){for(x>=_&&(_=x+1);!(b=f[_])&&++_<m;);y._next=b||null}}return(a=new XE(a,i))._enter=o,a._exit=h,a},enter:function(){return new XE(this._enter||this._groups.map(sE),this._parents)},exit:function(){return new XE(this._exit||this._groups.map(sE),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 XE(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=hE);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 XE(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=jN(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?uE:lE:"function"==typeof t?s.local?mE:pE:s.local?dE:cE)(s,t))},style:function(e,t,s){return arguments.length>1?this.each((null==t?fE:"function"==typeof t?bE:yE)(e,t,null==s?"":s)):function(e,t){return e.style.getPropertyValue(t)||gE(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?xE:"function"==typeof t?vE:_E)(e,t)):this.node()[e]},classed:function(e,t){var s=TE(e+"");if(arguments.length<2){for(var i=wE(this.node()),r=-1,n=s.length;++r<n;)if(!i.contains(s[r]))return!1;return!0}return this.each(("function"==typeof t?CE:t?EE:AE)(s,t))},text:function(e){return arguments.length?this.each(null==e?RE:("function"==typeof e?FE:PE)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?IE:("function"==typeof e?LE:BE)(e)):this.node().innerHTML},raise:function(){return this.each(DE)},lower:function(){return this.each(OE)},append:function(e){var t="function"==typeof e?e:$N(e);return this.select((function(){return this.appendChild(t.apply(this,arguments))}))},insert:function(e,t){var s="function"==typeof e?e:$N(e),i=null==t?kE:"function"==typeof t?t:XN(t);return this.select((function(){return this.insertBefore(s.apply(this,arguments),i.apply(this,arguments)||null)}))},remove:function(){return this.each(UE)},clone:function(e){return this.select(e?VE:zE)},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?jE:GE,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?$E:WE)(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 YE,KE,QE,ZE,JE,eA,tA,sA,iA,rA,nA,aA,oA={},hA=[],lA=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,uA=Array.isArray;function cA(e,t){for(var s in t)e[s]=t[s];return e}function dA(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function pA(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?++QE:r,__i:-1,__u:0};return null==r&&null!=KE.vnode&&KE.vnode(n),n}function mA(e){return e.children}function gA(e,t){this.props=e,this.context=t}function fA(e,t){if(null==t)return e.__?fA(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?fA(e):null}function yA(e){var t,s;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(s=e.__k[t])&&null!=s.__e){e.__e=e.__c.base=s.__e;break}return yA(e)}}function bA(e){(!e.__d&&(e.__d=!0)&&JE.push(e)&&!xA.__r++||eA!=KE.debounceRendering)&&((eA=KE.debounceRendering)||tA)(xA)}function xA(){for(var e,t,s,i,r,n,a,o=1;JE.length;)JE.length>o&&JE.sort(sA),e=JE.shift(),o=JE.length,e.__d&&(s=void 0,r=(i=(t=e).__v).__e,n=[],a=[],t.__P&&((s=cA({},i)).__v=i.__v+1,KE.vnode&&KE.vnode(s),EA(t.__P,s,i,t.__n,t.__P.namespaceURI,32&i.__u?[r]:null,n,null==r?fA(i):r,!!(32&i.__u),a),s.__v=i.__v,s.__.__k[s.__i]=s,AA(n,s,a),s.__e!=r&&yA(s)));xA.__r=0}function _A(e,t,s,i,r,n,a,o,h,l,u){var c,d,p,m,g,f,y=i&&i.__k||hA,b=t.length;for(h=vA(s,t,y,h,b),c=0;c<b;c++)null!=(p=s.__k[c])&&(d=-1==p.__i?oA:y[p.__i]||oA,p.__i=c,f=EA(e,p,d,r,n,a,o,h,l,u),m=p.__e,p.ref&&d.ref!=p.ref&&(d.ref&&PA(d.ref,null,p),u.push(p.ref,p.__c||m,p)),null==g&&null!=m&&(g=m),4&p.__u||d.__k===p.__k?h=TA(p,h,e):"function"==typeof p.type&&void 0!==f?h=f:m&&(h=m.nextSibling),p.__u&=-7);return s.__e=g,h}function vA(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?(h=n+d,(a=e.__k[n]="string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?pA(null,a,null,null,null):uA(a)?pA(mA,{children:a},null,null,null):null==a.constructor&&a.__b>0?pA(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=e,a.__b=e.__b+1,o=null,-1!=(l=a.__i=wA(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=fA(o)),FA(o,o));return i}function TA(e,t,s){var i,r;if("function"==typeof e.type){for(i=e.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=e,t=TA(i[r],t,s));return t}e.__e!=t&&(t&&e.type&&!s.contains(t)&&(t=fA(e)),s.insertBefore(e.__e,t||null),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function wA(e,t,s,i){var r,n,a=e.key,o=e.type,h=t[s];if(null===h&&null==e.key||h&&a==h.key&&o==h.type&&!(2&h.__u))return s;if(i>(null==h||2&h.__u?0:1))for(r=s-1,n=s+1;r>=0||n<t.length;){if(r>=0){if((h=t[r])&&!(2&h.__u)&&a==h.key&&o==h.type)return r;r--}if(n<t.length){if((h=t[n])&&!(2&h.__u)&&a==h.key&&o==h.type)return n;n++}}return-1}function SA(e,t,s){"-"==t[0]?e.setProperty(t,null==s?"":s):e[t]=null==s?"":"number"!=typeof s||lA.test(t)?s:s+"px"}function MA(e,t,s,i,r){var n;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||SA(e.style,t,"");if(s)for(t in s)i&&s[t]==i[t]||SA(e.style,t,s[t])}else if("o"==t[0]&&"n"==t[1])n=t!=(t=t.replace(iA,"$1")),t=t.toLowerCase()in e||"onFocusOut"==t||"onFocusIn"==t?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+n]=s,s?i?s.u=i.u:(s.u=rA,e.addEventListener(t,n?aA:nA,n)):e.removeEventListener(t,n?aA:nA,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 NA(e){return function(t){if(this.l){var s=this.l[t.type+e];if(null==t.t)t.t=rA++;else if(t.t<s.u)return;return s(KE.event?KE.event(t):t)}}}function EA(e,t,s,i,r,n,a,o,h,l){var u,c,d,p,m,g,f,y,b,x,_,v,T,w,S,M,N,E=t.type;if(null!=t.constructor)return null;128&s.__u&&(h=!!(32&s.__u),n=[o=t.__e=s.__e]),(u=KE.__b)&&u(t);e:if("function"==typeof E)try{if(y=t.props,b="prototype"in E&&E.prototype.render,x=(u=E.contextType)&&i[u.__c],_=u?x?x.props.value:u.__:i,s.__c?f=(c=t.__c=s.__c).__=c.__E:(b?t.__c=c=new E(y,_):(t.__c=c=new gA(y,_),c.constructor=E,c.render=IA),x&&x.sub(c),c.props=y,c.state||(c.state={}),c.context=_,c.__n=i,d=c.__d=!0,c.__h=[],c._sb=[]),b&&null==c.__s&&(c.__s=c.state),b&&null!=E.getDerivedStateFromProps&&(c.__s==c.state&&(c.__s=cA({},c.__s)),cA(c.__s,E.getDerivedStateFromProps(y,c.__s))),p=c.props,m=c.state,c.__v=t,d)b&&null==E.getDerivedStateFromProps&&null!=c.componentWillMount&&c.componentWillMount(),b&&null!=c.componentDidMount&&c.__h.push(c.componentDidMount);else{if(b&&null==E.getDerivedStateFromProps&&y!==p&&null!=c.componentWillReceiveProps&&c.componentWillReceiveProps(y,_),!c.__e&&null!=c.shouldComponentUpdate&&!1===c.shouldComponentUpdate(y,c.__s,_)||t.__v==s.__v){for(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)})),v=0;v<c._sb.length;v++)c.__h.push(c._sb[v]);c._sb=[],c.__h.length&&a.push(c);break e}null!=c.componentWillUpdate&&c.componentWillUpdate(y,c.__s,_),b&&null!=c.componentDidUpdate&&c.__h.push((function(){c.componentDidUpdate(p,m,g)}))}if(c.context=_,c.props=y,c.__P=e,c.__e=!1,T=KE.__r,w=0,b){for(c.state=c.__s,c.__d=!1,T&&T(t),u=c.render(c.props,c.state,c.context),S=0;S<c._sb.length;S++)c.__h.push(c._sb[S]);c._sb=[]}else do{c.__d=!1,T&&T(t),u=c.render(c.props,c.state,c.context),c.state=c.__s}while(c.__d&&++w<25);c.state=c.__s,null!=c.getChildContext&&(i=cA(cA({},i),c.getChildContext())),b&&!d&&null!=c.getSnapshotBeforeUpdate&&(g=c.getSnapshotBeforeUpdate(p,m)),M=u,null!=u&&u.type===mA&&null==u.key&&(M=CA(u.props.children)),o=_A(e,uA(M)?M:[M],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(N=n.length;N--;)dA(n[N]);else t.__e=s.__e,t.__k=s.__k;KE.__e(e,t,s)}else null==n&&t.__v==s.__v?(t.__k=s.__k,t.__e=s.__e):o=t.__e=RA(s.__e,t,s,i,r,n,a,h,l);return(u=KE.diffed)&&u(t),128&t.__u?void 0:o}function AA(e,t,s){for(var i=0;i<s.length;i++)PA(s[i],s[++i],s[++i]);KE.__c&&KE.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){KE.__e(e,t.__v)}}))}function CA(e){return"object"!=typeof e||null==e||e.__b&&e.__b>0?e:uA(e)?e.map(CA):cA({},e)}function RA(e,t,s,i,r,n,a,o,h){var l,u,c,d,p,m,g,f=s.props,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&&(KE.__m&&KE.__m(t,n),o=!1),n=null}if(null==b)f===y||o&&e.data==y||(e.data=y);else{if(n=n&&YE.call(e.childNodes),f=s.props||oA,!o&&null!=n)for(f={},l=0;l<e.attributes.length;l++)f[(p=e.attributes[l]).name]=p.value;for(l in f)if(p=f[l],"children"==l);else if("dangerouslySetInnerHTML"==l)c=p;else if(!(l in y)){if("value"==l&&"defaultValue"in y||"checked"==l&&"defaultChecked"in y)continue;MA(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||MA(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=""),_A("template"==t.type?e.content:e,uA(d)?d:[d],t,s,i,"foreignObject"==b?"http://www.w3.org/1999/xhtml":r,n,a,n?n[0]:s.__k&&fA(s,0),o,h),null!=n)for(l=n.length;l--;)dA(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])&&MA(e,l,m,f[l],r),l="checked",null!=g&&g!=e[l]&&MA(e,l,g,f[l],r))}return e}function PA(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){KE.__e(e,s)}}function FA(e,t,s){var i,r;if(KE.unmount&&KE.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||PA(i,null,t)),null!=(i=e.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(e){KE.__e(e,t)}i.base=i.__P=null}if(i=e.__k)for(r=0;r<i.length;r++)i[r]&&FA(i[r],t,s||"function"!=typeof e.type);s||dA(e.__e),e.__c=e.__=e.__e=void 0}function IA(e,t,s){return this.constructor(e,s)}function BA(e,t,s){var i,r,n;t==document&&(t=document.documentElement),KE.__&&KE.__(e,t),i=!1?null:t.__k,r=[],n=[],EA(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?YE.call(arguments,2):s),"function"==typeof e&&null!=e.defaultProps)for(n in e.defaultProps)null==a[n]&&(a[n]=e.defaultProps[n]);return pA(e,a,i,r,null)}(mA,null,[e]),i||oA,oA,t.namespaceURI,i?null:t.firstChild?YE.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,n),AA(r,e,n)}function LA(e,t,s){var i,r,n,a,o=cA({},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]=null==t[n]&&null!=a?a[n]:t[n];return arguments.length>2&&(o.children=arguments.length>3?YE.call(arguments,2):s),pA(e.type,o,i||e.key,r||e.ref,null)}function DA(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 OA(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 kA(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 UA(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 DA(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)?DA(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 zA(e){return zA="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},zA(e)}YE=hA.slice,KE={__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}},QE=0,ZE=function(e){return null!=e&&null==e.constructor},gA.prototype.setState=function(e,t){var s;s=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=cA({},this.state),"function"==typeof e&&(e=e(cA({},s),this.props)),e&&cA(s,e),null!=e&&this.__v&&(t&&this._sb.push(t),bA(this))},gA.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),bA(this))},gA.prototype.render=mA,JE=[],tA="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,sA=function(e,t){return e.__v.__b-t.__v.__b},xA.__r=0,iA=/(PointerCapture)$|Capture$/i,rA=0,nA=NA(!1),aA=NA(!0);var VA=function(e){if("object"!==zA(e))return e;var t,s=LA(e);s.props&&(s.props=function(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?kA(Object(s),!0).forEach((function(t){OA(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):kA(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(VA):VA(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 GA=zN({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 XE([[document.querySelector(e)]],[document.documentElement]):new XE([[e]],qE)}(!!e&&"object"===zA(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=UA(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 ZE(LA(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,BA(VA(t),s)):e.tooltipEl.text("")}}),jA=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,Clock:e.Clock},HA=zN({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.clock.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 uN(o).to(n,i).easing(rN.Quadratic.Out).onUpdate(l).start()),e.tweenGroup.add(new uN(h).to(a,i/3).easing(rN.Quadratic.Out).onUpdate(u).start())}else l(n),u(a);return this}return Object.assign({},r.position,{lookAt:c()});function l(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 u(t){var s=new jA.Vector3(t.x,t.y,t.z);e.controls.target?e.controls.target=s:r.lookAt(s)}function c(){return Object.assign(new jA.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 jA.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 jA.Box3(new jA.Vector3(0,0,0),new jA.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 jA.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 jA.Vector2(t/e.width*2-1,-s/e.height*2+1),n=new jA.Raycaster;return n.setFromCamera(r,e.camera),Object.assign({},n.ray.at(i,new jA.Vector3))},intersectingObjects:function(e,t,s){var i=new jA.Vector2(t/e.width*2-1,-s/e.height*2+1),r=new jA.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}},stateInit:function(){return{scene:new jA.Scene,camera:new jA.PerspectiveCamera,clock:new jA.Clock,tweenGroup:new aN,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 GA(t.container),t.pointerPos=new jA.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)&&("touch"!==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=!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?Vw:jA.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 xM(t.renderer),t.postProcessingComposer.addPass(new _M(t.scene,t.camera)),t.controls=new{trackball:hS,orbit:zS,fly:sM}[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 jA.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 jA.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=VM(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new jA.Color(iN(1,e.backgroundColor)),c)}function d(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new jA.TextureLoader).load(e.backgroundImageUrl,(function(t){t.colorSpace=jA.SRGBColorSpace,e.skysphere.material=new jA.MeshBasicMaterial({map:t,side:jA.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 HA}));